Skip to content

fix(core): exclude evicted binary payloads from exempt retrieval byte budget - #30473

Open
bitwizard25 wants to merge 3 commits into
google-gemini:mainfrom
bitwizard25:fix/exempt-retrieval-budget-evicted-binary
Open

bitwizard25 wants to merge 3 commits into
google-gemini:mainfrom
bitwizard25:fix/exempt-retrieval-budget-evicted-binary

Conversation

@bitwizard25

Copy link
Copy Markdown

TLDR

Fixes #30446.

collapseOlderFunctionResponses now sizes older retrieval turns using their retained byte size (after evicted sibling inlineData and nested functionResponse.parts are excluded) instead of calculateHistoryByteSize([turn]), preventing a single older image read_file from exhausting the 64 KB MAX_EXEMPT_RETRIEVAL_HISTORY_BYTES budget and collapsing earlier text reads.

Dive Deeper

  • Root cause: collapseOlderFunctionResponses always evicts binary payloads from older turns (replacing sibling part.inlineData with OMITTED_BINARY_MESSAGE and stripping nested part.functionResponse.parts), even for preserved exempt retrieval turns. However, the budget loop measured each candidate turn with calculateHistoryByteSize([turn]), which counts those evicted binary bytes. One >64 KB screenshot read_file exhausted the entire exempt retrieval budget and caused older text read_file / grep outputs to collapse to 2 KB previews.
  • Fix: Added a private calculateRetainedTurnByteSize(turn) helper in packages/core/src/context/chatCompressionService.ts used only in the exempt-budget loop. It counts OMITTED_BINARY_MESSAGE_BYTES for sibling inlineData parts and omits nested functionResponse.parts, while leaving calculateHistoryByteSize untouched so memory-pressure thresholds continue measuring full binary size.
  • Tests: Added a parameterized regression test in packages/core/src/context/chatCompressionService.test.ts covering both nested (functionResponse.parts[].inlineData) and sibling (part.inlineData) layouts. Both cases fail on main and pass with this fix.

Reviewer Test Plan

npx vitest run packages/core/src/context/chatCompressionService.test.ts packages/core/src/agents/memory-leak-regression.test.ts --coverage.enabled=false
  • packages/core/src/context/chatCompressionService.test.ts: 38/38 passed
  • packages/core/src/agents/memory-leak-regression.test.ts: 18/18 passed
  • prettier --check & eslint --max-warnings 0 on modified files: passed

@bitwizard25
bitwizard25 requested a review from a team as a code owner November 25, 2026 19:50
@gemini-code-assist

Copy link
Copy Markdown
Contributor

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 addresses an issue where large binary payloads in older chat turns were causing the exempt retrieval budget to be exhausted prematurely. By modifying how turn sizes are calculated during the budget check, the system now correctly ignores evicted binary data, ensuring that important text-based history is not unnecessarily collapsed.

Highlights

  • Exempt Retrieval Budget Fix: Updated the exempt retrieval budget calculation to use the retained byte size of turns instead of the full size, preventing large binary payloads from incorrectly exhausting the budget.
  • New Helper Function: Introduced calculateRetainedTurnByteSize to accurately measure turn size by accounting for evicted binary data and excluding nested function response parts.
  • Regression Testing: Added a parameterized test case covering both nested and sibling binary data layouts to ensure older text responses are preserved correctly.
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 the 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 counterproductive. 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.

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. ↩

@github-actions github-actions Bot added the size/m A medium sized PR label Nov 25, 2026
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

📊 PR Size: size/L

  • Lines changed: 256
  • Additions: +255
  • Deletions: -1
  • Files changed: 2

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces a new helper function calculateRetainedTurnByteSize in chatCompressionService.ts to compute the byte size of older chat history turns after binary payloads are evicted, preventing evicted data from incorrectly exhausting the exempt retrieval budget. It also adds corresponding unit tests to verify this behavior for both nested and sibling layouts. A review comment identifies a potential issue where calculateRetainedTurnByteSize ignores nested parts when part.functionResponse.response is undefined but parts are present, which could lead to budget underestimation. A code suggestion is provided to correctly account for these nested parts.

Comment on lines +114 to +141
function calculateRetainedTurnByteSize(turn: Content): number {
let bytes = 0;
if (!turn.parts) {
return bytes;
}
for (const part of turn.parts) {
if (part.inlineData) {
bytes += OMITTED_BINARY_MESSAGE_BYTES;
continue;
}
if (part.text) {
bytes += Buffer.byteLength(part.text, 'utf8');
}
if (part.functionResponse?.response) {
const resp = part.functionResponse.response;
if (typeof resp === 'string') {
bytes += Buffer.byteLength(resp, 'utf8');
} else if (typeof resp === 'object' && resp !== null) {
try {
bytes += Buffer.byteLength(JSON.stringify(resp), 'utf8');
} catch {
// ignore JSON errors
}
}
}
}
return bytes;
}

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.

high

If part.functionResponse.response is undefined but part.functionResponse.parts is defined, collapseOlderFunctionResponses will return the part unmodified (meaning the nested parts are retained). However, calculateRetainedTurnByteSize currently counts 0 bytes for this functionResponse, completely ignoring the retained nested parts. We should update the function to count the nested parts when response is undefined, ensuring consistency with calculateHistoryByteSize and preventing budget underestimation.

function calculateRetainedTurnByteSize(turn: Content): number {
  let bytes = 0;
  if (!turn.parts) {
    return bytes;
  }
  for (const part of turn.parts) {
    if (part.inlineData) {
      bytes += OMITTED_BINARY_MESSAGE_BYTES;
      continue;
    }
    if (part.text) {
      bytes += Buffer.byteLength(part.text, 'utf8');
    }
    if (part.functionResponse) {
      const resp = part.functionResponse.response;
      if (resp !== undefined && resp !== null) {
        if (typeof resp === 'string') {
          bytes += Buffer.byteLength(resp, 'utf8');
        } else if (typeof resp === 'object') {
          try {
            bytes += Buffer.byteLength(JSON.stringify(resp), 'utf8');
          } catch {
            // ignore JSON errors
          }
        }
      } else if (part.functionResponse.parts) {
        for (const nestedPart of part.functionResponse.parts) {
          if (nestedPart && typeof nestedPart === 'object') {
            if (
              'text' in nestedPart &&
              typeof nestedPart.text === 'string' &&
              nestedPart.text
            ) {
              bytes += Buffer.byteLength(nestedPart.text, 'utf8');
            }
            if (nestedPart.inlineData?.data) {
              bytes += Buffer.byteLength(nestedPart.inlineData.data, 'utf8');
            }
          }
        }
      }
    }
  }
  return bytes;
}

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 — updated calculateRetainedTurnByteSize in 8a03170 to count retained nested functionResponse.parts when response is absent, and added a regression test covering that case.

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 — fixed in 8a03170. calculateRetainedTurnByteSize now counts nested functionResponse.parts whenever part.functionResponse.response is absent (matching the early return in collapseOlderFunctionResponses and calculateHistoryByteSize), and I added a regression test covering that case.

@bitwizard25

Copy link
Copy Markdown
Author

/gemini review

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces a more accurate byte size calculation for older chat turns during history compression. Specifically, it adds the calculateRetainedTurnByteSize function to compute the size of a turn after binary payloads (such as sibling inlineData and nested functionResponse parts) are evicted, preventing these evicted payloads from prematurely exhausting the exempt retrieval budget. It also includes comprehensive unit tests to verify this behavior under nested and sibling layouts, as well as when nested parts are retained due to an absent response. I have no additional feedback to provide as the implementation is clean and well-tested.

@chrikrah chrikrah left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@bitwizard25 evicted binaries no longer count, and two of the three new cases fail on base 60f8082. Ready as far as I can test.

non-blocking: a non-exempt part in the same turn still charges in full, so a 70 KB shell output next to a read_file collapses the older 15 KB read. Charging only exempt parts keeps it:

# probe: [read_file 15 KB] [model] [read_file "small" + run_shell_command 70 KB, one turn] [3 recent shell turns]
$ npx vitest run src/context/zzProbeR4.test.ts --coverage.enabled=false   # head 8a03170; values from the assertion message
kb=70 first_intact=false first_len=2139 shell_retained=2139
kb=70 first_intact=true first_len=15600 shell_retained=2139                 # with the diff below
$ npx vitest run src/context/chatCompressionService.test.ts src/agents/memory-leak-regression.test.ts --coverage.enabled=false
Tests  57 passed (57)                    # head, and again with the diff below
Tests  2 failed | 55 passed (57)         # chatCompressionService.ts from 60f8082: nested and sibling cases
$ npx vitest run --coverage.enabled=false        # packages/core, head
Tests  8713 passed | 57 skipped (8770)  # 7 files fail to load: no workspace build, so @google/gemini-cli-core does not resolve
# eslint 9.24.0 --max-warnings 0, prettier --check and tsc --noEmit (packages/core): clean at head
-function calculateRetainedTurnByteSize(turn: Content): number {
+function calculateRetainedTurnByteSize(
+  turn: Content,
+  exemptTools: ReadonlySet<string>,
+): number {
@@
-    if (part.functionResponse) {
+    if (
+      part.functionResponse &&
+      isExemptRetrievalTool(part.functionResponse.name, exemptTools)
+    ) {
@@
-    const turnBytes = calculateRetainedTurnByteSize(turn);
+    const turnBytes = calculateRetainedTurnByteSize(turn, exemptTools);

Cost: non-exempt parts then charge nothing, yet keep a ~2 KB preview, or everything when response is absent. The helper is new and private. Want the probe as a test?

@bitwizard25

Copy link
Copy Markdown
Author

Thanks for the review and approval, @chrikrah! Applied your suggestion in 30a7390 — calculateRetainedTurnByteSize now takes exemptTools and only charges exempt retrieval responses, plus added a regression test for a mixed read_file + large run_shell_command turn.

This branch has not been deployed

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

Labels

size/l A large sized PR size/m A medium sized PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(core): older image read_file exhausts the exempt retrieval budget in collapseOlderFunctionResponses, collapsing older text reads

2 participants