Skip to content

feat: add configurable retry for LLM provider API calls - #61443

Closed
Lambdauv wants to merge 7 commits into
openclaw:mainfrom
Lambdauv:feature/provider-api-retry
Closed

Lambdauv wants to merge 7 commits into
openclaw:mainfrom
Lambdauv:feature/provider-api-retry

Conversation

@Lambdauv

@Lambdauv Lambdauv commented Apr 5, 2026

Copy link
Copy Markdown

Summary

  • Adds opt-in retry config to models.providers.<name> for retrying transient LLM provider failures (ECONNREFUSED, 429, 502/503/504, timeouts)
  • Reuses existing channel retry infrastructure (retryAsync, RetryConfig, RetryConfigSchema) — no new retry primitives
  • Client errors (400/401/403/404) fail immediately without retry
  • Backward compatible: no retry when config is omitted

Motivation

Self-hosted LLM backends (vLLM, Ollama, etc.) sometimes require scheduled restarts for maintenance. Without provider-level retry, all in-flight and new requests fail during the restart window. This change lets users configure retry to ride through transient outages:

models.providers.vllm.retry = {
  attempts: 25,
  minDelayMs: 5000,
  maxDelayMs: 60000,
  jitter: 0.15
}

Closes #31104

Test plan

  • 15 unit tests covering retry behavior, error classification, config overrides
  • TypeScript clean (no new errors in changed files)
  • No regressions in broader test suite (pre-existing failures unrelated to this change)
  • Security scan: no secrets, personal info, or internal IPs in any changed file

Reuses the existing channel retry infrastructure (retryAsync,
RetryConfig, RetryConfigSchema) to add opt-in retry for model
provider requests. When a provider has retry config, transient
failures (ECONNREFUSED, 429, 502/503/504, timeouts) are retried
with exponential backoff. Client errors (400, 401, 403, 404) fail
immediately. This is useful for self-hosted backends with scheduled
maintenance windows.

Config example:
  models.providers.<name>.retry = {
    attempts: 25,
    minDelayMs: 5000,
    maxDelayMs: 60000,
    jitter: 0.15
  }

Closes openclaw#31104

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Apr 5, 2026
@greptile-apps

greptile-apps Bot commented Apr 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds opt-in retry configuration for LLM provider API calls, targeting transient failures from self-hosted backends like vLLM and Ollama. It introduces a module-scoped runner registry (src/agents/provider-retry.ts), a new createProviderApiRetryRunner factory in src/infra/retry-policy.ts, and hooks the retry path into the three OpenAI-compatible transport call sites in openai-transport-stream.ts. The approach is sound — reusing existing retryAsync/RetryConfig infrastructure, failing fast on client errors, and keeping the feature strictly opt-in.

  • Stale runner registry on config reload: registerProviderRetryConfig accumulates entries in a module-level Map but clearProviderRetryRunners() is never called in production. Removing or modifying a provider's retry config at runtime has no effect until process restart.
  • Missing 422 in non-retryable status codes: isNonRetryableProviderError omits HTTP 422 (Unprocessable Entity), which LLM providers use for invalid parameters — a permanent client error that should not be retried.
  • Retry is only wired into the OpenAI-compatible transports (responses, azure-responses, completions); Anthropic, Google, and Bedrock transports are unaffected, which appears intentional given the self-hosted-backend motivation.

Confidence Score: 3/5

Mostly safe to merge with caution — the stale-runner bug is real but only affects config-reload scenarios, not initial startup.

Score of 3 reflects a genuine P1 logic bug (stale runners after config reload) and a P2 gap in non-retryable status code coverage. The feature works correctly on first boot, but dynamic config updates without a restart will silently continue using the old retry policy, which could frustrate users who remove retry config to stop aggressive retrying during an incident.

src/agents/models-config.providers.normalize.ts (stale runner lifecycle) and src/infra/retry-policy.ts (non-retryable status codes)

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/models-config.providers.normalize.ts
Line: 142-144

Comment:
**Stale retry runners persist after config reload**

`registerProviderRetryConfig` adds entries to the module-scoped `providerRetryRunners` map but there is no corresponding cleanup path. `clearProviderRetryRunners()` is exported and used in tests, but is never called in any production code path.

In practice this means:
- If a user removes the `retry` field from a provider config and config reloads (via the `normalizeProviders` → `models-config.plan.ts` path), the old retry runner for that provider persists until process restart. The removed config has no runtime effect.
- If the retry config is changed (e.g., `attempts` reduced from 25 to 3), `registerProviderRetryConfig` will overwrite the entry on re-registration **only if `normalizedProvider.retry` is still truthy**. Removal still leaves the stale entry.

A simple fix is to call `clearProviderRetryRunners()` at the top of `normalizeProviders` (before the provider loop), so the map is rebuilt on every normalization pass:

