Skip to content

feat(kiro): per-account concurrency cap and least-loaded selection - #5994

Merged
lidge-jun merged 3 commits into
devfrom
codex/kiro-lb2-040-account-load
Sep 26, 2026
Merged

lidge-jun merged 3 commits into
devfrom
codex/kiro-lb2-040-account-load

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Sep 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

Kiro had no way to limit how many requests hit one account at once, and no way to spread load across healthy accounts: the pool kept every healthy request on the active account until it was refused.

After this change:

  • oauthAccountFailover.maxConcurrentPerAccount (Kiro only, 1–100) bounds in-flight requests per account with a process-local lease ledger. A request admitted to a full account waits up to 250 ms for a slot, then gets a retryable 503 account_capacity with Retry-After: 1. Capacity never moves a request and never writes the stored selection.
  • A released slot is handed directly to the first live waiter, so a new arrival cannot jump the queue. Leases release on body end, read error, cancel and request abort, and a lazy 15-minute reclaim bounds any leak; release is idempotent.
  • Reactive rotation (from fix(kiro): fail over on monthly quota and suspension refusals #5991) takes a no-wait lease on its target before committing the selection. A full target leaves the store and request state untouched and the original refusal reaches the client. A 401 replay that resolves a different account leases that account first or stops with the formatted 401.
  • least-loaded is a new opt-in Kiro pool strategy: among eligible accounts it skips those at their cap and picks the fewest in flight, with stable ties. It runs only under the existing proactive-preference switch and pool.kernel; with it off, rotation keeps today's headroom ranking. When a cap is configured, reactive rotation prefers a sibling with room.
  • Non-Kiro providers are unchanged, including the legacy /api/oauth/accounts/pool response shape. The unified /api/pool/settings DTO gains maxConcurrentPerAccount as a declared null for every kind, per its same-keys contract.

Layer 040 of devlog/_plan/260926_kiro_lb_parity2/.

Stack (manual chain, merge bottom-up):

# Layer State
010 usage probe + restart continuity merged (#5967)
020 transport merged (#5981)
030 refusal classes + account failover merged (#5991)
040 concurrency cap + least-loaded ← you are here
050 per-account model catalogue next

Verification

  • bun run typecheck — pass
  • One-process run of tests/providers/kiro/, the three server Kiro e2e suites, credential-redirect-guard, web-search-sidecar-429, generic-oauth-failover, oauth-store-multi, images/loop, the 429 docs guard, cli-account-pool-verbs, layout, ratchet and core–Lab boundary — 923 pass, 0 fail
  • Every test that touches pool settings or pool strategy, plus account-pool-management-api, run in a clean worktree outside ~/.codex — 1162 pass, 0 fail
  • New tests cover the per-lease ledger (idempotent release, reclaim without double-decrement, live-waiter handoff, no queue jumping), the bounded wait and direct 503, a reactive rotation onto a full account (original refusal, store unchanged), the commit-race lease match, the 401 replay lease, least-loaded choice and its proactive gate, non-Kiro rotation unchanged, and an abandoned body released on request abort.
  • An independent review of the diff found two concurrency races (queue jumping, 401 replay lease); both are fixed with regressions that failed first.
  • privacy:scan, structure:check — pass. Hosted CI: see the follow-up comment.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed. (configuration and account CLI references en/fr/tr; structure/providers/kiro.md, structure/transports/responses-failover.md and related structure docs)
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults. (Every send holds the lease of the account whose credentials it carries; the cap and strategy are opt-in.)

Summary by CodeRabbit

  • New Features
    • Added Kiro-only least-loaded account selection when proactive selection is enabled.
    • Added an optional per-account concurrency limit of 1–100 requests. When an account is full, requests wait up to 250 ms before receiving a 503 capacity response; they are not moved to another account solely due to capacity.
    • Account slots are released when responses complete or are cancelled.

maxConcurrentPerAccount bounds in-flight requests per Kiro account with a
process-local lease ledger. A request admitted to a full account waits up to a
bounded interval and then gets a retryable 503 account_capacity; capacity never
moves a request or writes the stored selection. A reactive rotation takes a
no-wait lease on its target before committing the selection, so a full target
returns the original refusal with state unchanged. The opt-in least-loaded
strategy picks the eligible account with the fewest requests in flight,
skipping accounts at their cap, under the existing proactive-preference switch.
Leases release on body end, error, cancel and request abort, and a 15-minute
reclaim bounds any leak.
…count

A slot released while a request is queued now goes straight to the first live
waiter instead of back to the pool, so a new arrival cannot take it and leave
the waiter to time out. A 401 replay that resolves a different account takes
that account's lease before sending, or stops with the formatted 401.
@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner September 26, 2026 19:06
@github-actions

Copy link
Copy Markdown
Contributor

✅ Deterministic PR hygiene checks passed.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-26T19:11:19.236766Z 08aa385 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions github-actions Bot added the enhancement New feature or request label Sep 26, 2026
@coderabbitai

coderabbitai Bot commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration

Configuration used: Repository: lidge-jun/opencodex/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 3c3f8909-97dc-4115-a257-f370747c43b3

📥 Commits

Reviewing files that changed from the base of the PR and between 8a26a79 and 08aa385.

📒 Files selected for processing (29)
  • devlog/_plan/260926_kiro_lb_parity2/040_account_load_cap_and_least_loaded.md
  • docs-site/src/content/docs/fr/reference/cli/providers-accounts.md
  • docs-site/src/content/docs/reference/cli/providers-accounts.md
  • docs-site/src/content/docs/reference/configuration/providers.md
  • docs-site/src/content/docs/tr/reference/cli/providers-accounts.md
  • scripts/test-layout/layout.json
  • src/cli/account-extended.ts
  • src/cli/account.ts
  • src/oauth/generic-account-failover.ts
  • src/oauth/kiro-account-load.ts
  • src/oauth/pool-settings-capability.ts
  • src/server/management/oauth-account-routes.ts
  • src/server/responses/core-lifetime.ts
  • src/server/responses/core-options.ts
  • src/server/responses/core.ts
  • src/server/responses/request-transport.ts
  • src/types/provider.ts
  • structure/config.md
  • structure/providers-and-adapters.md
  • structure/providers/kiro.md
  • structure/runtime.md
  • structure/transports/inventory.md
  • structure/transports/responses-failover.md
  • structure/transports/responses.md
  • tests/fixtures/test-layout-expected.json
  • tests/providers/kiro/kiro-account-load.test.ts
  • tests/providers/kiro/kiro-leased-responses.test.ts
  • tests/providers/kiro/kiro-pool-load-settings.test.ts
  • tests/server/account-pool-management-api.test.ts
 _______________________________________
< Goodbye, 3-hour code review sessions. >
 ---------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 08aa38572d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +622 to +625
if (kiroLoadEnabled) {
const lease = await acquireAccountLease("kiro", admitted.accountId, {
maxConcurrentPerAccount: kiroCap, waitMs: KIRO_ACCOUNT_WAIT_MS, signal: options.abortSignal ?? req.signal,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reserve the least-loaded account before asynchronous resolution

When two Kiro requests arrive concurrently with least-loaded and a per-account cap, both can observe the same zero-load tie before either reaches this post-resolution lease acquisition. They therefore select the same account; one acquires its lease while the other waits and returns 503 account_capacity, even though another eligible account remains idle. Make selection and reservation atomic, or retry least-loaded selection against the current ledger when this acquisition cannot obtain a slot.

Useful? React with 👍 / 👎.

@lidge-jun

Copy link
Copy Markdown
Owner Author

Verification follow-up for head 08aa38572d: hosted Cross-platform CI run 36264910723 (pull_request) — test 1/4, 2/4, 3/4, 4/4 and gates passed.

@lidge-jun
lidge-jun merged commit 93e5d5b into dev Sep 26, 2026
33 of 34 checks passed
@lidge-jun
lidge-jun deleted the codex/kiro-lb2-040-account-load branch September 26, 2026 19:14
@lidge-jun

Copy link
Copy Markdown
Owner Author

리뷰 · 우선순위 63 / 80

Kiro는 계정 하나에 요청이 몇 개까지 동시에 붙는지 정하지 못했습니다. 멀쩡한 계정이 더 있어도, 지금 계정으로 계속 보냈습니다.

이 PR은 그 한도와, 덜 바쁜 계정을 고르는 방법을 넣습니다. maxConcurrentPerAccount(1–100)는 이 프로세스 안에서 계정마다 지금 처리 중인 요청을 셉니다. 고른 계정이 가득 차면 250ms만 기다렸다가 503 account_capacity를 줍니다. Retry-After는 1초입니다. 가득 찼다는 이유만으로 다른 계정으로 옮기지는 않고, 저장된 선택도 그 이유만으로 바꾸지 않습니다. 자리는 응답이 끝나거나, 읽기가 실패하거나, 취소되거나, 요청이 끊기면 돌려줍니다. 같은 반납을 두 번 해도 숫자는 한 번만 줄어듭니다. 15분이 지난 자리는 다음 번에 셀 때 비웁니다. least-loaded는 따로 켜는 전략입니다. pool.kernel과 보내기 전 계정 선호가 같이 켜져 있을 때만, 한도에 안 걸린 계정 중 처리량이 가장 적은 쪽을 고릅니다. 거절 뒤에 계정을 바꿀 때는 한도가 있으면 여유가 있는 옆 계정을 먼저 보고, 그 계정이 가득 차면 저장값과 이 요청을 그대로 둔 채 처음 거절을 돌려줍니다. Kiro가 아닌 제공자는 예전과 같습니다. 바탕 브랜치는 dev입니다. types.ts와 config.ts를 나누는 변경은 아닙니다.

라인 - src/oauth/generic-account-failover.ts 549줄. src/server/responses/request-transport.ts 622줄. 계정을 고르는 순간과 자리를 맡는 순간이 다릅니다. 고른 뒤에는 토큰을 읽고 저장에 적은 다음에야 자리를 맡습니다. 요청 두 개가 같이 들어오면 둘 다 비어 있는 같은 계정을 볼 수 있습니다. 한 개만 자리를 얻고, 다른 한 개는 250ms 뒤에 503을 받습니다. 옆 계정이 쉬고 있어도 다시 고르지 않습니다.

라인 - src/oauth/kiro-account-load.ts 15줄, 48줄. 자리가 15분을 넘으면 응답이 아직 나가고 있어도 빈 자리로 칩니다. 긴 Kiro 응답이 그 시간을 넘기면, 한도보다 많은 요청이 같은 계정에 붙습니다. 늦게 반납해도 숫자는 두 번 줄지 않습니다.

라인 - src/server/responses/request-transport.ts 198줄. src/server/responses/adapter-dispatch.ts 640줄. 401 뒤에 다른 계정으로 다시 보내려다 그 계정이 가득 차면 에러를 던집니다. 받는 쪽은 그 에러를 로그인 실패로 바꿉니다. 클라이언트는 401 invalid_api_key와 "OAuth authentication failed..."를 봅니다. 토큰이 아니라 자리가 없는 경우인데, 다시 로그인하라는 문장입니다. Retry-After도 없습니다.

메인테이너의 판단이 필요한 지점

한도만 켜면 요청은 지금 계정에 남고, 넘치면 503입니다. 옆 계정으로 퍼뜨리려면 least-loaded, pool.kernel, 보내기 전 선호를 같이 켜야 합니다. 용량 때문에 계정을 옮기는 길은 리뷰 뒤에 일부러 뺐습니다. 자리는 이 프로세스 안에서만 셉니다. 프록시 프로세스가 두 개면 계정마다 한도가 두 배가 됩니다. 바탕은 dev라서 그대로 두면 됩니다. types.ts/config.ts 분할로 닫을 대상은 아닙니다.

너의 추천

고른 계정이 가득 차 있으면 503 전에 여유가 있는 계정을 한 번 더 고르면 됩니다. 고르는 순간에 자리를 같이 맡기면 같은 결과가 납니다. 15분 정리는 두되, 응답 본문이 아직 열려 있는 자리는 빼지 않으면 됩니다. 401 재시도에서 자리가 없으면 503 account_capacity와 Retry-After: 1을 주면 됩니다. 토큰이 살아 있으면 그 용량 문장을 쓰면 됩니다.

이 댓글은 grok-bot이 작성했습니다

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant