Skip to content

fix(tool): cap code_search matched-line size and total output bytes - #1832

Open
AaronPasi wants to merge 3 commits into
alibaba:mainfrom
AaronPasi:fix/code-search-byte-cap
Open

AaronPasi wants to merge 3 commits into
alibaba:mainfrom
AaronPasi:fix/code-search-byte-cap

Conversation

@AaronPasi

Copy link
Copy Markdown

Description

code_search caps matches at 100 (gitGrepMaxCount) but not result size. In repos with committed minified bundles (single lines up to ~2.1M chars observed), one tool result reached 3–8 MB; the next LLM request exceeds the model's context limit and compression cannot digest the giant lines, so the review item fails (Context compression exceeded threshold). See #1827.

This PR adds:

  • per-line truncation at gitGrepMaxLineBytes (2 KB, backed off to a valid UTF-8 boundary, with a [line truncated, N more bytes omitted] marker)
  • a gitGrepMaxOutputBytes (256 KB) total output cap as defense in depth

Normal source lines are far below both caps, so behavior is unchanged for minified-free repos.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)

How Has This Been Tested?

  • Full suite via go test ./... — all packages pass (run with -vet=off locally due to an environment-specific vet false positive; upstream CI vet is unaffected). gofmt -l clean on both files.
  • Manual testing: A/B on an internal ~12 GB monorepo with committed web build output — before: 1/6 files reviewed (5 failed with context compression exceeded), 1 finding; after: 6/6 files reviewed, 11 findings. On a minified-free repo the change never triggers (byte-identical output).

Checklist

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have signed the CLA (will sign via the CLA bot)
  • I did not use AI/LLM to create this PR, or I disclosed the tool/model below and reviewed its output; I did not attribute commits to AI and will answer maintainer questions and review comments myself without AI/LLM.

AI disclosure: developed with AI assistance (GLM-5.3 via ZCode agent); the author reviewed the output and ran the tests/measurements above.

Related Issues

Fixes #1827

Add truncation for matched lines to limit output size and ensure valid UTF-8.
Add tests for Git grep functionality, including handling of long lines and truncation.
@github-actions

github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 1 issue(s) in this PR.

  • ✅ Successfully posted inline: 1 comment(s)

Comment on lines +278 to +281
cut := s[:gitGrepMaxLineBytes]
for len(cut) > 0 && !utf8.ValidString(cut) {
cut = cut[:len(cut)-1]
}

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.

bug · high
Bug: utf8.ValidString(cut) validates the entire substring, not just the bytes near the cut boundary. If the original line contains any invalid UTF-8 byte before position gitGrepMaxLineBytes (e.g., binary data in a minified/bundled file), this loop will keep shrinking cut one byte at a time until it's empty, discarding all matched content.

Instead, only check whether the cut falls in the middle of a multi-byte sequence at the boundary. utf8.DecodeLastRuneInString returns RuneError with size 0 when the trailing bytes are an incomplete sequence, which is exactly the condition you want to back off from:

Suggestion:

Suggested change
cut := s[:gitGrepMaxLineBytes]
for len(cut) > 0 && !utf8.ValidString(cut) {
cut = cut[:len(cut)-1]
}
cut := s[:gitGrepMaxLineBytes]
for len(cut) > 0 {
if r, size := utf8.DecodeLastRuneInString(cut); r != utf8.RuneError || size != 0 {
break
}
cut = cut[:len(cut)-1]
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hola este es un problema de Windows de arranque con Linux lanch

@CLAassistant

CLAassistant commented Oct 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ lizhengfeng101
❌ AaronPasi
You have signed the CLA already but the status is still pending? Let us recheck it.

@abhisheksharma2411 abhisheksharma2411 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.

Heads up that #1833 is fixing #1827 in the same file, within a day of this one. Flagging it so a maintainer does not review both cold.

I put the comparison on #1833 rather than repeating it here. The short version: this one is the more complete fix, because the total output cap is what actually bounds the result. #1833 caps each line at 4096 runes but has no aggregate limit, and with gitGrepMaxCount = 100 the worst case stays around 400 KB to 1.6 MB depending on encoding — still in the range that provoked the context failure. A per-line limit times a match count is not a ceiling; your 256 KB cap is.

One thing from #1833 worth stealing if this is the one that lands: it reports how many lines were truncated in aggregate ("N match line(s) exceeded..."), where this PR marks each line individually. Both are useful, and the aggregate note is the one a person reading a long result actually notices.

I have not reviewed the implementation itself in detail yet — this is about the overlap. Happy to go through the code properly if it is going to be the branch that proceeds.

Claude assisted with this review.

@Locoabordo

Copy link
Copy Markdown

@lizhengfeng101

Copy link
Copy Markdown
Contributor

Thanks @AaronPasi for working on this and sharing the real-repository measurements.

For #1827, my preferred direction is to continue with this PR's byte-based limits: 2 KiB of match content per line and 256 KiB for the complete rendered result. This gives a predictable size bound regardless of UTF-8 character width. #1833 now also includes an aggregate limit; the useful pieces to incorporate here are its pre-write budget checks and aggregate-output tests, rather than its rune-based budget. We should converge on one implementation instead of merging both overlapping fixes.

Please address these items before we consider this ready:

  1. Fix test compilation. At the current head (14006cc3), make test PACKAGES=./internal/tool fails with code_search_test.go:877: undefined: utf8. The test file needs its own unicode/utf8 import.
  2. Make the total limit apply to the complete result. The current check only examines the existing buffer before writing an entire file's matches, so the next block can exceed the budget. Check the prospective size before each write, including file headers, match lines, separators, notes, and warnings; reserve room for the truncation notice. The final returned string should stay within the byte budget, including when the last file crosses the limit.
  3. Avoid over-truncating non-UTF-8 input. Repeatedly validating the entire prefix can discard all otherwise useful ASCII content after an earlier invalid byte. Handle a split character at the cut boundary without deleting everything after an unrelated invalid byte; if invalid bytes are normalized, account for that separately.
  4. Add regression coverage and pass repository checks. Cover aggregate output, long paths/the final file crossing the budget, notices included in the budget, and invalid bytes followed by valid text. Assert the final byte length, not just the presence of a marker. The existing CJK fixture also fails make english-check; use an escaped fixture or the documented line-scoped exemption. Please run make check and make test, and report any remaining failures.

Please also complete the pending CLA step.

Let's keep this fix focused: streaming git grep to reduce pre-render memory usage and returning snippets around the actual match can be follow-ups, not prerequisites here. Once the items above are addressed, we can reassess this PR for merge.

AI disclosure: analysis and drafting assisted by OpenAI Codex; automated review performed with OpenCodeReview.

@NanaseInori NanaseInori 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.

Reviewed both changed files, #1827, the competing #1833 implementation, and the maintainer's current requested changes. The byte-based approach addresses the reported unbounded-line problem, but the following defects remain at head 14006cc.

[P1] Import unicode/utf8 in the test file. TestTruncateMatchLine calls utf8.ValidString, but code_search_test.go's import block has no unicode/utf8 import. The production file's import does not put that package name in scope in the test file. This is a test-package compilation blocker, consistent with the maintainer's reported undefined: utf8 failure.

[P2] Enforce the complete-result byte budget before each write. The current check runs only before an entire file block, then appends the header and every match unchecked. A last block can cross the limit without another iteration to detect it. I reproduced this using real git grep output from a temporary Linux repository and the pinned successful-workspace parsing/rendering algorithm:

41 files, 100 matches; 40 paths are 3,272 bytes long
Each matched line is exactly 2,048 bytes (no individual-line truncation)
Last file has 60 matches
Returned result: 336,979 bytes
Configured limit: 262,144 bytes
Excess: 74,835 bytes
Total-output truncation notice: absent

Check prospective sizes of headers, lines, separators and diagnostics, reserving space for a truncation notice. Add a regression for the final file crossing the budget and assert the final returned length, not only marker presence.

[P2] Keep useful text after an unrelated invalid byte. The whole-prefix ValidString loop also reproduces the existing over-truncation concern: OK + 0xff + NEEDLE + 3000 ASCII x bytes retains only OK before the omission marker, dropping all valid text after the invalid byte even though the boundary is much later. Fix boundary handling independently of any intentional invalid-byte normalization. The earlier bot's proposed DecodeLastRuneInString size==0 condition is not a correct substitute for detecting incomplete nonempty input; do not apply that suggestion unchanged.

The independent execution above was an isolated parser/render/helper harness, not OCR's complete repository suite. The missing import was confirmed by source inspection; I did not claim to rerun the maintainer's make command. #1833 is an alternative implementation; this earlier PR does not need to wait for it. Streaming subprocess output and match-centered snippets can remain follow-ups, as the maintainer requested.

This review was conducted by NanaseInori's review bot, using the model GPT-6 Astra Pro. If you need a human review, please manually @NanaseInori.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

code_search: 100-match cap is count-only — minified single-line files produce multi-MB tool results that exceed the context limit

6 participants