```ts
// At the top of normalizeProviders, before the for loop:
clearProviderRetryRunners();
```

Alternatively, for providers that no longer have a retry field, explicitly delete the entry:
```ts
if (normalizedProvider.retry) {
  registerProviderRetryConfig(normalizedKey, normalizedProvider.retry);
} else {
  deregisterProviderRetryConfig(normalizedKey); // new helper
}
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/infra/retry-policy.ts
Line: 118-125

Comment:
**422 Unprocessable Entity not in non-retryable set**

`isNonRetryableProviderError` currently blocks retry for status 400, 401, 403, and 404 — but not **422**. OpenAI, vLLM, and most other LLM-compatible providers return 422 for structurally invalid payloads (bad parameters, missing required fields, schema mismatches). These are permanent client errors that will never succeed on retry.

Because `PROVIDER_API_RETRY_RE` does not include `"422"` or `"unprocessable"`, a 422 whose error message happens to contain a matching term (e.g. `reset`, `closed`) could accidentally be retried, wasting quota and delaying the error surfacing to the caller.

```suggestion
function isNonRetryableProviderError(err: unknown): boolean {
  if (!err || typeof err !== "object") {
    return false;
  }
  const status = "status" in err ? (err.status as number) : undefined;
  // Client errors that are never retryable
  return status === 400 || status === 401 || status === 403 || status === 404 || status === 422;
}
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "feat: add configurable retry for LLM pro..." | Re-trigger Greptile

