Skip to content

fix(ai): let a small broker pool serve while an account cools down - #3794

Merged
yannickmonney merged 8 commits into
mainfrom
fix/broker-floor-held-fallback
Sep 29, 2026
Merged

yannickmonney merged 8 commits into
mainfrom
fix/broker-floor-held-fallback

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #3742 (TALE-82), from the post-merge review of a970418. Each finding was re-checked on main before it was changed; the high one reproduced as described.

What was wrong

  • [high] A small broker pool starved. The AI gateway's hand-out floor holds an account back while another account of its vendor can take the work, as the gateway sees it. The platform then applies rules the gateway cannot see: the shared 60-second cooldown after a 429, and OpenAI's required account_id.
    • Floor-held accounts arrived as available: false and were never selection candidates.
    • So a two-account pool, with A cooling down and B inside its refresh floor, threw CREDENTIAL_BROKER_EXHAUSTED (or CREDENTIAL_BROKER_EMPTY in the OpenAI case), and the immediate retries spent the whole budget in seconds.
  • [low] A free credential-rotation retry after a clean run showed "Auto-retry 1 of 3", and the next ordinary failure showed "Auto-retry 1 of 3" again, while the docs say the count does not advance.
  • [low] credential-rotation.integration.ts credited failure_code to migration 0132; it is 0133.

What changed

Gateway (services/ai-gateway). Every token now carries hold:

  • quota while its quota is spent (also when the floor holds it too);
  • refresh while only the hand-out floor holds it;
  • null while it is available.

available keeps its meaning, so a consumer that reads nothing else still skips a floor-held account. The README, .env.example and the manual reference say so.

Platform broker resolution.

  • diagnoseTokenMapping puts an account with available: false and hold: "refresh" into a separate heldAccounts list, as long as it passes every other filter (provider, account id, status, expiry, dedupe). The list is ordered by latest available_at first; for a refresh hold that is the gateway's refresh_at, so the token with the most life comes first. A quota hold, an unknown hold, or no hold at all stays excluded as before.
  • The pick (pickBrokerCandidate, extracted from selectBrokerAccount so it can be unit-tested) never takes a cooling account. It serves a held account only when no available account is out of its cooldown, never while one can serve (even one already tried this run). Held accounts go in the order given.
  • The resolver throws CREDENTIAL_BROKER_EMPTY only when both lists are empty, and logs when it vends a held account.
  • Rollout (platform before gateway): a gateway that does not send hold yet produces no held accounts, so behaviour is exactly as today. A unit test covers this.

All accounts cooling down: retry at retryAtMs. The cooldown refusal now carries retryAtMs (read with credentialRetryAtMs), and a start refused this way settles as credential_cooldown.

  • Task lane: the failed mark arms task.agent_retry with startAfterMs. The retry kicks the run at once, so the card shows it queued, while its task.agent_turn job is held in pg-boss until then.
  • Automation lane: the stepper's re-kick passes notBefore, and the host delays the start. The turn's time limit counts from the start, and the re-kick resumes the conversation the refused attempt was meant to resume.
  • Other start paths: a task's comment restart and an automation's answered-ask resume carry the moment the same way.
  • Cap: each wait is capped at the 60-second cooldown (BROKER_RATE_LIMIT_COOLDOWN_MS), well inside the stranded-run sweeps' 4-minute window.
  • What the wait costs:
    • It is free when the refused run was retrying the task's own 429. The 429 already counted, and waiting out its cooldown is the same event (freeCooldownWaits / retriedRateLimit).
    • Any other refused start counts, as does a second refusal in a row. Every free wait needs a counted 429 directly behind it, so a pool that other work keeps cooling cannot hold a run in an endless wait. This bound is written down in start_failure.ts, agent_retry.ts and the docs.
  • A start's credential refusal now shows its own sentence (runFailureMessage) instead of the serialized AppError payload, following the repo's "words, never payload" rule.

Free rotation caption. A free rotation's retry now shows what the run it replaces showed, so the count never advances or falls back. When that run showed no count, or worked at least fifteen minutes (which refreshed the budget, as the automation lane already stamps it), the stamp is 0 and the card reads Resumed after a token refresh (en, de, fr).

Run failure codes on the wire. credential_cooldown and credential_rotated are retry-only agent codes. When an automation run's budget runs out on them, Run.failureCode reports the code the same failure carried before this work: start_failed for a start a cooling pool refused, harness_error for a rotated 401. The OpenAPI enum does not change, and an agent code that is neither on the wire nor mapped fails to compile.

