#12959·qwen-code

feat(core): add maxConcurrentBackgroundAgents setting and retry on transient API errors for background subagents

Author: kolya182Created Sep 28, 2026Updated Sep 30, 2026

Problem

When launching multiple background subagents simultaneously (e.g. 6-7 in parallel via the agent tool), all of them send concurrent inference requests to the same API endpoint. This can exceed the endpoint's concurrent request limit, causing HTTP 400 errors with messages like:

The inference request was rejected as invalid.

Reproduction

  1. Use an OpenAI-compatible endpoint with a per-key concurrent request limit (e.g. self-hosted inference via Sovinfra, vLLM, etc.)
  2. Launch 5+ background subagents in a single turn
  3. All agents run concurrently, each making independent API calls
  4. The endpoint rejects requests as "invalid" under load
  5. Failed agents terminate permanently — no retry, no backoff

Observed behavior

From session log (2026-09-28): 20 API errors across 30 minutes with 7 concurrent agents (1 main + 6 background). 3 subagents failed permanently. The same prompt_id sometimes succeeded on retry in the main conversation but background agents had no retry path.

Root cause (source-level trace)

The error propagation chain, verified from the installed 0.24.6 bundle:

  1. Sovinfra API returns HTTP 400 with {"error": {"message": "The inference request was rejected as invalid."}} — undocumented in their OpenAPI spec (only 422 is documented). Their stack is GPUStack + vLLM behind a TLS reverse proxy; the exact component emitting the 400 is unconfirmed.

  2. OpenAI JS SDK parses the error body, throws APIError with error.message set to the API's message verbatim.

  3. EnhancedErrorHandler.buildErrorMessage() in chunk-HQNM3OMI.js calls getErrorMessage(error) which returns error.message — the API's message is passed through unchanged.

  4. EnhancedErrorHandler.handle() re-throws the error immediately for 400s. Per merged PR #11634, 4xx (including 400) is classified as fail-fast — only 429/503/1302/1305 get a retry budget. PR #11291 further classifies errors with type: invalid_request_error as permanent, even without an HTTP status code.

  5. AgentHeadless.execute() in chunk-4DAVFJGK.js catches the error:

    javascript
    catch(error3) {
        this.terminateMode = "ERROR";
        this.core.eventEmitter?.emit("error", {
            subagentId: this.core.subagentId,
            error: error3.message,
            timestamp: Date.now()
        });
        throw error3;  // no retry, no backoff
    }
  6. The error event handler in chunk-R3AIDFCJ.js receives the event and disposes the agent:

    javascript
    this.emitter.emit("error", {
        subagentId: this.id,
        error: error.message,
        timestamp: Date.now()
    });
    await this.dispose();  // agent is permanently gone
    if(!signal?.aborted && !timedOut) throw error;
  7. The agent is marked failed with lastError: "Unhandled error. ..." in its .meta.json. No re-spawn, no backoff, no retry. The agent is dead.

The main conversation loop survives the same 400 because the user can type again (new prompt, fresh API call). Background subagents have no interactive user — once disposed, the work is lost.

Proposed solutions

1. maxConcurrentBackgroundAgents setting (primary)

Add a new setting in settings.json:

json
{
  "maxConcurrentBackgroundAgents": 3
}

When the limit is reached, additional background agents should be queued and start as slots free up, rather than all firing simultaneously. This is a straightforward admission control — the agent roster already tracks running agents, so only a queue + slot check is needed.

Default: 0 (unlimited, current behavior) to avoid breaking existing workflows.

2. Automatic retry on transient 400/429 in AgentHeadless.execute() (secondary)

The retry should go in AgentHeadless.execute() in chunk-4DAVFJGK.js — wrap the agent loop in a retry for transient errors before the agent gets disposed. The current code has zero retry logic here:

javascript
// Current code (chunk-4DAVFJGK.js, AgentHeadless.execute):
catch(error3) {
    this.terminateMode = "ERROR";
    this.core.eventEmitter?.emit("error", {
        subagentId: this.core.subagentId,
        error: error3.message,
        timestamp: Date.now()
    });
    throw error3;
}

Proposed fix:

javascript
// Proposed: retry transient errors before disposing
const MAX_TRANSIENT_RETRIES = 3;
const BACKOFF_BASE_MS = 1000;

for (let attempt = 0; attempt < MAX_TRANSIENT_RETRIES; attempt++) {
    try {
        return await this.runAgentLoop();
    } catch (error) {
        const status = getErrorStatus(error);
        const isTransient =
            (status === 400 && /rejected|invalid|too many|concurrent/i.test(error.message)) ||
            status === 429 ||
            status >= 500;
        if (!isTransient || attempt === MAX_TRANSIENT_RETRIES - 1) {
            this.terminateMode = "ERROR";
            this.core.eventEmitter?.emit("error", {
                subagentId: this.core.subagentId,
                error: error.message,
                timestamp: Date.now()
            });
            throw error;
        }
        const delay = BACKOFF_BASE_MS * Math.pow(2, attempt); // 1s, 2s, 4s
        await sleep(delay);
    }
}

Key design decisions:

  • Scoped retry: only retry 400s whose message matches transient patterns ("rejected", "invalid", "too many", "concurrent") — not all 400s, which may be genuine request format errors (see #11956, #11045 for examples of real 400s)
  • Exponential backoff: 1s → 2s → 4s, matching the existing SENT_COMPLETION_DELIVERY_RETRY_MS pattern in create-sub-session-ZYBWLO3M.js
  • Respects abort: check signal?.aborted between retries
  • Max 3 retries: bounded, won't hang the agent forever

Related

  • #8097 — Background agent coordination gap (duplicate work, premature completion)
  • #11634 — Merged: classifies 4xx as fail-fast in retry classifier (the design choice that makes this bug possible)
  • #11291 — Merged: classifies invalid_request_error type as permanent
  • #11215 / PR #11216 — Same bug class: throttle error surfaced as invalid_request_error was not retried
  • The agent roster already tracks running/completed/failed states per subagent; a concurrency gate would build on this

Impact

Users running multiple parallel AI sessions or launching batch subagent workloads against rate-limited endpoints (self-hosted inference, custom OpenAI-compatible proxies) lose work when all concurrent agents hit the endpoint's limit simultaneously. Currently the only workaround is manual: don't launch more than N agents at a time, which is a behavioral constraint rather than a system-level safeguard.