From 62ffc40169244becec8d4ff7f4fe62a8b6ef2c89 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 2 Nov 2026 03:40:11 +0800 Subject: [PATCH] gateway: a waiting request goes to an account back from rest (01huadalang) 01huadalang on Discord (11-01): three ZCode accounts, three requests at once each. The first two got a 405 and rested, so every request went to the third, and those over its three waited in its lane. Once the first two were back, the waiting ones stayed on the third, behind its long turns, until its requests were cut by hand. Same under Smart, In turn and Stays off. Cause: a request that queued in a lane (lanes.take) waited only for that lane's turn. Nothing looked again when another lane gave a slot back or a rest ended. With ZCode's maxAccounts 2, the third took a seat while the first two rested and was a reserve again once they were back, but the requests already waiting for it stayed. laneMate also gave way to a mate resting, because ready() checks only lane and RPM room. Change: - lanes.take takes a move func. While waiting (lanes.await), it looks again when any lane gives a slot back, when a rest is lifted (Unrest, UnrestAll signal lanes.freed), when the soonest rest among the others ends, and at least every 5s (laneRecheck). waitMate finds the first candidate after it in the planned order (then those probeOne left out for resting) of the same provider, or any member of a group, that has a free slot with no queue (tryTake), minute room, isn't resting, didn't give way, and isn't a reserve as keepAtOnce stands now. The request then leaves its queue (errMoved) and serve runs that candidate with the slot already taken for it. A fallback provider is never one. Strict stays leave no other candidate, so nothing changes there. - laneMate skips resting mates. - docs/subsystems/gateway-routing.md Limits row says so. Tests: - TestWaitingRequestGoesToAccountBackFromRest: 3 keys, cap 3, MaxAccounts 2, k1 and k2 resting (405), 9 requests. 3 go to k3, 6 wait for it, and none reach the resting two. Then the rests are lifted (Unrest) or run out (300ms), and the six go to k1 and k2 while k3's three are still out (9 at once). Run under Smart and Rotate, with Stays default and off. - TestWaitingRequestTakesSlotGivenBackElsewhere: 2 keys, cap 1. A third request waiting for one key goes to the other when that one's request ends, under default, order, rotate and usage routing. - TestFullMemberGivesWay updated. c, waiting for first, now goes to second once second's b ends. d (first's fallback is second) still waits for first. Run on mote (mote-run), rebased on e65bc8473: - go test -count=1 -timeout 45m ./internal/gateway: every test ok except TestCodexPoolSaysTheClientsVersion (608s; #4807, below) - go vet ./internal/gateway, GOOS=linux (-tags nogui), GOOS=windows: ok - gofmt -l: clean - go test -race -count=10 on the three tests above: ok - That red is #4807, also the only red in an earlier full run (it passes alone, here and on origin/main e65bc8473; another test's Codex version reaches it). Rebased again on 6b3a6d42c (VS Code agent host, gateway.go): at this head, vet for darwin, linux and windows ok, gofmt clean, and go test -run 'Lane|Waiting|FullMember|AtOnce|VSCode|Vscode|AgentHost|Concurrency| Queue|Rest|Probe|Affinity' ./internal/gateway ok (44s). Broken by hand: - On origin/main's code, the new tests and the updated TestFullMemberGivesWay are red. The rest test fails at "six waiting for k3" because laneMate handed requests to the resting keys. - With waitMate's move ignored (if ok && false), every case is red at "the waiting ones at k1 and k2", and so is TestWaitingRequestTakesSlot- GivenBackElsewhere. - With the rest's end ignored for the recheck timer (only laneRecheck), the four "ran out" cases are red. - Two test races were found under -race and fixed in the test: the rest was timed from before the nine were sent, and the concurrency count was read before the ninth reached the fake vendor. Not tried: real ZCode accounts or the ZCode plugin. The plugin's own 405 handling and maxAccounts are as before. Not run on Windows or Linux machines; vet only. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/concurrency.go | 250 +++++++++++++++++-- internal/gateway/concurrency_account_test.go | 19 +- internal/gateway/gateway.go | 70 +++++- internal/gateway/lane_moves_test.go | 196 +++++++++++++++ internal/gateway/routing.go | 2 + 6 files changed, 517 insertions(+), 22 deletions(-) create mode 100644 internal/gateway/lane_moves_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index aa44ba7fe..c652a164f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -35,7 +35,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | A model's own id at a provider | A model the user lists by an id of theirs at a provider (a signed-in account's and a plugin's too; settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log, recent calls and the Routing page keep as `served`; the agent gets the id it asked for back in the reply, in every protocol, streamed or whole (`memberWriter` in [`member.go`](../../internal/gateway/member.go), `replyNamingOf`: the reply's `model`, Responses' `response.model`, Anthropic's `message.model`, Gemini's `modelVersion`; issennknight on Discord, whose agent warned that `deepseek-v4.1-flash` came back as `deepseek-v4.1-flash-1017`). The same holds for a group or a `provider/model` id the vendor knows by another name. A reply whose vendor sent the wire name as asked keeps the vendor's name (a dated `-20261017` included); `memberModel` names the group's member instead, and `X-Magpie-Response-Model: vendor` keeps the vendor's name always (`TestReplyNamesAskedModel`, `TestGeminiReplyNamesAskedModel`, `TestReplyNamesMember`). A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's `--model`, Antigravity's variant, and which accounts list it and at what levels (`TestLocalModelIDAtAPlugin`, `TestLocalModelIDAtAClaudeAccount`, `TestLocalModelIDAtAnAntigravityAccount`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Weekly pace, Free first, Speed first, a plugin's) takes the outer group's, as a provider left on the default does (`provider.Group.Within`, set on `Member.Via`, so the trace's `Subs` and the Routing page read the routing that applies, #3847). In a group In order, By weight or Manual it stays Smart. `TestFreeFirstReachesAGroupInItLeftOnTheDefault`. So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first), `drain` (until used up) or, a group's only, `cheap` (cheapest first). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models, each at DeepSeek's hours; Ollama Cloud's deepseek-v4.1-flash and deepseek-v4-pro, dated tags too, at its own 12:00–18:00 UTC weekdays, `catalog.PeakOllama`). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour, and `TestCheapestFirstGroupFollowsOllamaOffPeak` at each edge of Ollama Cloud's hours, a Saturday, and in far zones. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). `drain` (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back once it renews) stays on one seat per pool (`routes.Drain`, which remembers the seat's `Key` per pool) until it is used up — a known window at 100% (`provider.SpentShareOf`, as In order) or resting out of quota or credit (`routes.Seat.Spent`, filled by `spentRest` from `restingOf`'s `failQuota`/`failCredit`) — then goes on to the next not used up in listed order and stays there, wrapping round; the others follow it in listed order for failover. A rate limit or a failure only rests the seat, tried last meanwhile, and the pool comes back to it; with every seat used up it stays put, and a seat that leaves the pool leaves it on the first not used up. A group routed `drain` pools its members' accounts and keys under `group/`, as Smart does. A restart forgets where each pool was, and it starts again at the first not used up (`TestDrainKeepsTheOneThatTookOver`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | -| Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | +| Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`) that isn't resting: its lane is free only because nothing is sent there. A request already waiting in a lane doesn't stay bound to it: whenever a slot is given back in any lane or a rest is lifted (`lanes.freed`, signalled by the releaser, `Unrest` and `UnrestAll`), and when the soonest rest among the others runs out (at most every `laneRecheck`), it goes to the first key or account after it in the planned order that has a free slot with no queue, minute room, isn't resting and isn't a reserve now (`waitMate`, `keepAtOnce` re-derived over the provider's candidates, `errMoved`). So one that took a seat while those before it rested, then became a reserve once they were back, doesn't keep requests waiting behind its own long turns (01huadalang on Discord: three ZCode accounts at three at once, the first two back from a 405 while the waiting ones stayed on the third until its requests were cut by hand; `TestWaitingRequestGoesToAccountBackFromRest` under Smart and In turn, with Stays on and off, `TestWaitingRequestTakesSlotGivenBackElsewhere` under every routing). Strict stays leaves no other candidate, so the request waits for its own. A fallback is never asked for want of a slot or a minute (`TestFullMemberGivesWay`). A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | diff --git a/internal/gateway/concurrency.go b/internal/gateway/concurrency.go index 582e5f8af..1eccbd177 100644 --- a/internal/gateway/concurrency.go +++ b/internal/gateway/concurrency.go @@ -31,6 +31,48 @@ import ( type lanes struct { mu sync.Mutex m map[string]*lane + // freed is closed, and made afresh, each time a slot of any lane is + // given back or a rest is lifted (signal): a request waiting in one + // lane looks then for another with room (waitMate) + freed chan struct{} +} + +// signalLocked wakes every request waiting in a lane to look for another +// with room. l.mu is held. +func (l *lanes) signalLocked() { + if l.freed != nil { + close(l.freed) + l.freed = nil + } +} + +// signal is signalLocked, taking l.mu. +func (l *lanes) signal() { + l.mu.Lock() + l.signalLocked() + l.mu.Unlock() +} + +// tryTake takes one of who's slots if one is free now and nobody waits +// for it: no limit, or room. false takes none. +func (l *lanes) tryTake(who string, limit int) (release func(), ok bool) { + l.mu.Lock() + defer l.mu.Unlock() + if l.m == nil { + l.m = map[string]*lane{} + } + ln := l.m[who] + if ln == nil { + ln = &lane{} + l.m[who] = ln + } + if limit > 0 && (ln.busy >= limit || len(ln.queue) > 0) { + l.drop(who, ln) + return nil, false + } + ln.limit = max(limit, 0) + ln.busy++ + return l.releaser(who, ln), true } // lane is one key's or account's: how many are out, and who waits, first @@ -53,11 +95,20 @@ type lane struct { // // A full one gives way first. Where the request has another key or // account of the same provider, or another member of its routing group, -// with a slot free now, that one is asked first and the full one keeps its -// place after it (laneMate): a group spreads its requests over members -// with room before any waits. A fallback provider is never asked for want -// of a slot — it is another vendor, often a paid one — and a request whose -// keys and accounts are all full waits for the one routing chose. +// with a slot free now and not resting, that one is asked first and the +// full one keeps its place after it (laneMate): a group spreads its +// requests over members with room before any waits. A fallback provider is +// never asked for want of a slot — it is another vendor, often a paid one +// — and a request whose keys and accounts are all full waits in the queue +// of the one routing chose, but not for it alone: each time a slot of any +// lane is given back (lanes.freed), a rest of one of the others ends or is +// lifted, it looks again, and the first of the others in routing's order +// with a slot free, not resting and not held back as a reserve as its +// provider's accounts stand now (waitMate) takes it, its slot taken for +// it as it leaves the queue (errMoved). 01huadalang on Discord: three +// ZCode accounts at three at once, the first two resting after a 405; once +// they were back, the requests already waiting for the third waited on +// behind its long turns, in every routing, until its own were cut by hand. // errQueueFull and errQueueWait turn a request away from a lane: its queue // at its bound, or the request waited as long as it may. @@ -66,12 +117,21 @@ var ( errQueueWait = errors.New("waited too long") ) +// errMoved is a request that left its lane's queue for another key or +// account with room (waitMate): nobody failed, and it is asked there. +var errMoved = errors.New("gave way to one with room") + +// laneRecheck is how often a request waiting in a lane looks again for +// another with room with nothing given back meanwhile: a minute's room +// (MaxRPM) comes back with nothing said. +const laneRecheck = 5 * time.Second + // acquire waits for one of who's limit slots, in turn, with no bound on // the queue or the wait. It answers the release, to call once the request // is done with the vendor, and false with no slot taken when ctx ended // first. A limit of 0 never waits; the request is only counted. func (l *lanes) acquire(ctx context.Context, who string, limit int) (release func(), ok bool) { - release, _, err := l.take(ctx, who, limit, 0, 0) + release, _, err := l.take(ctx, who, limit, 0, 0, nil) return release, err == nil } @@ -80,7 +140,11 @@ func (l *lanes) acquire(ctx context.Context, who string, limit int) (release fun // error when it ended first, with no slot taken. waited is how long it // stood in the queue: 0 when a slot was free at once or there is no // limit, so a request that never queued never reads as queued (#2153). -func (l *lanes) take(ctx context.Context, who string, limit, queue int, wait time.Duration) (release func(), waited time.Duration, err error) { +// move, when not nil, is asked while it waits — at once, each time a slot +// of any lane is given back, at the time it names and every laneRecheck — +// whether the request goes to another key or account instead (waitMate, +// which takes that one's slot): true leaves the queue with errMoved. +func (l *lanes) take(ctx context.Context, who string, limit, queue int, wait time.Duration, move func() (bool, time.Time)) (release func(), waited time.Duration, err error) { l.mu.Lock() if l.m == nil { l.m = map[string]*lane{} @@ -122,13 +186,9 @@ func (l *lanes) take(ctx context.Context, who string, limit, queue int, wait tim defer t.Stop() timeout = t.C } - select { - case <-ch: + err = l.await(ctx, ch, timeout, move) + if err == nil { return l.releaser(who, ln), time.Since(queued), nil - case <-ctx.Done(): - err = ctx.Err() - case <-timeout: - err = errQueueWait } waited = time.Since(queued) l.mu.Lock() @@ -144,9 +204,66 @@ func (l *lanes) take(ctx context.Context, who string, limit, queue int, wait tim ln.busy-- ln.grant() l.drop(who, ln) + l.signalLocked() return nil, waited, err } +// await waits for ch, the request's turn in its lane: nil then, else +// ctx's error, errQueueWait at timeout, or errMoved once move says it goes +// elsewhere. +func (l *lanes) await(ctx context.Context, ch chan struct{}, timeout <-chan time.Time, move func() (bool, time.Time)) error { + for { + var freed chan struct{} + var again <-chan time.Time + var t *time.Timer + if move != nil { + l.mu.Lock() + if l.freed == nil { + l.freed = make(chan struct{}) + } + freed = l.freed + l.mu.Unlock() + select { + case <-ch: + return nil // its turn came first: it goes where it waited + default: + } + ok, next := move() + if ok { + return errMoved + } + d := laneRecheck + if !next.IsZero() { + d = min(d, max(time.Until(next), time.Millisecond)) + } + t = time.NewTimer(d) + again = t.C + } + select { + case <-ch: + if t != nil { + t.Stop() + } + return nil + case <-ctx.Done(): + if t != nil { + t.Stop() + } + return ctx.Err() + case <-timeout: + if t != nil { + t.Stop() + } + return errQueueWait + case <-freed: + case <-again: + } + if t != nil { + t.Stop() + } + } +} + // free says whether a request for who would be sent at once: no limit, or // a slot free and nobody waiting for it. func (l *lanes) free(who string, limit int) bool { @@ -165,7 +282,10 @@ func (l *lanes) free(who string, limit int) bool { // full, or has sent its MaxRPM in the last minute; -1 when it isn't // full, gave way once already, or none has room. A reserve is never one // (keepAtOnce): it is held back for its provider not to be used from more -// accounts at once than it lets be, and a full lane is not a failure. +// accounts at once than it lets be, and a full lane is not a failure. Nor +// is one resting: its lane is free because it is resting, and a request +// handed to it for want of a slot would only ask it again before its rest +// is out. func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string]bool) int { c := cands[i] who := c.who() @@ -177,6 +297,9 @@ func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string] if m.who() == who || !group && m.p.ID != c.p.ID || m.reserve > 0 { continue } + if _, resting := restedUntil(m); resting { + continue + } if s.ready(m) { return j } @@ -184,6 +307,104 @@ func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string] return -1 } +// restedUntil is when c's rest ends, and whether it rests now: its key's +// or account's, else its model's (restingOf, without reading a key's +// allowance again). +func restedUntil(c candidate) (time.Time, bool) { + r, ok := restOf(c.restKey()) + if !ok && c.restID() != c.restKey() { + r, ok = restOf(c.restID()) + } + return r.Until, ok +} + +// waitMate is, for a request waiting in the full lane of cands[i], the +// first other candidate in routing's order that would take it now, with +// its slot taken for it (release): another key or account of cands[i]'s +// provider, or in a routing group any member, not tried yet by this +// request, not one that gave way (gave), not resting, with a slot free and +// room in its minute, and not held back as a reserve as its provider's +// accounts stand now (keepAtOnce over them as the rests are now, so a +// reserve that took a seat while the first rested gives it back once they +// are back). Those after i come first, then those of planned that probeOne +// left out for resting, back now. ok is false when none would; next is +// then when the soonest of those left out only for resting is back (zero +// for none), for the request to look again then. A fallback provider is +// never one, as with laneMate. +func (s *Server) waitMate(cands []candidate, i int, group bool, gave map[string]bool, planned []candidate) (mate candidate, release func(), next time.Time, ok bool) { + c := cands[i] + who := c.who() + seat := func(m candidate) string { return m.who() + "|" + m.model } + seen := map[string]bool{} + for _, m := range cands[:i+1] { + seen[seat(m)] = true + } + var pool []candidate + for _, m := range append(slices.Clone(cands[i+1:]), planned...) { + if !seen[seat(m)] { + seen[seat(m)] = true + pool = append(pool, m) + } + } + // the reserves of each provider of the pool with accounts at once, as + // its accounts' rests are now + reserves := map[string]map[string]bool{} + reserveNow := func(m candidate) bool { + k := m.p.ID + "|" + m.model + set, done := reserves[k] + if !done { + n := m.p.AtOnce() + if n > 0 { + var all []candidate + for _, o := range append(slices.Clone(cands), planned...) { + if o.p.ID == m.p.ID && o.model == m.model && !slices.ContainsFunc(all, func(a candidate) bool { return a.who() == o.who() }) { + all = append(all, o) + } + } + _, held := keepAtOnce(n, all, nil) + set = map[string]bool{} + for _, o := range held { + set[o.who()] = true + } + } + reserves[k] = set + } + return set[m.who()] + } + for _, m := range pool { + if m.who() == who || gave[m.who()] || !group && m.p.ID != c.p.ID { + continue + } + if until, resting := restedUntil(m); resting { + if next.IsZero() || until.Before(next) { + next = until + } + continue + } + if reserveNow(m) || !s.rpms.free(m.who(), m.p.RPMLimit()) { + continue + } + if rel, took := s.lanes.tryTake(m.who(), m.p.LaneLimit()); took { + m.reserve = 0 + return m, rel, time.Time{}, true + } + } + return candidate{}, nil, next, false +} + +// movedAhead is cands with m at i, ahead of the one there, which keeps its +// place after it, and m left out where it stood after i. +func movedAhead(cands []candidate, i int, m candidate) []candidate { + cs := slices.Clone(cands) + for j := i + 1; j < len(cs); j++ { + if cs[j].who() == m.who() && cs[j].model == m.model { + cs = slices.Delete(cs, j, j+1) + break + } + } + return slices.Insert(cs, i, m) +} + // dropReserves leaves out, of the candidates after i, the reserves of // provider id (keepAtOnce). func dropReserves(cands []candidate, i int, id string) []candidate { @@ -219,6 +440,7 @@ func (l *lanes) releaser(who string, ln *lane) func() { ln.busy-- ln.grant() l.drop(who, ln) + l.signalLocked() l.mu.Unlock() }) } diff --git a/internal/gateway/concurrency_account_test.go b/internal/gateway/concurrency_account_test.go index 4c5d0f48b..2740043c1 100644 --- a/internal/gateway/concurrency_account_test.go +++ b/internal/gateway/concurrency_account_test.go @@ -253,8 +253,10 @@ func TestLaneReleasedOnFailure(t *testing.T) { } // A full member of a routing group gives way to one with a slot free (no -// waiting while another member has room), while a provider's fallback is -// never asked for want of a slot: the request waits for its own. +// waiting while another member has room), and a request of the group +// waiting for one goes to another once that one has room again (waitMate), +// while a provider's fallback is never asked for want of a slot: the +// request waits for its own. func TestFullMemberGivesWay(t *testing.T) { fresh(t) v1, up1 := slowUp(t) @@ -292,11 +294,20 @@ func TestFullMemberGivesWay(t *testing.T) { if r := g.reply(); r.tag != "b" || !strings.Contains(r.body, "from b") { t.Fatalf("b = %+v", r) } - time.Sleep(50 * time.Millisecond) + // second has room again: c, waiting for first, goes there (waitMate); + // d, which second is only the fallback of, waits on for first + within(t, "c at second", func() bool { return slices.Contains(v2.seen(), "c") }) + if l := firstLane(); l.Waiting != 1 { + t.Fatalf("first's lane = %+v, want d alone waiting", l) + } if slices.Contains(v2.seen(), "d") { t.Fatal("d went to first's fallback for want of a slot") } - for _, tag := range []string{"a", "c", "d"} { + close(v2.gate("c")) + if r := g.reply(); r.tag != "c" || !strings.Contains(r.body, "[DONE]") { + t.Fatalf("c = %+v", r) + } + for _, tag := range []string{"a", "d"} { close(v1.gate(tag)) if r := g.reply(); r.tag != tag || !strings.Contains(r.body, "[DONE]") { t.Fatalf("%s = %+v", tag, r) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index aaf54e20d..04167db0f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2811,7 +2811,20 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if from == provider.Gemini { streams = strings.Contains(r.URL.Path, "streamGenerateContent") } - gaveWay := map[string]bool{} // keys and accounts that gave way, full, to one free (laneMate) + gaveWay := map[string]bool{} // keys and accounts that gave way, full, to one free (laneMate, waitMate) + // the slot a request waiting in a full lane took of the key or account + // it went to instead (waitMate), for that one's try; given back if it + // isn't the one tried next, or when serve ends with it unused + var handed struct { + who string + release func() + waited time.Duration // how long it waited where it was, the first try's + } + defer func() { + if handed.release != nil { + handed.release() + } + }() // a group's members that failed in a way that passes are asked again, // once each has been, for up to its Patience (#1418): a member of a // group in the group uses the innermost that sets Patience (#2410) @@ -2870,7 +2883,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro failedRow = nil } c := cands[i] - if j := s.laneMate(cands, i, isGroup, gaveWay); j > i { + if handed.release != nil && handed.who != c.who() { + handed.release() + handed.release = nil + } + if handed.release != nil { + // it holds a slot of this one already: no giving way + } else if j := s.laneMate(cands, i, isGroup, gaveWay); j > i { // its key or account is full, and another of its provider's, // or of its group, has a slot free: that one is asked first, // this one keeps its place after it (#892) @@ -3281,7 +3300,46 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // machine) // a streaming agent waiting is kept alive meanwhile queuedAlive := hw.keepQueued() - release, inLane, err := s.lanes.take(ctx, c.who(), c.p.LaneLimit(), c.p.QueueLimit, time.Duration(c.p.QueueWait)*time.Second) + var release func() + var inLane time.Duration + var err error + var mate candidate + if handed.release != nil { + // it left a full lane's queue for this one, whose slot it + // took as it did (waitMate): the wait there is its queue + release, handed.release = handed.release, nil + inLane, handed.waited = handed.waited, 0 + } else { + // waiting, it goes to the first other key or account with + // room, not resting, once there is one (01huadalang on + // Discord: the requests already waiting for a third ZCode + // account waited on once the first two were back) + release, inLane, err = s.lanes.take(ctx, c.who(), c.p.LaneLimit(), c.p.QueueLimit, time.Duration(c.p.QueueWait)*time.Second, func() (bool, time.Time) { + m, rel, next, ok := s.waitMate(cands, i, isGroup, gaveWay, all) + if !ok { + return false, next + } + mate, handed.who, handed.release = m, m.who(), rel + return true, time.Time{} + }) + } + if errors.Is(err, errMoved) { + // nothing was sent, and nobody failed: the one with room is + // asked now, this one keeps its place after it. The try + // never went out, so the route lists it no more + queuedAlive() + stop() + s.trace.update(tr, func(t *Route) { t.Tries = t.Tries[:len(t.Tries)-1] }) + if firstBegan.Equal(began) { + // the first try's wait is the next one's queue, not a + // failed try's time + firstBegan, handed.waited = time.Time{}, inLane + } + gaveWay[c.who()] = true + cands = movedAhead(cands, i, mate) + i-- + continue + } var inMinute time.Duration if err == nil && c.p.RPMLimit() > 0 { // with a MaxRPM, it then waits for room in the minute, and @@ -3314,6 +3372,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } stop() } + if handed.release != nil && handed.who == c.who() { + // answered without asking (verifyHeld, quotaHeld): the slot + // taken for it goes back + handed.release() + handed.release = nil + } if laneErr != nil { // its key's or account's queue was full, or it waited as long // as it may: nobody failed, and nobody rests; the next is diff --git a/internal/gateway/lane_moves_test.go b/internal/gateway/lane_moves_test.go new file mode 100644 index 000000000..5a78393ee --- /dev/null +++ b/internal/gateway/lane_moves_test.go @@ -0,0 +1,196 @@ +package gateway + +import ( + "context" + "fmt" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// 01huadalang on Discord (11-01): three ZCode accounts at three requests +// at once each, the first two resting after a 405. Every request went to +// the third, and those over its three waited in its queue; once the first +// two were back, the waiting ones waited on behind the third's long turns, +// under Smart, In turn and with Stays off alike, until its requests were +// cut by hand. A request waiting in a full lane goes to the first other +// key or account with room that isn't resting (waitMate) as soon as there +// is one: one back from its rest, lifted by hand (Try now) or run out. +// While they rest, the full lane gives way to neither (laneMate): its lane +// is free only because it rests. With two accounts at once (ZCode's +// plugin's maxAccounts), the third, which took a seat while the first two +// rested, is a reserve again once they are back, and those waiting for it +// go to the two. +func TestWaitingRequestGoesToAccountBackFromRest(t *testing.T) { + for _, mode := range []string{"", provider.Rotate} { + for _, aff := range []string{"", provider.AffinityOff} { + for _, lift := range []string{"lifted", "ran out"} { + t.Run(fmt.Sprintf("routing=%q/stays=%q/%s", mode, aff, lift), func(t *testing.T) { + waitingGoesBack(t, mode, aff, lift == "lifted") + }) + } + } + } +} + +func waitingGoesBack(t *testing.T, mode, aff string, lift bool) { + fresh(t) + v, _ := slowUp(t) + rec := &atOnceKeys{next: v} + up := httptest.NewServer(rec) + t.Cleanup(up.Close) + three, two := 3, 2 + if err := provider.Save(provider.Provider{ID: "zc", Name: "ZC", Key: "k1", Keys: []provider.KeyAccount{{Key: "k2"}, {Key: "k3"}}, Models: []string{"m"}, Chat: up.URL + "/v1", + Routing: mode, MaxConcurrency: &three, MaxAccounts: &two}); err != nil { + t.Fatal(err) + } + if aff != "" { + if err := provider.SetAffinity("zc", aff); err != nil { + t.Fatal(err) + } + } + key := func(k string) string { return "zc#" + provider.KeyID(k) } + // the first two rest after ZCode's 405 + restFor := func(d time.Duration) { + restingUntil.Lock() + for _, k := range []string{"k1", "k2"} { + restingUntil.m[key(k)] = time.Now().Add(d) + restingUntil.note[key(k)] = Rest{Why: failOther, Status: 405, Key: key(k)} + } + restingUntil.Unlock() + } + restFor(time.Hour) + + g := newLaneRig(t) + count := func(k string) int { + n := 0 + for _, got := range rec.seen() { + if got == k { + n++ + } + } + return n + } + waiting := func() int { + n := 0 + for _, l := range g.s.Lanes() { + n += l.Waiting + } + return n + } + tags := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i"} + for _, tag := range tags[:3] { + g.send(context.Background(), "/v1/chat/completions", "zc/m", tag) + } + within(t, "three out at k3", func() bool { return count("k3") == 3 }) + for _, tag := range tags[3:] { + g.send(context.Background(), "/v1/chat/completions", "zc/m", tag) + } + within(t, "six waiting for k3", func() bool { return g.s.Lanes()[key("k3")].Waiting == 6 }) + if n1, n2 := count("k1"), count("k2"); n1+n2 > 0 { + t.Fatalf("k1 asked %d, k2 %d while resting: a full lane gave way to one resting", n1, n2) + } + if lift { + g.s.Unrest(key("k1")) + g.s.Unrest(key("k2")) + } else { + // the rests now end in a moment, as if set so: the waiting ones + // look once more (as when they queued) and find them resting, so + // what moves them is the end itself, well before laneRecheck + restFor(300 * time.Millisecond) + g.s.lanes.signal() + } + // back: the six waiting go to the two, three each, at once, while + // the third's three are still out + within(t, "the waiting ones at k1 and k2", func() bool { return count("k1") == 3 && count("k2") == 3 && waiting() == 0 }) + if n := count("k3"); n != 3 { + t.Fatalf("k3 asked %d, want its three only", n) + } + // rec counts a request before it reaches v: all nine at v at once + within(t, "nine at the vendor", func() bool { return len(v.seen()) == 9 }) + for _, tag := range tags { + close(v.gate(tag)) + } + for range tags { + if r := g.reply(); r.err != nil || !strings.Contains(r.body, "[DONE]") { + t.Fatalf("reply %+v", r) + } + } + if v.most != 9 { + t.Fatalf("most out at once = %d, want 9: three on each", v.most) + } + within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 }) +} + +// A request waiting for a key whose slots are all out goes to another key +// of its provider once one of that one's is given back, under every +// routing, rather than waiting for the one it first queued for. The lane +// it goes to has no queue of its own: who waits there goes first. +func TestWaitingRequestTakesSlotGivenBackElsewhere(t *testing.T) { + for _, mode := range []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed} { + t.Run(fmt.Sprintf("routing=%q", mode), func(t *testing.T) { + fresh(t) + v, _ := slowUp(t) + rec := &atOnceKeys{next: v} + up := httptest.NewServer(rec) + t.Cleanup(up.Close) + one := 1 + if err := provider.Save(provider.Provider{ID: "two", Name: "Two", Key: "k1", Keys: []provider.KeyAccount{{Key: "k2"}}, Models: []string{"m"}, Chat: up.URL + "/v1", + Routing: mode, MaxConcurrency: &one}); err != nil { + t.Fatal(err) + } + g := newLaneRig(t) + waiting := func() int { + n := 0 + for _, l := range g.s.Lanes() { + n += l.Waiting + } + return n + } + g.send(context.Background(), "/v1/chat/completions", "two/m", "a") + within(t, "a out", func() bool { return len(v.seen()) == 1 }) + g.send(context.Background(), "/v1/chat/completions", "two/m", "b") + within(t, "b out", func() bool { return len(v.seen()) == 2 }) + g.send(context.Background(), "/v1/chat/completions", "two/m", "c") + within(t, "c waiting", func() bool { return waiting() == 1 }) + // whichever key c waits for, the other one's request ends + // first: c goes there + keys := rec.seen() + waitsFor := "" + for who, l := range g.s.Lanes() { + if l.Waiting == 1 { + waitsFor = who + } + } + end, other := "a", keys[0] // c waits for b's key: a's ends + if waitsFor == "two#"+provider.KeyID(keys[0]) { + end, other = "b", keys[1] // c waits for a's key: b's ends + } + close(v.gate(end)) + if r := g.reply(); r.tag != end { + t.Fatalf("reply %+v, want %s", r, end) + } + within(t, "c sent to "+other, func() bool { return len(v.seen()) == 3 }) + if got := rec.seen(); got[2] != other { + t.Fatalf("keys asked %v: c went to %s, want %s, the one whose slot was given back", got, got[2], other) + } + if n := waiting(); n != 0 { + t.Fatalf("%d still waiting", n) + } + for _, tag := range []string{"a", "b", "c"} { + if tag != end { + close(v.gate(tag)) + } + } + for range 2 { + if r := g.reply(); r.err != nil || !strings.Contains(r.body, "[DONE]") { + t.Fatalf("reply %+v", r) + } + } + within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 }) + }) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 584248283..f1f404c7a 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -837,6 +837,7 @@ func (s *Server) Unrest(key string) bool { } unsink(key) s.trace.lifted() + s.lanes.signal() // a request waiting in a full lane may go to it now (waitMate) return ok } @@ -862,6 +863,7 @@ func (s *Server) UnrestAll(key string) int { } unsinkAll(key) s.trace.lifted() + s.lanes.signal() // a request waiting in a full lane may go to it now (waitMate) return n }