Skip to content

fix(agents): continue uncached when Google prompt-cache responses fail - #124479

Merged
vincentkoc merged 1 commit into
openclaw:mainfrom
coaiMax:pr/6-google-prompt-cache-json-parse
Aug 30, 2026
Merged

vincentkoc merged 1 commit into
openclaw:mainfrom
coaiMax:pr/6-google-prompt-cache-json-parse

Conversation

@coaiMax

@coaiMax coaiMax commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Related: #123632
Related: #95417
Related: #109754

What Problem This Solves

Fixes an issue where eligible Gemini runs could stop before primary generation when Google prompt-cache creation or refresh returned an invalid successful response, a transport error, or unusable cache metadata.

Prompt caching is an optional optimization. Provider-side cache failures must leave the system prompt, tools, and visible generation path intact unless the caller itself cancelled the run or another authoritative operation failed.

Why This Change Was Made

The repair lives in the Google prompt-cache lifecycle owner. It removes the duplicate JSON reader and uses the shared provider response parser for the existing 1 MiB bound, fatal UTF-8 decoding, JSON parsing, top-level object validation, and credential-safe causes.

Request URL, authentication headers, sentinel resolution, and body serialization are completed before the optional-operation boundary, so construction failures remain fatal. Only fetch, non-2xx handling, response consumption, and automatic response validation degrade to uncached generation. Caller cancellation, transcript-writer authority loss, and primary stream failures remain fatal.

Automatic and persisted cache names share one transport-stability validator. It requires the cachedContents/ prefix, a nonempty id other than . or .., and a throw-safe encodeURIComponent(id) === id result. This follows Google's published cachedContents/{id} contract while ensuring the maintained SDK's raw resource-name interpolation cannot alter the request URL. Ready state requires a parseable future expiry. Invalid ready entries rebuild, valid existing caches survive malformed refresh responses, and the existing failed-create backoff remains best effort.

This cache state is transient. There is no migration, configuration, schema, protocol, public API, or security-contract change. Explicit operator-provided cachedContent remains untouched.

The contributor's original approach was discarded because wrapping the local JSON.parse still left a duplicate parser and allowed optional cache failures to abort the primary stream.

User Impact

Gemini users continue receiving normal uncached output when automatic prompt-cache creation or refresh fails or returns malformed metadata. Valid caches and explicit operator cache references continue working as before.

Contributor credit is preserved with the public noreply coauthor trailer for @coaiMax.

Evidence

  • Before repair: malformed successful cache JSON rejected before the primary stream; innerCalls=0 and no visible generation output.
  • After repair: the same failure records transient backoff and proceeds through the unchanged uncached system prompt/tools path.
  • Persisted-name regression: files/cache-id previously bypassed creation with zero cache fetches. It now triggers one rebuild and injects cachedContents/rebuilt.
  • Resource-name contract: the current Google Generative Language v1beta Discovery document (revision 20260829) describes CachedContent.name as cachedContents/{id} and constrains get/update path parameters with ^cachedContents/[^/]+$: https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta
  • Maintained SDK proof: OpenClaw's pinned @google/genai v2.18.0 source calls the name server-generated, then performs raw path substitution before new URL(): https://github.com/googleapis/js-genai/blob/128781fdfec5d33f24d8305d90964f3b75b0774f/src/types.ts#L6227-L6229, https://github.com/googleapis/js-genai/blob/128781fdfec5d33f24d8305d90964f3b75b0774f/src/_common.ts#L9-L21, https://github.com/googleapis/js-genai/blob/128781fdfec5d33f24d8305d90964f3b75b0774f/src/caches.ts#L332-L386, and https://github.com/googleapis/js-genai/blob/128781fdfec5d33f24d8305d90964f3b75b0774f/src/_api_client.ts#L443-L455.
  • Transport-stability pre-fix reproduction: 12 focused cases failed on the prior regex. C0 controls, DEL/C1, lone high/low surrogates, and NFC/NFD Unicode creation names stripped the prompt/tools; representative persisted names bypassed rebuild; and a failed rebuild still suppressed uncached input.
  • Transport-stability regression: automatic creation rejects controls, DEL/C1, whitespace, non-ASCII NFC/NFD, lone surrogates, slash/backslash, query/fragment delimiters, percent escapes, and dot segments. Every case preserves the original uncached system prompt/tools, omits cachedContent, and records the existing 10-minute backoff.
  • Persisted invalid names never form a PATCH URL: representative encoded and throwing cases rebuild through the exact create URL, and a failed rebuild continues uncached. A valid punctuation id preserved by encodeURIComponent uses the exact PATCH URL. An otherwise-invalid explicit operator reference still bypasses automatic validation unchanged.
  • Fixture proof through real buildGuardedModelFetch: a controlled loopback server returns malformed cache-creation JSON, then a valid generation stream. The generation endpoint is reached and emits visible-generation-output.
  • This is fixture proof, not live Google proof. A real Google cache creation is an external write, and Google cannot be made to reliably return malformed JSON with a successful status, so the reported malformed-success response is not concretely inducible against the live service.
  • Final focused owner suite: 73/73 passed.
  • Relevant maintainer suite: 92/92 passed, including parser, lifecycle, runner integration, backoff, cancellation, authority, primary-stream, explicit-cache coverage, and the guarded-loopback fixture.
  • Mandatory exact-commit autoreview and an independent exact-commit review both found no P0/P1 issue.
  • Core types, core/targeted lint, formatting, assertion-safety ratchet, max-lines ratchet, dead-export scans, and targeted repository contracts passed.
  • Production LOC: +101/-99 (net +2). The small positive delta is the required prefix/id validation plus the throw-safe URI stability check; the duplicate parser and old lifecycle paths remain deleted.
  • Tests and test support: +849/-182 (net +667), covering the requested malformed-response, transport-stability, and lifecycle matrix.
  • The pushed commit is GitHub-verified, authored by the authenticated maintainer, and preserves @coaiMax only through the public noreply coauthor trailer.
  • Full local build/type aggregation is limited by the linked checkout's existing pako environment state: ui:build sees its CommonJS named-export mismatch, and the core-test type graph reports the missing declaration at ui/vite.config.ts:9. The changed core typecheck and focused tests pass; no dependency installation or unrelated repair was included.

@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Aug 16, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 8:48 AM ET / 12:48 UTC.

ClawSweeper review

What this changes

The PR makes automatic Google prompt-cache create and refresh failures continue through normal uncached generation, with validation and lifecycle regression coverage.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

This PR remains necessary and appears correct: current main still lets a malformed successful cache response abort before generation, while the introduced cache-owner path degrades to uncached generation and preserves cancellation and transcript authority failures.

Priority: P1
Reviewed head: d911810347fd2418f65f927125a499050cf3921e

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) The repair is focused, uses the canonical bounded parser, resolves prior name-safety findings, and has directly relevant boundary coverage.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The changed production owner is exercised through a controlled loopback cache failure followed by the real guarded model-fetch boundary, with the suite asserting the generation endpoint returns visible output; the supplied evidence also covers the preserved fatal abort and transcript-claim paths. This is sufficient injected-fault transport proof for this internal reliability repair.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The changed production owner is exercised through a controlled loopback cache failure followed by the real guarded model-fetch boundary, with the suite asserting the generation endpoint returns visible output; the supplied evidence also covers the preserved fatal abort and transcript-claim paths. This is sufficient injected-fault transport proof for this internal reliability repair.
Evidence reviewed 6 items Current-main defect remains: The fetched main branch has no change to the prompt-cache owner since this PR's base; its successful-response parser and metadata path can still throw before the wrapper reaches uncached generation.
Introduced owner-boundary repair: The introduced request owner converts cache fetch, response-read, JSON-object, and metadata failures to no cache reference, while rethrowing an already-aborted caller signal.
Caller and downstream invariant: The run setup installs the wrapper before prompt submission; the wrapper passes the untouched context to the original stream when no cache is available. The Google transport only omits live prompt and tools when cachedContent is present.
Findings None None.
Security None None.

How this fits together