Docs (en/de/fr):

  • task automation: the caption, and the cooldown wait with its cost;
  • automation execution logs: the cooldown wait and resume;
  • self-hosted broker reference: the hold field, the fallback, and the wait;
  • admin providers: the fallback.

The platform and gateway manual references record the new behaviour. TASK-F47 judges the caption's layout in every locale, and ACCT-21 lists hold among the token fields.

How it was verified

  • Unit, UI and i18n suites for every changed module and everything that imports it, all passing:
    • 55 server test files (597 tests);
    • the task card UI test;
    • lib/i18n/messages.test.ts;
    • the gateway's accounts, routes and rollback tests;
    • the @tale/docs structural suite.
  • New tests cover:
    • the two-account pool with A cooling and B floor-held vending B, at three levels: pick, resolver and real Postgres;
    • the OpenAI account-id case, and an old gateway without hold;
    • held accounts ordered and filtered, ignoring the selection strategy;
    • the gateway's hold field, in the service and on the wire;
    • retryAtMs flowing through the task start, the comment restart, the automation start and the answered-ask resume, to a delayed arm, kick and scheduled start, including the cap;
    • the free wait after an own 429 versus a counted one, in both lanes;
    • resume continuity after a refused start;
    • the inherited stamp, and its caption.
  • Mutation check: each of 29 targeted mutations turned its test red. Examples: drop the held tier, prefer a held account over an excluded available one, drop or unclamp the delay, never free the wait, drop the resume carry-forward, restore the old max(…, 1) stamp.
  • Real Postgres (backend:integration, local pgserver, filtered run):
    • checkBrokerAccountSelection has two new records: a real HTTP broker whose A cools down or lacks account_id vends B, and an all-cooling pool refuses with A's cooldown end.
    • The new checkCooledStartRetry lane shows three things: the retry arm carries the wait, the history reads the wait after the run's own 429 as free, and the queued run's task.agent_turn job has start_after at the cooldown end.
    • checkCredentialRotationRetry and checkAutoRetryAndKickPlan (the live 1-2-3 retry cascade) pass, as do checkOneLiveRunPerTask, checkQueuedRunRecovery and checkTaskRunStartFence from the first round.
    • The only failure is the environmental knowledge BM25 indexes verified at boot: pgserver has no pg_search, and it fails the same way on main.
  • Static checks: oxlint --type-aware --type-check on every changed file, lint:manual, and a local Opengrep scan (0 findings).
  • Real browser (local app stack):
    • On the task page, a live retry stamped 0 reads Resumed after a token refresh, and one stamped 2 reads Auto-retry 2 of 3, in en, de and fr. The German caption wraps to two lines in the property panel.
    • The visual-aspect-analyzer scores the page 74 on both this branch and main, with the same three load defects: a flicker on the Board toggle, a 0.013 page layout shift, and a 0.002 shift of the Repeat field. None is in the run strip, and no element is affected by the caption.
  • Independent review: an adversarial review of the first round found no high-severity defect; its medium and low findings are addressed in f20d2f8. A second review round found the run failure code of an exhausted cooldown chain reading harness_error, and the rotation stamp after real progress. Both are fixed in 128e27b and be109d7, with tests that fail without the fix.
  • Squash message: the repository squash-merges with the PR title and a blank body, so earlier commit bodies (42a43e7 says a refused start always counts, which f20d2f8 reversed) do not reach main.

Not run locally: the whole platform suite, a workspace-wide tsc, the full backend:integration, and a live vendor 429/401. CI runs the first two.

The hand-out floor holds an account back while another account of its
vendor can take the work, judged by the gateway's own view of the pool. A
consumer applies rules the gateway cannot see: the platform's shared
60-second cooldown after a 429, and OpenAI's required vendor account id.
When those drop the one account the gateway counted as servable, the
floor-held account arrived as `available: false` like a spent quota, and a
two-account pool refused all work for the hour before each refresh.

Each token now carries `hold`: `quota` while its quota is spent (also when
the floor holds it too), `refresh` while only the floor holds it, null while
it is available. `available` keeps its meaning, so a consumer that reads
nothing else still skips a floor-held account; one whose own rules leave it
no available account may start work on a `refresh` hold, the latest
`refresh_at` first, as the gateway would itself.
The credential-rotation lane's header credited `failure_code` to migration 0132, the task-repeat series; 0133_project_agent_runs_failure_code.sql adds it.
A free credential-rotation retry stamped `Math.max(streak, 1)`, so the
first one after a clean run read "Auto-retry 1 of 3" on the task card and
the next ordinary failure read "Auto-retry 1 of 3" again, while the docs say
the attempt count does not advance.