Comment on lines +142 to +144
if (normalizedProvider.retry) {
registerProviderRetryConfig(normalizedKey, normalizedProvider.retry);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Stale retry runners persist after config reload

registerProviderRetryConfig adds entries to the module-scoped providerRetryRunners map but there is no corresponding cleanup path. clearProviderRetryRunners() is exported and used in tests, but is never called in any production code path.

In practice this means:

  • If a user removes the retry field from a provider config and config reloads (via the normalizeProviders → models-config.plan.ts path), the old retry runner for that provider persists until process restart. The removed config has no runtime effect.
  • If the retry config is changed (e.g., attempts reduced from 25 to 3), registerProviderRetryConfig will overwrite the entry on re-registration only if normalizedProvider.retry is still truthy. Removal still leaves the stale entry.

A simple fix is to call clearProviderRetryRunners() at the top of normalizeProviders (before the provider loop), so the map is rebuilt on every normalization pass:

// At the top of normalizeProviders, before the for loop:
clearProviderRetryRunners();

Alternatively, for providers that no longer have a retry field, explicitly delete the entry:

if (normalizedProvider.retry) {
  registerProviderRetryConfig(normalizedKey, normalizedProvider.retry);
} else {
  deregisterProviderRetryConfig(normalizedKey); // new helper
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/models-config.providers.normalize.ts
Line: 142-144

Comment:
**Stale retry runners persist after config reload**

`registerProviderRetryConfig` adds entries to the module-scoped `providerRetryRunners` map but there is no corresponding cleanup path. `clearProviderRetryRunners()` is exported and used in tests, but is never called in any production code path.

In practice this means:
- If a user removes the `retry` field from a provider config and config reloads (via the `normalizeProviders` → `models-config.plan.ts` path), the old retry runner for that provider persists until process restart. The removed config has no runtime effect.
- If the retry config is changed (e.g., `attempts` reduced from 25 to 3), `registerProviderRetryConfig` will overwrite the entry on re-registration **only if `normalizedProvider.retry` is still truthy**. Removal still leaves the stale entry.

A simple fix is to call `clearProviderRetryRunners()` at the top of `normalizeProviders` (before the provider loop), so the map is rebuilt on every normalization pass:

```ts
// At the top of normalizeProviders, before the for loop:
clearProviderRetryRunners();
```

Alternatively, for providers that no longer have a retry field, explicitly delete the entry:
```ts
if (normalizedProvider.retry) {
  registerProviderRetryConfig(normalizedKey, normalizedProvider.retry);
} else {
  deregisterProviderRetryConfig(normalizedKey); // new helper
}
```

How can I resolve this? If you propose a fix, please make it concise.

Comment thread src/infra/retry-policy.ts
Comment on lines +118 to +125
function isNonRetryableProviderError(err: unknown): boolean {
if (!err || typeof err !== "object") {
return false;
}
const status = "status" in err ? (err.status as number) : undefined;
// Client errors that are never retryable
return status === 400 || status === 401 || status === 403 || status === 404;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 422 Unprocessable Entity not in non-retryable set

isNonRetryableProviderError currently blocks retry for status 400, 401, 403, and 404 — but not 422. OpenAI, vLLM, and most other LLM-compatible providers return 422 for structurally invalid payloads (bad parameters, missing required fields, schema mismatches). These are permanent client errors that will never succeed on retry.

Because PROVIDER_API_RETRY_RE does not include "422" or "unprocessable", a 422 whose error message happens to contain a matching term (e.g. reset, closed) could accidentally be retried, wasting quota and delaying the error surfacing to the caller.

Suggested change
function isNonRetryableProviderError(err: unknown): boolean {
if (!err || typeof err !== "object") {
return false;
}
const status = "status" in err ? (err.status as number) : undefined;
// Client errors that are never retryable
return status === 400 || status === 401 || status === 403 || status === 404;
}
function isNonRetryableProviderError(err: unknown): boolean {
if (!err || typeof err !== "object") {
return false;
}
const status = "status" in err ? (err.status as number) : undefined;
// Client errors that are never retryable
return status === 400 || status === 401 || status === 403 || status === 404 || status === 422;
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/retry-policy.ts
Line: 118-125

Comment:
**422 Unprocessable Entity not in non-retryable set**

`isNonRetryableProviderError` currently blocks retry for status 400, 401, 403, and 404 — but not **422**. OpenAI, vLLM, and most other LLM-compatible providers return 422 for structurally invalid payloads (bad parameters, missing required fields, schema mismatches). These are permanent client errors that will never succeed on retry.

Because `PROVIDER_API_RETRY_RE` does not include `"422"` or `"unprocessable"`, a 422 whose error message happens to contain a matching term (e.g. `reset`, `closed`) could accidentally be retried, wasting quota and delaying the error surfacing to the caller.

```suggestion
function isNonRetryableProviderError(err: unknown): boolean {
  if (!err || typeof err !== "object") {
    return false;
  }
  const status = "status" in err ? (err.status as number) : undefined;
  // Client errors that are never retryable
  return status === 400 || status === 401 || status === 403 || status === 404 || status === 422;
}
```

How can I resolve this? If you propose a fix, please make it concise.

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

Copy link
Copy Markdown
Contributor

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: 2c93abb2f9

ℹ️ 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 +142 to +143
if (normalizedProvider.retry) {
registerProviderRetryConfig(normalizedKey, normalizedProvider.retry);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Clear stale provider retry runners on config reload

normalizeProviders registers a runner when normalizedProvider.retry exists, but there is no corresponding unregister path when a later config reload removes that retry block (or removes the provider). Because the registry is module-scoped, the old runner remains active and openai-transport-stream will keep retrying for that provider until process restart, so runtime behavior no longer matches the updated config.

Useful? React with 👍 / 👎.

Comment on lines +136 to +140
continue;
}
next[normalizedKey] = normalizedProvider;

// Register provider-level retry config when present so the transport

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Register retry after duplicate provider-key merge

When two provider keys normalize to the same id (for example, accidental whitespace variants), the existing branch merges configs and continues before reaching the retry-registration block. If only the later duplicate defines retry, the merged provider config contains retry settings but no runner is registered, so retries silently do not apply for that provider.

Useful? React with 👍 / 👎.

- Clear retry runner registry at start of normalizeProviders so
  removed/changed retry configs take effect without process restart
- Move retry registration after duplicate provider-key merge so
  merged providers get their retry runner registered
- Add 422 Unprocessable Entity to non-retryable status codes
- Add test for 422 non-retry behavior

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

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

Copy link
Copy Markdown
Contributor

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: 32d9efa49a

ℹ️ 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 +717 to +719
const responseStream = retryRunner
? await retryRunner(createStream, "responses")
: await createStream();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Make retry backoff abort-aware for streaming requests

This wraps stream creation in retryRunner(...), but the retry loop is not cancellation-aware, so if the first attempt fails and the user aborts while backoff sleep is in progress, cancellation is delayed until the sleep (and potentially later attempts) completes. In practice, a cancelled request can appear hung for up to the configured backoff window(s) when provider retry is enabled; retries should short-circuit immediately once options.signal is aborted.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Valid point. The existing retryAsync() in src/infra/retry.ts uses a plain sleep() that is not AbortSignal-aware — the sleepWithAbort() utility in src/infra/backoff.ts exists but is not wired into retryAsync. Fixing this would require modifying the shared retry infrastructure (used by all channel integrations too), which feels out of scope for this PR. Happy to file a follow-up issue to make retryAsync abort-aware.

In practice, the outer catch block in the transport stream checks options?.signal?.aborted and sets stopReason = "aborted", so the request does get cleaned up — just with a delay of up to one backoff interval.

Comment on lines +48 to +50
// Rebuild the provider retry runner registry on every normalization pass
// so removed/changed retry configs take effect without a process restart.
clearProviderRetryRunners();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Clear provider retry runners on empty-provider reloads

The retry registry is cleared only here inside normalizeProviders, but config reloads that resolve to zero providers take the early skip path in models planning and never call this function, leaving previously registered runners active. That means removing all providers (or passing through an empty-provider config) can still apply stale retry behavior until restart. Fresh evidence: this commit moved the clear into normalization, so the early-empty skip path now bypasses registry reset entirely.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch. When the provider map is empty/undefined, normalizeProviders returns early before reaching the clearProviderRetryRunners() call, so stale runners survive.

Fixed by moving the clear before the early return:

Move clearProviderRetryRunners() before the empty-provider early
return so stale runners are cleaned up even when all providers
are removed from config.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

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

Copy link
Copy Markdown
Contributor

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: 8112eeac68

ℹ️ 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".

// Uses the final merged value so duplicate-key merges are covered.
const finalRetry = next[normalizedKey]?.retry;
if (finalRetry) {
registerProviderRetryConfig(normalizedKey, finalRetry);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Normalize provider IDs before registering retry runners

registerProviderRetryConfig is keyed with normalizedKey, which only trims whitespace, but the runtime lookup path uses normalized provider IDs (for example lowercased and alias-mapped IDs such as z.ai → zai in model selection). When a config uses case variants or aliases, the transport calls getProviderRetryRunner(model.provider) with a different key and silently skips retries for that provider. Register (or lookup) with the same canonical provider-id normalization used by model resolution so provider retry works consistently.

Useful? React with 👍 / 👎.

Comment thread src/infra/retry-policy.ts Outdated
"headers" in err && err.headers && typeof err.headers === "object"
? (err.headers as Record<string, unknown>)
: undefined;
const retryAfter = headers?.["retry-after"];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Read Retry-After from Headers objects

getProviderApiRetryAfterMs assumes err.headers is a plain object and reads headers["retry-after"], but OpenAI-style errors commonly expose headers as a Headers instance. In that case this lookup returns undefined, so 429/503 responses with Retry-After are ignored and retries run on backoff defaults instead of server guidance, which can trigger premature retries and faster attempt exhaustion. Handle Headers via .get("retry-after") (with object fallback) before computing delay.

Useful? React with 👍 / 👎.

Three follow-up fixes for items the original PR explicitly deferred to a
later patch:

1. Provider ID normalization mismatch (provider-retry.ts)
   Registration used `key.trim()` only; runtime lookups used `model.provider`
   in canonical form (lowercased + alias-mapped). Provider configs keyed by
   "OpenAI", "z.ai", "modelstudio", etc. silently failed to match runtime
   lookups. Fix: route both register and lookup through normalizeProviderId
   so they're symmetric. Tests cover case, alias, and whitespace variants.

2. Retry-After header parsing (retry-policy.ts)
   getProviderApiRetryAfterMs assumed err.headers is a plain object and used
   bracket access. fetch `Headers` instances only expose `.get()` —
   bracket access returns undefined, silently dropping the server's hint.
   Fix: probe both shapes; for plain objects also try Title-Case variants
   (HTTP header names are case-insensitive, Headers.get handles that
   internally). Tests cover plain-bag (lowercase + Title-Case) and Headers.

3. Abort-signal-aware backoff (retry.ts + retry-policy.ts + 3 transport sites)
   Plain setTimeout-based sleep ignored the request's AbortSignal; cancelling
   a request would still wait up to one full backoff interval (max 30s) before
   the retry loop exited. Fix:
   - Added `signal?: AbortSignal` to RetryOptions; abortableSleep() rejects
     promptly on abort, retry loop catches and stops without throwing the
     abort itself (rethrows the most recent attempt's error so the caller
     can distinguish API failure from cancel by checking signal.aborted).
   - Also check signal.aborted at top of each loop iteration so we don't
     start a new attempt for an already-cancelled request.
   - RetryRunner now accepts an optional `{ signal }` options object as a
     third arg; backwards-compatible with the existing `(fn, label)` form.
   - Three call sites in openai-transport-stream.ts updated to pass
     `{ signal: options?.signal }`.
   Tests: backoff is interrupted within ~50ms of abort even with 5s minDelay;
   no new attempt is started when signal aborts during the first attempt.

All 51 retry-related tests pass; tsc --noEmit clean.
@clawsweeper

clawsweeper Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Keep open, but not merge-ready: the PR tackles a real provider-retry gap, yet the current patch has blocking design issues around global retry state, over-broad config exposure, stale merge conflicts, and missing real behavior proof.

Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a feature PR. Source inspection confirms current main lacks configurable main LLM provider retry, while the patch defects are source-reproducible from the PR head and current main contracts.

Is this the best way to solve the issue?

No. The PR is a plausible direction, but the best fix needs scoped per-model/shared retry state and a settled provider API contract instead of a global registry plus generic schema that only some transports honor.

Security review:

Security review cleared: No concrete security or supply-chain regression was found; the diff does not add dependencies, workflow execution, credential handling, or secret exposure, though retry behavior remains an auth/provider merge-risk concern.

AGENTS.md: found and applied where relevant.

What I checked:

  • stale F-rated PR: PR was opened 2026-04-05T17:15:05Z, is older than 60 days, and the latest review rated it F.
  • proof blocker: real behavior proof is missing and proof tier is F, so this branch is not merge-ready without contributor follow-up.
  • no human follow-up: live comments and timeline hydrated by apply contain no non-automation activity after the ClawSweeper review.

Likely related people:

  • Peter Steinberger: Blame and recent history on the current provider config, schema, request-transport, and OpenAI request-options surfaces point to Peter's broad provider transport work. (role: recent area contributor; confidence: high; commits: a02813164dd5, 2a6eeceb40fe, a57b4c513f81; files: src/config/types.models.ts, src/config/zod-schema.core.ts, src/agents/provider-transport-fetch.ts)
  • Vincent Koc: Recent provider transport history credits Vincent on the large provider transport/schema commit and related provider runtime refactors near this surface. (role: adjacent contributor; confidence: medium; commits: a02813164dd5, ea4265a82063, 8c802aa68351; files: src/agents/provider-transport-fetch.ts, src/agents/anthropic-transport-stream.ts, src/config/types.models.ts)
  • Thomas Krohnfuß: Recent OpenAI transport compatibility work touched the same OpenAI/Azure route family that this PR wraps with retry. (role: recent OpenAI transport contributor; confidence: low; commits: a12942518e3f; files: src/agents/openai-transport-stream.ts)

Codex review notes: model internal, reasoning high; reviewed against b5999bc6a07d.

@Lambdauv

Copy link
Copy Markdown
Author

Folded the three deferred review items into this PR rather than a follow-up.
All in commit 45165e2845:

  • Images not passed to Claude CLI - only path reference in text #4 abort-signal-aware backoff: added signal?: AbortSignal to
    RetryOptions + an abortableSleep(ms, signal) helper that rejects
    promptly. Retry loop also short-circuits at the top of each iteration if
    the signal aborted between attempts, so a cancelled request doesn't burn
    additional attempts. 3 call sites in openai-transport-stream.ts now
    thread options?.signal through. RetryRunner signature is
    backwards-compatible: both runner(fn, label) and
    runner(fn, label, { signal }) work.
  • CLI: add Opencode integration #5 provider-id normalization: both registerProviderRetryConfig and
    getProviderRetryRunner go through normalizeProviderId (the existing
    canonicalizer in provider-id.ts). Case-insensitive registration +
    lookup, alias resolution (z.ai/modelstudio/qwencloud), and
    whitespace handling are all covered by new tests.
  • Clarification for clawd.md #6 Retry-After header parsing: factored out a readRetryAfterHeader
    helper that probes Headers.get("retry-after") first (for fetch
    Headers instances) and falls back to bracket access with case variants
    (retry-after / Retry-After / RETRY-AFTER) for plain object
    headers — HTTP header names are case-insensitive and Headers.get
    handles that internally for the first path.

Verification:

  • pnpm vitest run src/infra/retry.test.ts src/infra/retry-policy.test.ts src/infra/provider-retry-policy.test.ts src/agents/provider-retry.test.ts src/agents/compaction.retry.test.ts — 51 tests pass (9 new)
  • pnpm tsc --noEmit -p tsconfig.json — clean
  • Pre-commit lint hooks (lint:auth:no-pairing-store-group,
    lint:auth:pairing-account-scope) — clean

@clawsweeper

clawsweeper Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge.

What this changes:

The branch adds opt-in models.providers.<name>.retry config, a provider retry runner registry and policy, abort-aware retry support, OpenAI-compatible transport wrapping, config help/labels/types/schema, and focused retry tests.

Maintainer follow-up before merge:

This is an active contributor implementation touching public config and shared transport/retry behavior; maintainers should request fixes/rebase and choose between this PR and #38640 rather than queue an automated replacement now.

Review findings:

  • [P2] Clear retry runners before zero-provider skips — src/agents/models-config.providers.normalize.ts:35
  • [P2] Preserve OpenAI SDK request options — src/agents/openai-transport-stream.ts:714
  • [P2] Regenerate the public config schema — src/config/zod-schema.core.ts:342
Review details

Best possible solution:

Update this implementation or a single canonical replacement so provider retry is opt-in, scoped correctly through config reloads, preserves existing timeout/request-option behavior, updates generated config surfaces and docs, and has targeted regression coverage before #38640 is resolved.

Full review comments:

  • [P2] Clear retry runners before zero-provider skips — src/agents/models-config.providers.normalize.ts:35
    clearProviderRetryRunners() runs only inside normalizeProviders, but planOpenClawModelsJson returns skip when provider resolution is empty before calling that function. If a reload removes all providers, the old module-scoped runners remain active until restart. Move the clear into the planning path before the empty-provider return or otherwise clear the registry on that skip path.
    Confidence: 0.9
  • [P2] Preserve OpenAI SDK request options — src/agents/openai-transport-stream.ts:714
    Current main passes buildOpenAISdkRequestOptions(model, options?.signal) to these SDK calls so provider timeoutSeconds reaches each request. The PR branch wraps stream creation but passes only signal, which would drop the per-request timeout when this is rebased. Use the existing helper inside each createStream wrapper.
    Confidence: 0.86
  • [P2] Regenerate the public config schema — src/config/zod-schema.core.ts:342
    Adding models.providers.*.retry changes the public config surface, but the generated base schema on the branch has no retry entries and buildConfigSchema() serves that generated payload. Regenerate and commit the base config schema and config-doc baseline so schema consumers and checks see the new field.
    Confidence: 0.84

Overall correctness: patch is incorrect
Overall confidence: 0.87

What I checked:

  • current_main_lacks_provider_retry_config: On current main, ModelProviderConfig has request and models fields but no retry, and the strict ModelProviderSchema also lacks retry; the current retry docs say model providers rely on SDK retry behavior rather than OpenClaw provider retry config. (src/config/types.models.ts:117, e46dccb35374)
  • pr_adds_provider_retry_contract: The PR head adds a ModelProviderRetryConfigSchema and wires retry into ModelProviderSchema, plus adds retry?: OutboundRetryConfig to ModelProviderConfig. (src/config/zod-schema.core.ts:342, 45165e2845ca)
  • empty_provider_reload_still_bypasses_clear: The PR clears retry runners inside normalizeProviders, but planOpenClawModelsJson returns skip when provider resolution is empty before it calls normalizeProviders, so removing all providers can still leave stale runners active until restart. (src/agents/models-config.plan.ts:100, 45165e2845ca)
  • provider_timeout_plumbing_must_be_preserved: Current main passes buildOpenAISdkRequestOptions(model, options?.signal) into OpenAI SDK stream creation so provider timeoutSeconds reaches request options; the PR head wraps stream creation but passes only signal, so a rebase needs to preserve the timeout-aware helper at all three wrapped call sites. (src/agents/openai-transport-stream.ts:714, 45165e2845ca)
  • generated_schema_not_updated: The PR head's generated base config schema has no models.providers.*.retry entries, while current schema serving code reads from GENERATED_BASE_CONFIG_SCHEMA; generated schema and config-doc baselines need regeneration for this public config field. (src/config/schema.base.generated.ts, 45165e2845ca)
  • related_open_implementation: The provided timeline links open feat: Add LLM retry mechanism with exponential backoff #38640 as another LLM retry implementation, so maintainers need to choose one canonical provider-retry design before landing.

Likely related people:

  • steipete: Local current-main inspection and the provided review context tie this area to recent OpenAI transport, provider config/schema, and timeout plumbing work that this PR must preserve. (role: recent maintainer / adjacent owner; confidence: high; commits: d1b2d81752b8, 1dd011984a31, 252c63429ecf; files: src/agents/openai-transport-stream.ts, src/config/types.models.ts, src/config/zod-schema.core.ts)
  • gumadeiras: The provided review context identifies prior shared retry-policy and channel retry hardening work in the infrastructure this PR extends. (role: adjacent retry infrastructure contributor; confidence: medium; commits: b861a0bd73e6, 2f46308d5a9f; files: src/infra/retry-policy.ts, src/infra/retry.ts)
  • DranboFieldston: The provided review context links recent provider fetch/timeout propagation work to this surface; the PR's OpenAI wrapping needs to preserve those timeout and dispatcher semantics. (role: adjacent provider timeout contributor; confidence: medium; commits: 977a4b24afd0; files: src/agents/provider-transport-fetch.ts, src/infra/net/fetch-guard.ts, src/infra/net/undici-runtime.ts)

Remaining risk / open question:

  • The branch is behind current main in provider transport/config files, so a rebase may surface conflicts around timeout and config-schema changes.
  • No CI or Testbox validation was run during this read-only review; the PR author reported targeted local checks, but changed-gate proof is still needed.
  • The scope overlaps open feat: Add LLM retry mechanism with exponential backoff #38640, so maintainers need to pick one canonical retry design before merge.

Codex review notes: model gpt-5.5, reasoning high; reviewed against e46dccb35374.

Lambdauv and others added 2 commits April 30, 2026 05:08
Pre-existing TS errors that blocked `pnpm check` (and therefore
`pnpm tsgo` in CI). All test-only changes; no runtime code touched
beyond fixture/mock typing.

- extensions/memory-core/src/dreaming.test.ts: add the now-required
  `recencyHalfLifeDays` field to 12 ShortTermPromotionDreamingConfig
  fixtures (uses constants.DEFAULT_DREAMING_RECENCY_HALF_LIFE_DAYS).

- src/memory-host-sdk/dreaming.test.ts, src/gateway/server-methods/
  doctor.test.ts: explicitly type the resolveMemorySearchConfig mock
  with `() => { enabled: boolean } | null` so test mocks can return
  null (the real function's return type is `… | null`; vi.fn was
  inferring the type from the initializer and dropping `| null`).

- src/agents/models-config.providers.{anthropic-vertex,nvidia,
  moonshot}.test.ts: add the now-required `models` field to
  ModelProviderConfig fixtures (or annotate the helper return as
  ModelProviderConfig). Introduce a small partialModels() helper
  in nvidia.test.ts to keep call sites readable.

- src/agents/models-config.providers.cloudflare-ai-gateway.test.ts:
  narrow the credential union with an "in" check before reading
  `metadata` (AuthProfileCredential lacks that field).

- src/agents/models-config.providers.ollama.test.ts: cast the env
  literal as NodeJS.ProcessEnv so subsequent OLLAMA_API_KEY reads
  typecheck (`satisfies` only validated, didn't widen).

- src/agents/models-config.providers.stepfun.test.ts: add `!`
  non-null assertions on already-asserted standardProvider/
  planProvider before calling .models on them.

- src/auto-reply/reply/dispatch-from-config.test.ts: update
  `sendPolicy: "deny"` to the SessionSendPolicyConfig shape
  `{ default: "deny" }`.

- src/infra/run-node.test.ts: change the spawn mock's `kill` return
  type from `string` to `void` to match the consumer's
  `kill?: (signal?) => void | boolean` shape.

- src/plugin-sdk/acp-runtime.test.ts, src/plugins/wired-hooks-
  reply-dispatch.test.ts: add `CommandAuthorized: false` to ctx
  fixtures (FinalizedMsgContext requires it).

Verification: pnpm tsgo / pnpm check pass. Retry test suite (the
PR-relevant work) 68/68 passes. dispatch-from-config moves -1 vs
HEAD (the sendPolicy fix repaired one pre-existing failure).
Other touched files have the same failure counts as HEAD.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three P2 findings from clawsweeper at 2026-04-29T16:59:

1. Clear retry runners on the empty-provider skip path
   `planOpenClawModelsJson` returns `{ action: "skip" }` early when
   provider resolution is empty, before normalizeProviders runs — so
   the previous fix that put `clearProviderRetryRunners()` inside
   normalizeProviders is unreachable on that path. Add the call in
   plan.ts before the early return so a "remove all providers"
   reload actually clears the registry. The clear inside
   normalizeProviders stays — it covers "1+ providers, retry removed
   from one" while this new clear covers "0 providers, normalize
   never called."

2. Preserve OpenAI SDK request options in the three createStream
   wrappers. Upstream main passes
   `buildOpenAISdkRequestOptions(model, options?.signal)` to the SDK
   so per-provider `timeoutSeconds` reaches each request; the PR
   branch was passing only `{ signal: options.signal }`, which would
   drop the timeout on rebase. Port a minimal helper with the same
   signature (signal-only on this base; the timeout-resolution
   chain doesn't exist here yet) and call it at all three sites.
   On rebase to current main, the helper definition resolves to
   main's timeout-aware version and the three call sites stay
   unchanged.

3. Regenerate the public config schema. Adding
   models.providers.*.retry to ModelProviderSchema changes the
   surface that buildConfigSchema() serves; ran
   `pnpm config:schema:gen` and `pnpm config:docs:gen` to update
   src/config/schema.base.generated.ts (now contains the four
   retry entries) and the config-doc baseline sha256.

Verification: pnpm tsgo / pnpm check clean. 68/68 retry-related
tests pass (provider-retry, retry-policy, retry, transport-stream).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: memory-core Extension: memory-core labels Apr 30, 2026
@Lambdauv

Copy link
Copy Markdown
Author

Folded the three P2 findings from the @clawsweeper / Codex review at 2026-04-29T16:59 into commit 86bed8e923 (with a separate housekeeping commit df49e2fe2b ahead of it that fixes pre-existing TS errors so pnpm check could run cleanly).

1. Clear retry runners on the empty-provider skip path (models-config.plan.ts:101)
The previous round's clear lived inside normalizeProviders, but planOpenClawModelsJson returns { action: "skip" } early when resolveProvidersForModelsJson produces zero providers, so normalizeProviders is never reached on that path. Added clearProviderRetryRunners() in plan.ts immediately before the early return. The clear inside normalizeProviders stays — it covers "1+ providers, retry removed from one" while the new clear covers "0 providers, normalize never called."

2. Preserve buildOpenAISdkRequestOptions at the three createStream wrappers (openai-transport-stream.ts)
Ported the helper from origin/main and updated the responses, azure-responses, and chat.completions stream wrappers to call buildOpenAISdkRequestOptions(model, options?.signal) instead of passing { signal: options.signal } directly. The branch's base predates main's resolveModelRequestTimeoutMs chain, so the helper body is signal-only here — but the signature matches main's exactly, so on rebase the helper definition will conflict cleanly to main's timeout-aware version while the three call sites stay unchanged. (Not porting the timeout chain wholesale — that's far out of scope and would balloon the diff against main's 11k commits ahead.)

3. Regenerate the public config schema
Ran pnpm config:schema:gen and pnpm config:docs:gen. src/config/schema.base.generated.ts now contains the four models.providers.*.retry entries (retry, retry.attempts, retry.minDelayMs, retry.maxDelayMs, retry.jitter) and docs/.generated/config-baseline.sha256 is updated.

Verification: pnpm check (which runs pnpm tsgo + lint + the auth/webhook checks) is clean. Targeted retry suites pass: provider-retry.test.ts, retry-policy.test.ts, retry.test.ts, openai-transport-stream.test.ts — 68/68 tests. The housekeeping commit incidentally repaired one pre-existing failure in dispatch-from-config.test.ts (a sendPolicy config-shape drift). All other touched test files match HEAD's failure counts; the failing tests in dispatch-from-config, nvidia.test.ts, and ollama.test.ts are pre-existing and unrelated to this PR.

Re: #38640 — happy to defer to whichever design the maintainers prefer; this PR's scope (opt-in models.providers.<name>.retry config + module-scoped runner registry) keeps the surface small and the retry path opt-in by default.

…1443)

Closes the clawsweeper P3 finding asking for a changelog entry for the
new opt-in `models.providers.<name>.retry` feature. Description summarizes
the scope landed across the prior commits (config schema, runner registry,
abort-aware backoff, provider-id normalization, Retry-After parsing, 422
in non-retryable set) so reviewers and downstream users can find the
feature in the next release notes.

Sweep status (responding to bot reviews on this PR):
  - HTTP 422 in isNonRetryableProviderError: already addressed in
    src/infra/retry-policy.ts:176 (no change needed).
  - Register-after-duplicate-key-merge: current loop in
    src/agents/models-config.providers.normalize.ts uses the merged
    next[normalizedKey].retry value with no `continue` short-circuit, so
    duplicate-key merges are correctly covered (no change needed).
  - Changelog entry: this commit.
@Lambdauv

Lambdauv commented May 5, 2026

Copy link
Copy Markdown
Author

Bot-feedback sweep + status update.

Three potentially-unclosed bot points checked, results:

  1. HTTP 422 in isNonRetryableProviderError (greptile P2): already addressed. src/infra/retry-policy.ts:176 reads status === 400 || status === 401 || status === 403 || status === 404 || status === 422. No change needed.

  2. Register-retry-after-duplicate-provider-key-merge (chatgpt-codex P2): the current loop in src/agents/models-config.providers.normalize.ts does NOT use a continue in the duplicate-key path; both the existing (merge) branch and the fresh-insert branch fall through to the registration block, which uses next[normalizedKey]?.retry (the merged value). So duplicate-key merges where only one of the conflicting entries declares retry are correctly handled. The bot's claim was likely against an earlier revision of this loop. No change needed.

  3. Changelog entry (clawsweeper P3): added in commit 6b3ecb2dca — Unreleased / Changes section, summarizes the scope landed across the prior commits (opt-in config schema, module-scoped runner registry rebuilt on every normalization pass, abort-aware backoff, provider-id normalization, Retry-After header parsing on Headers instances, 422 in non-retryable set).

On rebase against current main: the branch is ~14,400 commits behind, and git diff --name-only HEAD..main intersects 28 of the 29 files this PR touches. A rebase or merge would be hours of conflict resolution against changes unrelated to retry logic, with non-trivial regression risk. The competing PR #38640 was closed 2026-05-01, so the prior bot recommendation to choose between them is also resolved. Holding off on rebase pending maintainer guidance — happy to do it (or assist a maintainer who'd prefer to do it at merge-time via squash-rebase) if it would unblock review.

Current status: all bot rounds addressed, CI clean (4 ✓ / 3 skip / 1 cancel — no real failures), no human-maintainer review yet. Ready when a reviewer has cycles.

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 5, 2026
@clawsweeper clawsweeper Bot added the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label May 19, 2026
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels May 19, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 11, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 11, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 12, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 13, 2026
@clawsweeper

clawsweeper Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: configurable connection retry/timeout for provider API calls

1 participant