Google prompt caching is an optional embedded-agent optimization that prepares a cache reference before a Gemini generation request. A valid reference lets the Google transport omit duplicated prompt/tool payloads; an unavailable reference must leave the original generation request intact.

flowchart LR
  A[Embedded Gemini run] --> B[Prompt cache lifecycle]
  B --> C[Create or refresh cache]
  C --> D{Valid cache metadata?}
  D -->|Yes| E[Generation with cached prompt]
  D -->|No| F[Generation with original prompt and tools]
  E --> G[Visible model output]
  F --> G
Loading

Before merge

  • Complete next step (P2) - This active PR already owns the bounded repair; there is no separate mechanical repair task to queue.
Agent review details

Security

None.

PR surface

Source +176, Tests +494, Other 0. Total +670 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 275 99 +176
Tests 2 675 181 +494
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 5 951 281 +670

Review metrics

Metric Value Why it matters
Production versus test delta production +2 net; tests and test support +667 net The production growth is limited to cache-name and future-expiry validation while consolidating the prior create/refresh and JSON-reader paths.

Stored data model

Persistent data-model change detected: persistent cache schema: config/assertion-safety-baseline.txt, persistent cache schema: src/agents/embedded-agent-runner/google-prompt-cache.test-support.ts, serialized state: src/agents/embedded-agent-runner/google-prompt-cache.test-support.ts, unknown-data-model-change: src/agents/embedded-agent-runner/google-prompt-cache.test-support.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #124479
Summary: This is the active canonical repair for optional Google prompt-cache failures aborting primary generation; the cited prior work is complementary or superseded.

Members:

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

Technical review

Best possible solution:

Keep the cache failure policy at this lifecycle owner: validate metadata before suppressing the live prompt and tools, then merge once the exact-head required checks complete.

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

Yes, source-reproducible: current main awaits successful cache-response parsing before the uncached branch, so malformed metadata prevents the original stream from running; the introduced owner suite directly exercises that path.

Is this the best way to solve the issue?

Yes. The repair handles failure at the optional cache lifecycle owner and preserves the downstream transport's existing invariant that prompt/tools are omitted only with a validated cache reference.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: Without this repair, an eligible Gemini run can terminate before its primary generation path after an optional cache response failure.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The changed production owner is exercised through a controlled loopback cache failure followed by the real guarded model-fetch boundary, with the suite asserting the generation endpoint returns visible output; the supplied evidence also covers the preserved fatal abort and transcript-claim paths. This is sufficient injected-fault transport proof for this internal reliability repair.
  • remove P2: Current review triage priority is P1, so this older priority label is no longer current.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove merge-risk: 🚨 availability: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Without this repair, an eligible Gemini run can terminate before its primary generation path after an optional cache response failure.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The changed production owner is exercised through a controlled loopback cache failure followed by the real guarded model-fetch boundary, with the suite asserting the generation endpoint returns visible output; the supplied evidence also covers the preserved fatal abort and transcript-claim paths. This is sufficient injected-fault transport proof for this internal reliability repair.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed production owner is exercised through a controlled loopback cache failure followed by the real guarded model-fetch boundary, with the suite asserting the generation endpoint returns visible output; the supplied evidence also covers the preserved fatal abort and transcript-claim paths. This is sufficient injected-fault transport proof for this internal reliability repair.

Evidence

What I checked:

Likely related people:

  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • krissding: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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.

History

Review history (8 earlier review cycles)
  • reviewed 2026-08-16T07:56:35.482Z sha 1b77c6f55e2409b974849e0633bd6d3138263ebb :: needs real behavior proof before merge. :: none
  • reviewed August 21, 2026, 8:56 PM ET / August 22, 2026, 00:56 UTC sha unknown :: needs real behavior proof before merge. :: none
  • reviewed August 23, 2026, 1:10 AM ET / 05:10 UTC sha unknown :: needs real behavior proof before merge. :: [P1] Use the shared bounded provider JSON reader
  • reviewed 2026-08-23T05:10:30.341Z sha 1b77c6f55e2409b974849e0633bd6d3138263ebb :: needs real behavior proof before merge. :: [P1] Use the shared bounded provider JSON reader
  • reviewed 2026-08-29T06:00:49.859Z sha 1b77c6f55e2409b974849e0633bd6d3138263ebb :: needs real behavior proof before merge. :: [P1] Use the shared bounded provider JSON reader
  • reviewed 2026-08-30T11:29:09.934Z sha 7fd8c4be0aeafe64b35ce184fce49a2b95d9ee69 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T11:40:09.987Z sha 7fd8c4be0aeafe64b35ce184fce49a2b95d9ee69 :: needs changes before merge. :: [P1] Reject URL-delimiter characters in automatic cache names
  • reviewed 2026-08-30T12:17:48.754Z sha ebd3b91e0b8caf70aa0c57fa8d2bdabc1f43ecb0 :: needs changes before merge. :: [P1] Reject Unicode-unsafe automatic cache names

@vincentkoc
vincentkoc force-pushed the pr/6-google-prompt-cache-json-parse branch from 1b77c6f to 7fd8c4b Compare August 30, 2026 11:19
@vincentkoc vincentkoc changed the title fix(agents): wrap JSON.parse in try/catch in readGooglePromptCacheJson fix(agents): continue uncached when Google prompt-cache responses fail Aug 30, 2026
@vincentkoc vincentkoc self-assigned this Aug 30, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Aug 30, 2026
@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 30, 2026
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 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 exact_review_queue).
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 merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. and removed 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 30, 2026
@vincentkoc
vincentkoc force-pushed the pr/6-google-prompt-cache-json-parse branch from 7fd8c4b to ebd3b91 Compare August 30, 2026 12:09
@vincentkoc
vincentkoc force-pushed the pr/6-google-prompt-cache-json-parse branch from ebd3b91 to d911810 Compare August 30, 2026 12:41
@clawsweeper clawsweeper Bot removed the P2 Normal backlog priority with limited blast radius. label Aug 30, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 30, 2026
@vincentkoc

Copy link
Copy Markdown
Member

ClawSweeper disposition for the August 30 review on ebd3b91e:

  • Reject Unicode-unsafe automatic cache names (P1): resolved. The shared automatic-name boundary now requires the exact cachedContents/ prefix, a nonempty id other than . or .., and a throw-safe encodeURIComponent(id) === id. This rejects controls, C1/DEL, whitespace, NFC/NFD Unicode, lone high/low surrogates, slash/backslash, ?, #, %, encoded separators, and every other value changed or rejected by URI serialization. Explicit operator-provided cachedContent remains untouched.
  • Resolve merge risk (P2): resolved. Automatic creation and persisted-ready invalid-name cases retain the original system prompt/tools, omit cachedContent, and record the existing backoff when rebuilding fails. Invalid persisted names never issue PATCH.
  • Complete next step (P2): complete. The transport-stability cases produced 12 intended pre-fix failures. The final focused owner suite passes 73/73 and the relevant parser/cache/runner suite passes 92/92. A valid punctuation id that encodeURIComponent preserves uses the exact expected PATCH URL, while an otherwise-invalid explicit operator reference still bypasses automatic validation unchanged.
  • Rank-up: reject controls and lone surrogates: applied. Both C0 examples, DEL/C1, and lone high/low surrogate cases are covered.
  • Rank-up: create and persisted-ready uncached proof: applied. Both lifecycle paths prove unchanged uncached prompt/tools; the guarded loopback fixture still reaches generation and emits visible output after malformed cache creation.

Contract basis: Google publishes the resource shape as cachedContents/{id}. The pinned maintained googleapis/js-genai implementation substitutes that resource name raw into the PATCH URL before URL parsing, so transport stability is the owner invariant rather than an invented provider-id character grammar:

Production is +101/-99 (net +2); tests/support are +849/-182. Exact-commit Codex and independent Claude autoreviews found no P0/P1 issue, and native review artifacts are READY FOR /prepare-pr. Exact-head CI is green at posting.

@vincentkoc
vincentkoc merged commit 715760d into openclaw:main Aug 30, 2026
266 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

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

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XL 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.

2 participants