A free retry now stamps the attempts actually spent. With none spent it is
0, which the card shows as "Resumed after a token refresh" (en, de, fr)
instead of a count; after counted failures it keeps the count it had
reached. The task-automation docs say what the card shows.
The gateway holds an account back for its coming token refresh while
another account of its vendor can take the work, judged without the
platform's own rules. When the platform then drops that other account —
the shared 60-second cooldown after a 429, or OpenAI's missing account_id —
nothing was left, the start threw CREDENTIAL_BROKER_EXHAUSTED or
CREDENTIAL_BROKER_EMPTY, and the immediate retries spent the whole budget
in seconds. A two-account pool (A cooling, B inside its refresh floor)
failed the task or automation, where before the floor B would have served.

Accounts the broker marks `hold: "refresh"` now pass every other filter
into a held tier: the durable pick serves one, the latest refresh first,
only when no available account is out of its cooldown — never while one
can serve, and never on a quota hold. A broker that names no `hold` (the
gateway before this release) keeps today's behaviour, so the platform can
ship first.

A pool whose every account is cooling down now says when the first comes
back. A task retry is kicked at once, so the card shows it queued, but its
start job waits until then; an automation re-kick's start is held the same
way, its time limit counted from the start. Both waits are capped at the
cooldown. The refused start still counts as an attempt: a pool that other
work keeps cooling must not hold a run in an endless wait, and the attempt
after the wait can vend. A start's credential refusal is shown in its own
words instead of its serialized payload.
yannickmonney and others added 4 commits September 29, 2026 00:42
An adversarial review of the first round found:

- A 429 still cost two attempts when no other account was healthy: the
  failed turn counted, and so did its retry, which the cooling pool
  refused at once. A start refused this way now settles as
  `credential_cooldown`. When the refused run retried the task's own 429,
  the wait is free (`freeCooldownWaits`, and `retriedRateLimit` on an
  automation cursor). Every free wait needs a counted 429 directly behind
  it, so a pool that other work keeps cooling still cannot loop. The retry
  history now reads each run's vendor status and card stamp, over a window
  wide enough for that extra free row.
- An automation re-kicked after such a refusal started its conversation
  over. It now resumes the conversation the refused attempt was to resume,
  with the reason that cut it (`resumeReason` on the cursor).
- A task's comment restart and an automation's answered-ask resume ignored
  the refusal: they showed its serialized payload and retried into it at
  once. Both now use the refusal's own words (`runFailureMessage`) and
  carry its `retryAtMs`.
- A free rotation after a progress reset showed "Resumed after a token
  refresh" where the cut run had shown "Auto-retry 1 of 3". A free
  rotation's retry now shows whatever the cut run showed, 0 only when that
  run showed no count, so the docs' "the count does not advance" holds.

Docs (en, de, fr), the gateway README order, the manual reference, and a
held-order test follow.
An automation agent step whose every start a cooling broker pool refused
settled `credential_cooldown`, which the agent-to-run code mapping did not
know, so a run whose budget such refusals spent reported `harness_error`
through the public API for a turn that never started. Before the cooldown
code existed the same run reported `start_failed`.

`agentFailureCodeOf` now reports each retry-only agent code as the wire code
it refines: `credential_cooldown` as `start_failed`, `credential_rotated`
as `harness_error` (the code a rotated 401 always carried). The OpenAPI enum
does not change, and a new agent code that is neither on the wire nor mapped
fails to compile. A unit test locks the mapping, and two stepper tests
check the final run code of an exhausted cooldown chain and of an exhausted
rotation streak.
A free credential rotation's retry copied the attempt the cut run showed,
even when that run had worked past the progress threshold and so refreshed
the budget: a third auto-retry that worked twenty minutes before the refresh
cut it resumed as "Auto-retry 3 of 3", and the next ordinary failure then
dropped to "1 of 3". The automation lane already stamps 0 in that case.

The task lane now stamps 0 too, so the card reads "Resumed after a token
refresh", and the docs (en/de/fr) say when it does.
TASK-F47 provokes a free rotation after a run nothing retried and judges
the "Resumed after a token refresh" caption in the task dialog and on the
task page in en, de and fr, where the German caption wraps. ACCT-21 lists
`available` and `hold` among the token fields. The platform reference
records the rotation stamp after real progress and the run codes an
exhausted cooldown or rotation chain reports, and hands the caption's
layout to TASK-F47.
@yannickmonney
yannickmonney merged commit d7f1ee0 into main Sep 29, 2026
50 checks passed
@yannickmonney
yannickmonney deleted the fix/broker-floor-held-fallback branch September 29, 2026 03:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant