Skip to content

fix(providers): preserve prompt-cache accounting and affinity - #168145

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-prompt-cache-other-providers-20260919
Oct 10, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-prompt-cache-other-providers-20260919

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Provider cache hits can disappear from accounting, absent telemetry can look like a real cache drop, and several native endpoints receive no supported session-affinity hint. Gemini cached-content handles can survive credential/project changes, while older Bedrock Claude models receive unsupported one-hour checkpoints.

User Impact

Cache diagnostics distinguish unavailable telemetry from measured misses. Native Together, Cerebras, DeepInfra, Venice, Fireworks, and Baseten requests carry supported affinity hints while preserving caller overrides and opt-outs. Gemini cache creation and inference share the owning credential scope; older Bedrock Claude keeps valid five-minute checkpoints. Cerebras cached input and Moonshot K3 cache writes use documented tariffs.

No new configuration, dependency, schema, paid retention default, or migration is required. Server hit rates remain provider-dependent.

Why This Change Was Made

Existing owners absorb the corrections: the shared Completions parser accepts documented top-level cached counts; the observer retains its measured baseline when telemetry is unavailable; plugins declare native-endpoint capability; Gemini includes effective request headers in its existing cache identity. Fireworks uses validated dedicated-deployment headers only when body cache telemetry is absent, preserving explicit zero and provider-billed totals. The existing SDK stream transform consumes typed message events and skips absent sparse snapshots.

Production delta: +167 net lines (258 added / 91 removed, excluding tests, test support, and docs). Distinct wire and billing contracts require this growth, principally native affinity declarations and Fireworks header accounting. Existing cache owners are reused, redundant casts are removed, and serialized Gemini tool configuration becomes a fixed digest.

Evidence

Synthetic before/after: a 100-prompt/25-cached Completions response changes from 0 recognized cached tokens to 25; a Fireworks 100-prompt/80-cached header fixture changes from 0 to 80. Missing telemetry no longer produces a measured drop. Original-source regressions also reproduce credential/project reuse, unsupported TTLs, omitted affinity, and tariff errors.

Direct Gemini 2.5 Flash-Lite controls: three immediate implicit-cache generations reported 0/19,659 cached prompt tokens (910/1,048/1,643 ms); explicit caching reused 6,533/6,543 prompt tokens (99.847%, 466 ms). The resource was deleted. These are mechanism controls, not before/after Gateway benchmarks. Total: six API calls, 26,202 prompt tokens including 6,533 cached, five output tokens, approximately $0.002034 generation cost or $0.00323 with conservative storage/creation allowance. Other providers remain live-unmeasured; their proof uses documented contracts and synthetic request/usage boundaries.

Remote validation, with no local builds, suites, or typechecks:

  • AWS cbx_f44deb8e681d, run_c8131a256da91e880cb2151905083f4b: original-source replays and 336 focused tests passed. node scripts/run-vitest.mjs <14 files> --maxWorkers=1 took 69.93 s; the whole command with baseline replays took 160.028 s.
  • AWS cbx_37c1e4a40558, run_2fc8f9fca50201ca99bd9474d5caa017: export collision guard passed (32 s), eager-import/pr-wrapper closure and publisher tests passed (86 tests, 35 s), all non-live siblings in eight touched provider directories plus Completions/cache/usage siblings passed (six shards, 161.19 s), and full build passed (328 s).
  • Hetzner cbx_4d1b72933eff, run_3eef979c5168b3934588e1a56417f1c4: full build including the typed SDK implementation passed (461 s). Later fixture/style corrections are covered by the final tests, types, and lint.
  • Authorized Linux rig fallback: the changed-file plan passed all 27 core-test typecheck shards, production typechecks, ratchets, formatting, closure, and remaining structural checks. Fixture type errors were corrected; extension-test types and all root-test types then passed. Rebase-affected SDK/Cerebras/publisher tests: 88 passed, 106.87 s. Kimi/observer replay: 9.53 s. Google: 22 passed, 38.04 s (86% transformation, 9% test execution); it exercises the existing cache lifecycle and serialized transport without a new process fixture.
  • Final AWS cbx_5abb1b986311, run_b481ee4c26d7d0bbd23cdda52752d899: hashes verified for all 43 changed paths; corrected Baseten/Fireworks/Moonshot tests passed in 80.40 s, complete extension-test typecheck passed (31 s), full core lint passed (497 s, zero errors), full extension lint passed (377 s, zero warnings/errors). Whole command: 989.183 s; source transfer: 364.243 s. This dedicated lease resolved the shared rig's lint OOM and declaration-preparation timeout.
  • Independent Codex reviews are scoped-clean at P0–P2, including the final corrections. No new module/export/test file was added; the verified SDK assertion baseline shrinks from nine to seven.

Rebased for overlapping SDK/publisher changes: the production patch was preserved and only an expectation in a test main removed was dropped. The configured Blacksmith lease did not acquire a runner; AWS/Hetzner and the authorized rig supplied actual proof. Final-head CI run 38027351241 passed in 499 s wall time; its 21 successful Node test jobs totaled 2659 job-seconds (longest 256 s). Long-lived eviction, replica affinity, local-engine residency, and authenticated Bedrock/Vertex behavior remain unmeasured.

Recognize documented cache counters, preserve unavailable telemetry, bind Gemini cached resources to effective credentials, and apply native affinity and billing contracts.
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR corrects cache accounting, diagnostics, provider affinity, Gemini credential scoping, Bedrock checkpoints, and cached-token pricing.

Example: A Completions response reports prompt_tokens=100, completion_tokens=20, and top-level cached_tokens=25.

  • Before: OpenClaw records 100 uncached input tokens and 0 cached tokens.
  • After: OpenClaw records 75 uncached input tokens and 25 cached tokens.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful owner-level corrections with meaningful in-process coverage and no actionable code findings; confidence does not support a merge-ready verdict.
Proof confidence 🦐 gold shrimp (3/6) The supplied maintainer authorship exempts ordinary contributor proof; inspected evidence exercises production request/accounting boundaries in process, while the direct Gemini controls do not exercise the changed Gateway owner. Persisted-data compatibility remains insufficient: supplied fixtures use candidate-generated identities rather than a session upgraded from v2026.9.9.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Users can receive incorrect cache usage and cost estimates, misleading cache-drop diagnostics, and invalid or credential-mismatched provider cache requests.
Reason: Source and provider contracts establish concrete defects, and the supplied maintainer authorship provides direction for these existing-owner corrections.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this PR repairs current provider-cache defects through existing owners, and no introduced correctness defect was identified.

Priority: P2
Reviewed head: b637e2aa734755696fd0d168f89d3c1a98cc8249

Before merge

  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Provide a latest-stable-to-head Gemini session upgrade showing old cache metadata rebuilds safely, cached inference keeps the owning credentials, and settings and transcript data remain intact.
Agent review details

How this fits together

Provider plugins prepare request policy, transports exchange provider payloads, and shared usage accounting feeds session summaries and cache diagnostics; Gemini separately manages provider cache resources through persisted session metadata.

flowchart TD
A[Agent request] --> B[Provider plugin policy]
B --> C[Provider transport]
C --> D[Provider API]
D --> E[Shared usage accounting]
E --> F[Cache diagnostics]
B --> G[Gemini cache lifecycle]
G --> C
G --> H[Session metadata]
Loading

Technical review

Best possible solution:

Keep provider policy in plugins and repair accounting and cache lifecycle through their existing shared owners.

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

Current-main source establishes omitted top-level cached counts, unavailable telemetry updating the measured baseline, credential-independent Gemini cache identity, and unsupported long TTLs; no target code was executed during this review.

Is this the best way to solve the issue?

The patch uses existing owners, preserves explicit overrides and native-endpoint boundaries, retains provider-billed totals, and keeps optional Gemini cache failures recoverable.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against db74f466dcbe.

