GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(grep): stream ripgrep output to prevent memory exhaustion by Hona · Pull Request #5432 · anomalyco/opencode

Conversation

@Hona

@Hona Hona commented Dec 12, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

rg runs on some really common string on some large search space e.g. cd / && rg /
it waits for ALL the results to finish...
It used to load all the results (imagine 1 GB of text) all into memory.
Then string split, (allocating another 1+ GB of memory).
It would also do stat calls for all results
Then finally only fetch the first 100.

Now when you do sinful rg it returns instantly and saves your memory/disk for better things.

Note: There would be a behavior regression here - it used to load all results and when truncating to 100 it is sorted by recently modified
We could do a hybrid approach here - allow streaming in 2000(?) results and return the most recent 100 out of that (killing rg) to limit worst case, but still provide a good experience for small search results.

image

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@Hona
fix(grep): stream ripgrep output to prevent memory exhaustion
52e8688
Copilot AI review requested due to automatic review settings December 12, 2025 09:59
Copilot started reviewing on behalf of Hona December 12, 2025 09:59
View session
Copilot AI reviewed Dec 12, 2025
View reviewed changes

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Pull request overview

This PR improves the memory efficiency of the grep tool by streaming ripgrep output instead of loading all results into memory before processing. Previously, the tool would wait for ripgrep to complete, load all output into memory, split it into lines (creating a second copy), and only then limit to 100 results. The new implementation streams output line-by-line and stops processing once 100 matches are collected, preventing memory exhaustion on large search spaces.

Key changes:

  • Implements streaming processing of ripgrep stdout using ReadableStream API
  • Adds early termination by killing the ripgrep process once MATCH_LIMIT (100) matches are collected
  • Updates exit code handling to account for killed processes and partial results

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread packages/opencode/src/tool/grep.ts
Comment on lines +57 to +80
for (const line of lines) {
if (!line) continue
if (matches.length >= MATCH_LIMIT) {
hitCollectLimit = true
break
}

const [filePath, lineNumStr, ...lineTextParts] = line.split("|")
if (!filePath || !lineNumStr || lineTextParts.length === 0) continue

const lineNum = parseInt(lineNumStr, 10)
const lineText = lineTextParts.join("|")

const file = Bun.file(filePath)
const stats = await file.stat().catch(() => null)
if (!stats) continue

matches.push({
path: filePath,
modTime: stats.mtime.getTime(),
lineNum,
lineText,
})
}

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The streaming implementation processes matches asynchronously with file.stat() calls inside the read loop. If file.stat() is slow, this could cause backpressure issues where the stdout buffer fills up because the reader isn't consuming chunks fast enough. Consider processing file stats after collecting all line data, or implement a queue-based approach to handle I/O more efficiently.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
Comment thread packages/opencode/src/tool/grep.ts Outdated
Comment on lines +124 to +125
const truncated = matches.length > MATCH_LIMIT
const finalMatches = truncated ? matches.slice(0, MATCH_LIMIT) : matches

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The variable truncated is computed based on whether matches.length exceeds MATCH_LIMIT, but since the collection loop stops at MATCH_LIMIT items, matches.length will never actually be greater than MATCH_LIMIT. This means truncated will always be false, making the variable redundant. The truncation logic should rely solely on hitCollectLimit to determine if results were truncated.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
Comment thread packages/opencode/src/tool/grep.ts
reader.releaseLock()
}

const errorOutput = await new Response(proc.stderr).text()

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

When the collection limit is hit and the process is killed, the stderr might not be fully captured yet since proc.stderr is being read after the kill. This could lead to incomplete error messages. Consider reading stderr before killing the process, or at minimum be aware that error output may be incomplete when the limit is hit.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
Comment thread packages/opencode/src/tool/grep.ts Outdated
Comment on lines +85 to +101
if (!hitCollectLimit && buffer) {
const [filePath, lineNumStr, ...lineTextParts] = buffer.split("|")
if (filePath && lineNumStr && lineTextParts.length > 0) {
const lineNum = parseInt(lineNumStr, 10)
const lineText = lineTextParts.join("|")
const file = Bun.file(filePath)
const stats = await file.stat().catch(() => null)
if (stats) {
matches.push({
path: filePath,
modTime: stats.mtime.getTime(),
lineNum,
lineText,
})
}
}
}

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The handling of the last buffered line (lines 85-101) has duplication with the main loop logic (lines 64-79). This duplicated parsing and file stat logic reduces maintainability. Consider extracting the line processing into a separate function to avoid code duplication.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
Comment thread packages/opencode/src/tool/grep.ts Outdated
Comment on lines +70 to +72
const file = Bun.file(filePath)
const stats = await file.stat().catch(() => null)
if (!stats) continue

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Calling file.stat() for every single match result can be a performance bottleneck, especially when processing many results. Each stat call is an I/O operation that waits for file system access. Since ripgrep already provides the file path, consider whether the modification time is truly necessary for sorting, or if there's a way to batch or optimize these stat calls.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
Comment thread packages/opencode/src/tool/grep.ts
const exitCode = await proc.exited

if (exitCode === 1) {
if (exitCode === 1 && matches.length === 0) {

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

When the process is killed due to hitting the collection limit (line 103), the exit code will likely be non-zero (e.g., killed by signal). The error handling on line 118 accounts for this with !hitCollectLimit, but there's a potential edge case: if ripgrep legitimately fails with exit code 1 but we already collected some matches, we'll now return those matches instead of reporting the error. The condition on line 110 should verify that exit code 1 specifically means "no matches found" rather than another error condition.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
@Hona
clean
5a08e68
@Hona
Hona requested a review from Copilot December 12, 2025 10:27
Copilot started reviewing on behalf of Hona December 12, 2025 10:27
View session
Copilot AI reviewed Dec 12, 2025
View reviewed changes

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread packages/opencode/src/tool/grep.ts
Comment on lines +79 to +83
matches.push({
path: filePath,
lineNum: parseInt(lineNumStr, 10),
lineText: lineTextParts.join("|"),
})

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The final buffer processing logic doesn't check if the match count has already reached the MATCH_LIMIT. If exactly MATCH_LIMIT matches were found in the streaming loop, this code could push a 101st match, exceeding the intended limit.

Suggested change
matches.push({
path: filePath,
lineNum: parseInt(lineNumStr, 10),
lineText: lineTextParts.join("|"),
})
if (matches.length < MATCH_LIMIT) {
matches.push({
path: filePath,
lineNum: parseInt(lineNumStr, 10),
lineText: lineTextParts.join("|"),
})
} else {
truncated = true
}

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
Comment thread packages/opencode/src/tool/grep.ts
}

if (exitCode !== 0) {
if (exitCode !== 0 && exitCode !== 1 && !truncated) {

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

When the process is killed due to truncation, the exit code will likely be non-zero (typically 143 for SIGTERM or 137 for SIGKILL). The current condition checks if exitCode is not 0, not 1, and not truncated, but this doesn't account for the case where the process was killed and exits with a signal-related code. This could cause the error handler to throw incorrectly after a successful truncation. Consider checking if the process was killed before evaluating the exit code, or adjust the condition to handle signal-related exit codes.

Suggested change
if (exitCode !== 0 && exitCode !== 1 && !truncated) {
// Allow exit codes 137 (SIGKILL) and 143 (SIGTERM) if process was intentionally killed due to truncation
if (
exitCode !== 0 &&
exitCode !== 1 &&
!(truncated && (exitCode === 137 || exitCode === 143))
) {

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
Comment thread packages/opencode/src/tool/grep.ts
}
}
} finally {
if (truncated) proc.kill()

Copilot AI Dec 12, 2025

Copy link

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

When the process is killed due to truncation, stderr and the exit code are accessed immediately after without waiting for the process to fully terminate. The proc.kill() call is asynchronous, and accessing stderr before the process has fully exited could result in incomplete error output. Consider awaiting proc.exited in the finally block after killing the process to ensure proper cleanup.

Suggested change
if (truncated) proc.kill()
if (truncated) {
proc.kill();
await proc.exited;
}

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Copilot uses AI. Check for mistakes.
@anntnzrb anntnzrb mentioned this pull request Dec 25, 2025
High CPU usage (100%+) during LLM streaming in long sessions due to O(n) text buffer rendering #6172
Closed
shuv1337 added a commit to shuv1337/shuvcode that referenced this pull request Jan 7, 2026
@shuv1337
fix(grep): stream ripgrep output to prevent memory exhaustion
dae59f5
Cherry-pick from upstream PR anomalyco#5432 (anomalyco/opencode).

- Stream ripgrep output line-by-line instead of buffering into memory
- Kill ripgrep early after 100 matches to save resources
- Remove per-file stat() calls for significant performance improvement
- Handle Windows line endings in streaming context

Trade-off: Results no longer sorted by modification time.
shuv1337 added a commit to shuv1337/shuvcode that referenced this pull request Jan 7, 2026
@shuv1337
docs: add PR anomalyco#5432 grep streaming to merged PRs list
227acd0
@greptile-apps greptile-apps Bot mentioned this pull request Jan 7, 2026
Merge shuvcode-dev: upstream v1.1.6 sync, grep streaming, spinner and PWA fixes shuv1337/shuvcode#279
Merged
@shuv1337 shuv1337 mentioned this pull request Jan 7, 2026
fix: restore plugin command execution and sessionOnly guard shuv1337/shuvcode#280
Merged
@github-actions github-actions Bot mentioned this pull request Jan 20, 2026
feat(opencode): switch tool truncation to token-based limits #9648
Closed
@thdxr
thdxr force-pushed the dev branch from cbab81f to 2d3c7a0 Compare January 30, 2026 04:50
@opencode-agent
opencode-agent Bot force-pushed the dev branch from 00637c0 to 71e0ba2 Compare January 30, 2026 14:32
@thdxr
thdxr force-pushed the dev branch 3 times, most recently from f1ae801 to 08fa7f7 Compare January 30, 2026 14:37
@github-actions

github-actions Bot commented Feb 11, 2026

Copy link
Copy Markdown
Contributor

Closing this pull request because it has had no updates for more than 60 days. If you plan to continue working on it, feel free to reopen or open a new PR.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot closed this Feb 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

Copilot code review Copilot
Copilot review effort
Applies to this pull request for everyone.Learn more about Copilot code review.
Copilot left review comments

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@Hona
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.