Skip to content

fix: preserve original JSON bytes in normalizeCacheControlTTL#407

Open
thebtf wants to merge 1 commit intorouter-for-me:mainfrom
thebtf:fix/normalize-ttl-byte-preservation
Open

fix: preserve original JSON bytes in normalizeCacheControlTTL#407
thebtf wants to merge 1 commit intorouter-for-me:mainfrom
thebtf:fix/normalize-ttl-byte-preservation

Conversation

@thebtf
Copy link

@thebtf thebtf commented Mar 3, 2026

Summary

  • normalizeCacheControlTTL unconditionally re-serializes the entire request body through json.Unmarshaljson.Marshal, even when no TTL normalization is needed
  • Go's json.Marshal(map[string]any) randomizes map key order and HTML-escapes <, >, & (→ \u003c, \u003e, \u0026), producing different raw bytes on every call
  • Anthropic's prompt caching uses byte-prefix matching — any byte-level difference causes a cache miss, so the ~119K system prompt + tools are re-processed on every request routed through CPA

Changes

  • normalizeTTLForBlock now returns bool indicating whether it modified the block
  • normalizeCacheControlTTL tracks a modified flag and returns the original payload slice unchanged when no TTL downgrade was needed
  • New test TestNormalizeCacheControlTTL_PreservesOriginalBytesWhenNoChange verifies exact byte preservation (including HTML chars that json.Marshal would escape)

Test plan

  • go build ./... — clean build
  • go test ./internal/runtime/executor/... -run TestNormalizeCacheControlTTL — both tests pass
  • go test ./internal/runtime/executor/... — all existing tests unaffected
  • Deploy and verify prompt cache hit rate improves (cache_read tokens should be ~95%+ after warmup)

… TTL change needed

normalizeCacheControlTTL unconditionally re-serializes the entire request
body through json.Unmarshal/json.Marshal even when no TTL normalization
is needed. Go's json.Marshal randomizes map key order and HTML-escapes
<, >, & characters (to \u003c, \u003e, \u0026), producing different raw
bytes on every call.

Anthropic's prompt caching uses byte-prefix matching, so any byte-level
difference causes a cache miss. This means the ~119K system prompt and
tools are re-processed on every request when routed through CPA.

The fix adds a bool return to normalizeTTLForBlock to indicate whether
it actually modified anything, and skips the marshal step in
normalizeCacheControlTTL when no blocks were changed.
@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request optimizes the normalizeCacheControlTTL function to prevent unnecessary re-serialization of JSON request bodies. Previously, this process could alter byte-level representations, causing cache misses in systems that rely on exact byte-prefix matching. By conditionally returning the original payload when no cache control TTL normalization is needed, the changes aim to improve cache hit rates for prompt caching.

Highlights

  • Conditional JSON Re-serialization: The normalizeCacheControlTTL function now avoids unnecessary JSON re-serialization by returning the original byte payload if no modifications to cache control TTLs were made.
  • Function Signature Update: The normalizeTTLForBlock function's signature was updated to return a boolean, indicating whether it modified the block it processed.
  • Modification Tracking: A new modified flag was introduced in normalizeCacheControlTTL to track if any cache control TTLs were actually altered during processing.
  • Byte Preservation Test: A new test case, TestNormalizeCacheControlTTL_PreservesOriginalBytesWhenNoChange, was added to explicitly verify that original JSON bytes are preserved when no TTL normalization is required, including handling HTML-escaped characters.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • internal/runtime/executor/claude_executor.go
    • Modified normalizeTTLForBlock to return a boolean indicating if the block was altered.
    • Introduced a modified flag in normalizeCacheControlTTL to track if any cache_control TTLs were changed.
    • Added a conditional return in normalizeCacheControlTTL to pass back the original payload if no modifications occurred.
  • internal/runtime/executor/claude_executor_test.go
    • Implemented TestNormalizeCacheControlTTL_PreservesOriginalBytesWhenNoChange to verify byte-level preservation when no TTL changes are applied, including HTML characters.
Activity
  • A clean build (go build ./...) was performed successfully.
  • Specific tests for TestNormalizeCacheControlTTL passed.
  • All existing tests passed, indicating no regressions.
  • Verification of prompt cache hit rate improvement is planned for post-deployment.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request correctly addresses an issue where normalizeCacheControlTTL would always re-serialize the JSON payload, causing unnecessary cache misses due to byte-level differences. The change to return the original byte slice when no modifications are made is a solid improvement for performance and correctness. The addition of a new test case to verify this behavior is also great. I have one suggestion to improve code maintainability by reducing some duplication.

Comment on lines 1553 to 1571
if tools, ok := asArray(root["tools"]); ok {
for _, tool := range tools {
if obj, ok := asObject(tool); ok {
normalizeTTLForBlock(obj, &seen5m)
if normalizeTTLForBlock(obj, &seen5m) {
modified = true
}
}
}
}

if system, ok := asArray(root["system"]); ok {
for _, item := range system {
if obj, ok := asObject(item); ok {
normalizeTTLForBlock(obj, &seen5m)
if normalizeTTLForBlock(obj, &seen5m) {
modified = true
}
}
}
}

Choose a reason for hiding this comment

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

medium

The logic for iterating over tools and system arrays is identical. This pattern is also repeated for the content array within each message. To improve maintainability and reduce code duplication, consider extracting this iteration logic into a local helper function.

For example:

processItems := func(items []any) {
    for _, item := range items {
        if obj, ok := asObject(item); ok {
            if normalizeTTLForBlock(obj, &seen5m) {
                modified = true
            }
        }
    }
}

if tools, ok := asArray(root["tools"]); ok {
    processItems(tools)
}
// ... and so on for system and messages content

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant