Skip to content

fix(agents): separate retry count from API key position (#102938) - #115507

Merged
obviyus merged 1 commit into
openclaw:mainfrom
ruel225:v2/api-key-retry-attempt
Aug 28, 2026
Merged

obviyus merged 1 commit into
openclaw:mainfrom
ruel225:v2/api-key-retry-attempt

Conversation

@ruel225

@ruel225 ruel225 commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Make attempt the one-based execution count for the current API key.
  • Add apiKeyIndex as the zero-based key position.
  • Keep same-key retries and API-key rotation in their existing order.

What Problem This Solves

API-key rotation tracked both a one-based retry count and a zero-based key position. The callback field named attempt received the key position, so callbacks could not tell a same-key retry from a move to another key.

Fixes #102938

Why This Change Was Made

The rotation owner now builds one callback context from the current execution. attempt comes from the per-key execution loop, while apiKeyIndex comes from the key loop. Both shouldRetry and onRetry receive that same context.

The earlier attemptNumber callback field from #103577 was not retained. It never shipped, and it duplicated the corrected attempt field. The separate transient-retry classifier keeps its existing attemptNumber contract.

Compatibility

Maintainer decision: Accept the semantic correction to attempt. A stable release exposed the old index-valued callback through plugin-sdk/provider-auth-runtime, but that subpath is now private-local and JavaScript-only. No in-repo caller supplies either rotation callback.

Private-local consumers must read key position from apiKeyIndex after this change. Keeping index position in attempt would preserve the reported naming defect, while adding attemptNumber would create a second name for the same retry count.

User Impact

  • Before: callbacks reported key positions as attempt, such as 0, 0, 1 across two keys.
  • After: callbacks report per-key executions as attempt (1, 2, 1) and key positions as apiKeyIndex (0, 0, 1).

Evidence

Real behavior proof: The production executeWithApiKeyRotation owner ran with two controlled keys. The first key failed twice, the second key failed once, and the fourth execution succeeded. The second callback requested rotation. Both revisions executed key-1, key-1, key-2, key-2 and performed two same-key retry sleeps.

  • Exact main 629a47e3cc20a9f8b6d19c105f840b8a693ec4aa: attempt was 0, 0, 1; apiKeyIndex was absent.
  • Exact head ee3e95ac04e85d2324881d25bac18a473b09f06a: attempt was 1, 2, 1; apiKeyIndex was 0, 0, 1; attemptNumber was absent.
  • onRetry received attempt: 2 and apiKeyIndex: 0 before rotation.
{
  "contractPass": true,
  "result": "ok:key-2",
  "executions": ["key-1", "key-1", "key-2", "key-2"],
  "sameKeyRetrySleeps": 2,
  "shouldRetry": [
    { "attempt": 1, "apiKeyIndex": 0 },
    { "attempt": 2, "apiKeyIndex": 0 },
    { "attempt": 1, "apiKeyIndex": 1 }
  ],
  "onRetry": [{ "attempt": 2, "apiKeyIndex": 0 }],
  "attemptNumberPresent": false
}

Regression test: node scripts/run-vitest.mjs src/agents/api-key-rotation.test.ts

  • Exact main with the regression test: 1 failed, 22 passed for the callback mismatch.
  • Exact head: 23 passed.

Changed-scope checks: formatting, lint, production types, test types, dependency checks, dead-export checks, import-cycle checks, and selected repository guards passed.

Production LOC: +8/-8 (net 0) | Tests: +41/-0

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 29, 2026
@ruel225 ruel225 closed this Jul 29, 2026
@ruel225 ruel225 reopened this Jul 29, 2026
@ruel225 ruel225 closed this Jul 29, 2026
@ruel225 ruel225 reopened this Jul 29, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jul 29, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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. labels Jul 29, 2026
@clawsweeper

clawsweeper Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 24, 2026, 9:34 PM ET / August 25, 2026, 01:34 UTC.

ClawSweeper review

What this changes

The PR makes API-key rotation callbacks report the one-based per-key retry count as attempt and adds apiKeyIndex for the zero-based key position.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

Keep open. This is a coherent, narrow repair: current main passes the key position as attempt while maintaining a separate retry counter, and the PR exposes both meanings clearly. Current in-repo users do not pass rotation callbacks, and the documented provider-auth runtime facade is private-local.

Likely related people: Peter Steinberger, based on current-main line attribution (low confidence due shallow local history).

Priority: P2
Reviewed head: 3c01f48cdebf7195468091148236607d07a0030a

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused implementation, direct regression coverage, successful supplied checks, and an after-fix runtime transcript support normal merge review.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR body includes an exact-head terminal transcript from the real rotation helper showing retry ordinals and key positions diverging across two keys.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body includes an exact-head terminal transcript from the real rotation helper showing retry ordinals and key positions diverging across two keys.
Evidence reviewed 6 items Current-main defect: Current main tracks attemptNumber per key but supplies apiKeyIndex as the callback field named attempt, so the callback cannot distinguish retry ordinal from key position.
Narrow repair: The branch passes the existing one-based counter as attempt and the key position separately as apiKeyIndex at both callback dispatches.
Regression coverage: The added divergent-counter test covers two keys and same-key retries, asserting that retry ordinal resets for the next key while apiKeyIndex changes.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/agents/api-key-rotation.test.ts

Result: FAIL (partial) — step 2 expect_output diverges attempt (retry count) from apiKeyIndex: expected terminal output was not visible within 30 seconds: "diverges attempt (retry count) from apiKeyIndex"

node scripts/run-vitest.mjs src/agents/api-key-rotation.test.ts
runner@runnervm76f27:/tmp/clawsweeper-live-proof-115507-xDI6lO/target$ node scripts/run-vitest.mjs src/agents/api-key-rotation.test.ts
node scripts/run-vitest.mjs src/agents/api-key-rotation.test.ts
[test] starting test/vitest/vitest.agents-core.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-115507-xDI6lO/target

 ✓  agents-core  src/agents/api-key-rotation.test.ts (21 tests) 129ms

 Test Files  1 passed (1)
      Tests  21 passed (21)
   Start at  01:35:00
   Duration  7.08s (transform 5.35s, setup 912ms, import 5.82s, tests 129ms, environment 0ms)

[test] passed 1 Vitest shard in 11.34s
runner@runnervm76f27:/tmp/clawsweeper-live-proof-115507-xDI6lO/target$ node scripts/run-vitest.mjs src/agents/api-key-rotation.test.ts
[test] starting test/vitest/vitest.agents-core.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-115507-xDI6lO/target

 ✓  agents-core  src/agents/api-key-rotation.test.ts (21 tests) 68ms

 Test Files  1 passed (1)
      Tests  21 passed (21)
   Start at  01:35:11
   Duration  3.09s (transform 1.44s, setup 388ms, import 2.46s, tests 68ms, environment 0ms)

[test] passed 1 Vitest shard in 7.29s
runner@runnervm76f27:/tmp/clawsweeper-live-proof-115507-xDI6lO/target$






















Assertions:

  • FAIL expect_output: diverges attempt (retry count) from apiKeyIndex

How this fits together

API-key rotation wraps provider operations that fail from a key-specific limit or transient failure. It decides whether to retry the same key, rotate to the next key, or return the final error, and callback consumers receive that retry context.

flowchart LR
A[Provider operation] --> B[API-key rotation]
B --> C[Run current API key]
C --> D{Failure decision}
D --> E[Rotation callback]
D --> F[Same-key retry]
E --> G[Next API key]
F --> C
G --> C
C --> H[Result or final error]
Loading

Before merge

  • Complete next step (P2) - No repair job is needed: the contributor branch is a coherent fix with no source-backed correction to automate.
Agent review details

Security

None.

PR surface

Source +15, Tests +74. Total +89 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 17 2 +15
Tests 1 74 0 +74
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 91 2 +89

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #102938
Summary: This PR directly implements the retry-callback correction described by the linked issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Land the focused callback-contract repair with its regression tests, retaining attempt as the retry ordinal and apiKeyIndex as the distinct key-position field.

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

Yes. Current main directly shows the mismatch: the loop maintains attemptNumber but passes apiKeyIndex to both rotation callbacks as attempt.

Is this the best way to solve the issue?

Yes. Changing the two callback payloads at the rotation owner and adding a divergent-counter regression is the narrowest maintainable fix; existing in-repo consumers do not use these callbacks.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes an exact-head terminal transcript from the real rotation helper showing retry ordinals and key positions diverging across two keys.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes an exact-head terminal transcript from the real rotation helper showing retry ordinals and key positions diverging across two keys.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This repairs a bounded provider retry callback defect with limited blast radius.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes an exact-head terminal transcript from the real rotation helper showing retry ordinals and key positions diverging across two keys.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes an exact-head terminal transcript from the real rotation helper showing retry ordinals and key positions diverging across two keys.

Evidence

What I checked:

  • Current-main defect: Current main tracks attemptNumber per key but supplies apiKeyIndex as the callback field named attempt, so the callback cannot distinguish retry ordinal from key position. (src/agents/api-key-rotation.ts:69, b840a3c84e2c)
  • Narrow repair: The branch passes the existing one-based counter as attempt and the key position separately as apiKeyIndex at both callback dispatches. (src/agents/api-key-rotation.ts:70, 3c01f48cdebf)
  • Regression coverage: The added divergent-counter test covers two keys and same-key retries, asserting that retry ordinal resets for the next key while apiKeyIndex changes. (src/agents/api-key-rotation.test.ts:351, 3c01f48cdebf)
  • Caller and boundary check: Current main has rotation consumers in Google embeddings, Google streaming, and media understanding, but none supplies shouldRetry or onRetry; the provider-auth runtime facade is documented as private-local after July 2026. Public docs: docs/plugins/sdk-subpaths.md. (docs/plugins/sdk-subpaths.md:147, b840a3c84e2c)
  • Feature-history attribution: Local current-main blame attributes the affected callback lines to Peter Steinberger; the available history is shallow, so this is routing evidence rather than a complete feature origin. (src/agents/api-key-rotation.ts:69, 3c2667ca40f1)
  • Validation context: The supplied PR check rollup reports the relevant build, lint, type, guard, smoke, dependency, and CI-gate checks as successful for the reviewed head. (3c01f48cdebf)

Likely related people:

  • Peter Steinberger: git blame on the current callback dispatches attributes the available local history boundary to this author; deeper origin history is unavailable in this checkout. (role: current-main line attribution; confidence: low; commits: 3c2667ca40f1; files: src/agents/api-key-rotation.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 30, 2026
@ruel225

ruel225 commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Added real behavior proof to the PR body: a script driving the real executeWithApiKeyRotation (no mocks) with two fake keys, where the first key returns a rate-limit error. Both shouldRetry and onRetry receive apiKeyIndex: 0, attemptNumber: 1, and the preserved deprecated attempt: 0. The operation succeeds on the retry. No real API keys, endpoints, or network involved.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Jul 30, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 1, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 5, 2026
@ruel225

ruel225 commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

P2 addressed: removed the duplicate attemptNumber field from ApiKeyRetryParams. Rotation callbacks now expose only attempt (canonical retry count) and apiKeyIndex (key position). TransientProviderRetryParams retains its own attemptNumber (separate type, not a rotation callback). 21 tests pass.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 5, 2026
@ruel225

ruel225 commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Re-ran the proof on the exact final head (aa815a46c8b). The transcript now shows only attempt and apiKeyIndex — attemptNumber is no longer emitted (duplicate field removed). PR body Evidence updated to match the submitted head.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 6, 2026
@ruel225

ruel225 commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

The Scan changed paths (precise) CI failure is a GitHub Actions infra issue: it cannot fetch the fork PR's base SHA (branch is ~3450 commits behind main). This is not a code issue — the scan itself reports Secret source: None and no leak was detected before the fetch failed. A rebase to current main would fix it but the branch is too far behind for a clean rebase.

@ruel225

ruel225 commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Updated the PR body to match the final head — removed all references to the deprecated attemptNumber field and the index-valued attempt. The body now describes only attempt (canonicalized retry count) and apiKeyIndex (key position).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 17, 2026
@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper recorded closeout evidence for this proposed close.

  • Action: close remains subject to final live verification.
  • Close reason: lowest-signal PR over the author's open-PR budget.
    Review evidence: durable ClawSweeper review.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 25, 2026
@obviyus

obviyus commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

Thanks @ruel225!

Proof: A controlled two-key run on exact main reported callback attempt values 0, 0, 1 and no apiKeyIndex. The same production path on exact head ee3e95ac04e85d2324881d25bac18a473b09f06a reported attempt values 1, 2, 1 with apiKeyIndex values 0, 0, 1, kept execution order key-1, key-1, key-2, key-2, and passed all 23 focused tests plus exact-head CI.

  • Bug: Retry callbacks exposed API-key position as attempt, so a same-key retry and a move to another key could look identical.
  • Fix: The rotation owner now exposes the one-based per-key execution as attempt and the zero-based key position as apiKeyIndex to both callbacks.

Example

Before After
Second execution on the first key: attempt: 0 with no key-index field Second execution on the first key: attempt: 2, apiKeyIndex: 0

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

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(agents): ApiKeyRetryParams passes apiKeyIndex instead of attemptNumber to attempt parameter

2 participants