Provenance checked

  • Shared Completions accounting keeps the original intent (ed84162: Unify managed and package accounting while preserving disjoint token buckets and provider-billed totals.)
  • Prompt-cache diagnostics keeps the original intent (c76646a: Explain cache-reuse drops through request fingerprints without changing provider cache policy.)
  • Google optional-cache recovery keeps the original intent (715760d: Continue uncached after optional provider-cache failures while preserving cancellation and authoritative construction or transcript failures.)
  • Bedrock checkpoint TTL changes intended behavior with a stated reason (5eb6a2b: Centralize model-aware checkpoints while preserving Claude behavior and strictly opt-in Nova caching; this PR explains the model-specific Claude TTL correction.)
  • Cerebras pricing changes intended behavior with a stated reason (8affd61: Use native pricing metadata while retaining explicit configured prices; this PR supplies the documented standard-input cache-read tariff.)
  • Moonshot K3 pricing changes intended behavior with a stated reason (42ff5ec: Add K3 through existing provider owners using official model and pricing contracts; this PR corrects separately reported cache-write pricing.)
  • Fireworks Kimi request policy keeps the original intent (3e062ac: Prevent visible reasoning leaks by forcing thinking off and removing reasoning fields.)
  • SDK message transformation keeps the original intent (61cb9d0: Centralize provider stream-message transformations while preserving message objects and event order.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit cee0906 adds src/agents/embedded-agent-runner/prompt-cache-observability.ts:349 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cee0906f3877; files: src/agents/embedded-agent-runner/prompt-cache-observability.ts)
  • Vincent Koc: Raw commit c76646a adds src/agents/pi-embedded-runner/prompt-cache-observability.ts:182 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c76646adb135; files: src/agents/pi-embedded-runner/prompt-cache-observability.ts)
  • coaiMax: Raw commit 715760d adds src/agents/embedded-agent-runner/google-prompt-cache.ts:416 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 715760d1c718; files: src/agents/embedded-agent-runner/google-prompt-cache.ts)

PR surface

Source +167, Tests +755, Docs +79, Other 0. Total +1001 across 43 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 19 257 90 +167
Tests 15 897 142 +755
Docs 8 82 3 +79
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 43 1237 236 +1001

Labels

Label changes:

No label changes.

Label justifications:

  • P2: These are bounded provider accounting and cache-request defects without evidence of a widespread urgent outage.
  • merge-risk: 🚨 compatibility: The public SDK transformer changes callback typing and event visitation; the supplied maintainer-authored direction accepts that change, and bundled-consumer coverage preserves supported typed streams.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-10T03:27:02.491Z sha 415d1b8 :: blocked before merge. :: none
  • reviewed 2026-10-10T05:29:11.790Z sha b637e2a :: blocked before merge. :: none

Reviewed October 10, 2026, 1:45 AM ET / 05:45 UTC (Revision 3).

@steipete
steipete marked this pull request as ready for review October 10, 2026 05:23
@steipete
steipete merged commit 96c8ba5 into main Oct 10, 2026
217 checks passed
@steipete
steipete deleted the steipete/perf-micro-prompt-cache-other-providers-20260919 branch October 10, 2026 05:58
steipete added a commit that referenced this pull request Oct 10, 2026
#168145 (96c8ba5) added cacheTelemetry to usage, but the successful-trace parity fixture was never refreshed, so provider-transport-parity fails on main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…aw#168145)

* fix(providers): preserve prompt-cache accounting and affinity

Recognize documented cache counters, preserve unavailable telemetry, bind Gemini cached resources to effective credentials, and apply native affinity and billing contracts.

* fix(providers): satisfy cache boundary type and lint checks
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
openclaw#168145 (b348c67) added cacheTelemetry to usage, but the successful-trace parity fixture was never refreshed, so provider-transport-parity fails on main.
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: amazon-bedrock extensions: baseten Extension: baseten extensions: cerebras extensions: deepinfra extensions: fireworks extensions: kimi-coding extensions: moonshot extensions: together extensions: venice merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant