Skip to content

perf(core): linearize array reconstruction in truncateHistoryToBudget - #29517

Open
Kaushik2210 wants to merge 1 commit into
google-gemini:mainfrom
Kaushik2210:perf/linearize-history-truncation
Open

Kaushik2210 wants to merge 1 commit into
google-gemini:mainfrom
Kaushik2210:perf/linearize-history-truncation

Conversation

@Kaushik2210

Copy link
Copy Markdown

Summary

truncateHistoryToBudget() in packages/core/src/context/chatCompressionService.ts visits messages and their parts newest-to-oldest (to prioritize recent tool responses against the truncation budget), then restores chronological order by calling unshift() for every processed part and every reconstructed message.

Repeated front-insertion into a JS array is O(n) per call, so for H messages with P_i parts each, this costs O(H^2 + sum(P_i^2)) instead of O(H + sum(P_i)). This helper runs on the whole curated history before compression splits it, so the overhead applies even to messages that get summarized away afterward.

Fix

Append with push() instead of unshift(), and reverse each parts array once and the overall history array once at the end. The backwards traversal itself — and every budget/truncation decision, which only depends on processing order, not on how the result array is built — is unchanged.

Exported truncateHistoryToBudget for direct unit testing, following this file's existing pattern of exporting internal helpers for tests (findCompressSplitPoint, collapseOlderFunctionResponses).

Test plan

  • Added a regression test asserting message order and multi-part ordering within a message are preserved when no truncation occurs, isolating the array-reconstruction change from budget-truncation logic (which the existing tests in the same describe block already cover).
  • npm test -w @google/gemini-cli-core -- src/context/chatCompressionService.test.ts — 37/37 pass, including the existing truncation-ordering tests (should truncate older function responses when budget is exceeded, etc.) unchanged.
  • npx eslint on both touched files and npx tsc --noEmit on packages/core: clean.
  • This is a behavior-preserving refactor (push+reverse produces the same array as unshift, by construction), so there's no old-vs-new output difference to demonstrate — the added test locks in correctness rather than catching a regression.

Fixes #29511

truncateHistoryToBudget() in chatCompressionService.ts visits messages
and their parts newest-to-oldest to prioritize recent tool responses,
then restores chronological order via unshift() for every processed
part and every reconstructed message. Repeated front-insertion is
O(n) per call, so for H messages with P_i parts each this costs
O(H^2 + sum(P_i^2)) instead of O(H + sum(P_i)).

Append with push() instead and reverse each parts array and the
overall history once at the end. The backwards traversal (and all
budget/truncation decisions, which are unaffected by how the result
array is built) is unchanged.

Exported truncateHistoryToBudget for direct testing, matching the
existing pattern for this file's other internal helpers
(findCompressSplitPoint, collapseOlderFunctionResponses), and added a
regression test asserting message and multi-part ordering is
preserved when no truncation occurs.

Fixes google-gemini#29511
@Kaushik2210
Kaushik2210 requested a review from a team as a code owner September 26, 2026 15:24
@github-actions github-actions Bot added the size/s A small PR label Sep 26, 2026
@github-actions

Copy link
Copy Markdown

📊 PR Size: size/S

  • Lines changed: 41
  • Additions: +35
  • Deletions: -6
  • Files changed: 2

@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 improves the performance of the chat history truncation logic by switching from an O(n^2) array reconstruction approach to an O(n) approach. By appending elements and reversing the final arrays, the service avoids the overhead of repeated front-insertions, ensuring more efficient processing of chat history while maintaining identical output behavior.

Highlights

  • Performance Optimization: Optimized the truncateHistoryToBudget function by replacing repeated unshift() operations with push() and a final reverse(), reducing complexity from O(H^2 + sum(P_i^2)) to O(H + sum(P_i)).
  • API Exposure: Exported truncateHistoryToBudget to enable direct unit testing.
  • Regression Testing: Added a new test case to ensure message and multi-part ordering is preserved during history reconstruction.
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. ↩

@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 optimizes the truncateHistoryToBudget function in chatCompressionService.ts by replacing inefficient unshift operations with push followed by a single reverse() call, improving performance during array reconstruction. It also exports truncateHistoryToBudget and adds a unit test in chatCompressionService.test.ts to ensure that message and multi-part ordering are correctly preserved. There are no review comments, and I have no additional feedback to provide.

@gemini-cli gemini-cli Bot added the area/agent Issues related to Core Agent, Tools, Memory, Sub-Agents, Hooks, Agent Quality label Sep 26, 2026
@gemini-cli

gemini-cli Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Hi there! Thank you for your interest in contributing to Gemini CLI.

To ensure we maintain high code quality and focus on our prioritized roadmap, we only guarantee review and consideration of pull requests for issues that are explicitly labeled as 'help wanted'.

This PR will be closed in 7 days if it remains without that designation. We encourage you to find and contribute to existing 'help wanted' issues in our backlog! Thank you for your understanding.

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

area/agent Issues related to Core Agent, Tools, Memory, Sub-Agents, Hooks, Agent Quality size/s A small PR status/pr-nudge-sent

Projects

None yet

Development

Successfully merging this pull request may close these issues.

linearize-chat-compression-history-reconstruction

1 participant