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: Prevent O(n²) memory usage in command output by kov · Pull Request #9693 · anomalyco/opencode

Conversation

@kov

@kov kov commented Jan 20, 2026

Copy link
Copy Markdown

The bash tool and the inline command execution were accumulating command output using output += chunk.toString(), which creates a new string for every chunk and copies all previous content.

For commands producing large output (like meson in weston), this caused catastrophic O(n²) memory usage, as the GC had not time to catch up.

Large output was eventually written to disk and truncated in memory, but that was only done at the end, potentially leading to running out of memory.

Fix by streaming output to disk when it exceeds 50KB threshold:

  • Output < 50KB: stays in memory (no file created)
  • Output ≥ 50KB: streams to file, 50KB sliding window in memory

Also adds line count tracking to match original Truncate.MAX_LINES behavior and proper cleanup on error/abort.

The session/prompt.ts InteractiveCommand uses the same pattern.

What does this PR do?

Avoids a pathological GC case caused by repeated string concatenation that was leading to the OOM killer getting engaged on my 16GB RAM laptop when opencode ran a large meson build with verbose output. I was hitting the issue with the bash tool, but the problem also happens on the interactive command codepath, so changed that as well.

The fix is to not accumulate the whole output as a big string through repeated concatenation with Truncate.output() handling it after the tool has finished, but to do our own handling of truncation. We only accumulate up to 50K in memory (this could be improved to be a sliding window of 50K if we prefer) and when we get anything beyond that stream the output to a file. The final outcome is the same as we had before, but without explosive memory usage.

How did you verify your code works?

I ran the tests, typechecked, and ran a build of opencode that includes the fix. opencode itself tried using the tool and succeeded, was also able to look at the whole file after. I did not observe the explosive memory usage I was seeing before, so I assume that is now fixed.

A good way to test this is to do !find / and click to expand the preview - be careful as that may cause your machine to grind to a halt - you can use something else that causes long output. With this PR applied you should see the same text at the end, but you should not see the memory usage explode.

Sorry, something went wrong.

Uh oh!

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

langyo, LucasArruda, and ragnsan reacted with thumbs up emoji
All reactions
  • 👍 3 reactions
@github-actions github-actions Bot added the needs:issue label Jan 20, 2026
@github-actions

github-actions Bot commented Jan 20, 2026

Copy link
Copy Markdown
Contributor

Thanks for your contribution!

This PR doesn't have a linked issue. All PRs must reference an existing issue.

Please:

  1. Open an issue describing the bug/feature (if one doesn't exist)
  2. Add Fixes #<number> or Closes #<number> to this PR description

See CONTRIBUTING.md for details.

All reactions

Sorry, something went wrong.

Uh oh!

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

@github-actions

github-actions Bot commented Jan 20, 2026

Copy link
Copy Markdown
Contributor

The following comment was made by an LLM, it may be inaccurate:

Based on my search, I found one potentially related PR that addresses similar memory concerns:

Related PR:

  • feat(bash): stream large output to tmpfile with filtering and GC #8953 - feat(bash): stream large output to tmpfile with filtering and GC
    feat(bash): stream large output to tmpfile with filtering and GC #8953

    This PR appears to address the same underlying issue of streaming large bash output to temporary files to prevent memory problems. It may be addressing the same problem space, and this PR (fix: Prevent O(n²) memory usage in command output #9693) could be a refined or follow-up solution to that approach.

The other search results (like #7049 about output pruning) are related to memory management but focus on different aspects.

All reactions

Sorry, something went wrong.

Uh oh!

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

This was referenced Jan 20, 2026
High Memory Usage on macOS 15.7 (Apple M4, 16GB, arm64) #9239
Closed
Memory leak #9385
Closed
why cost so much memory? #9329
Closed
Lots of RAM Usage #9438
Closed
@kov
fix: reduce memory usage in command output (anomalyco#9699)
6c39f13
The bash tool and the inline command execution were accumulating command
output using `output += chunk.toString()`, which creates a new string
for every chunk and copies all previous content.

For commands producing large output (like meson in weston), this caused
catastrophic O(n²) memory usage, as the GC had not time to catch up.

Large output was eventually written to disk and truncated in memory,
but that was only done at the end, potentially leading to running out
of memory.

Fix by streaming output to disk when it exceeds 50KB threshold:
- Output < 50KB: stays in memory (no file created)
- Output ≥ 50KB: streams to file, 50KB sliding window in memory

Also adds line count tracking to match original Truncate.MAX_LINES behavior
and proper cleanup on error/abort.

The session/prompt.ts InteractiveCommand uses the same pattern.
@kov
kov force-pushed the bash-tool-perf branch from 5ee3c25 to 6c39f13 Compare January 20, 2026 21:32
LucasArruda
LucasArruda reviewed Jan 21, 2026
View reviewed changes
Comment thread packages/opencode/src/tool/bash.ts
import { Truncate } from "./truncation"

const MAX_METADATA_LENGTH = 30_000
import { Log } from "../util/log"

@LucasArruda LucasArruda Jan 21, 2026

Copy link
Copy Markdown

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.

keep that at 6 (now 9) just to reduce the diff?

Sorry, something went wrong.

Uh oh!

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

All reactions
@LucasArruda

LucasArruda commented Jan 21, 2026

Copy link
Copy Markdown

Could you review this, please, @rekram1-node ?

I have review it myself and I think the code looks good

All reactions

Sorry, something went wrong.

Uh oh!

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

@cgwalters

cgwalters commented Jan 21, 2026

Copy link
Copy Markdown

Hi @kov ! Yes agree with the LLM, can you look at #8953 ?

All reactions

Sorry, something went wrong.

Uh oh!

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

@kov

kov commented Jan 21, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Author

Hi @cgwalters your change looks even better with the addition of the filter, I like that a lot. I think the only thing that it's missing compared to mine is that I am also fixing the memory usage blowing up on the interactive command side. I'm happy to do whatever here, keep just that side on my patch and merge yours.

You are a lot more knowledgeable than I am, so happy to yield, as long as we get a fix and I don't have to carry a patch to avoid OOM on my system I am happy ;D what's your take @rekram1-node?

All reactions

Sorry, something went wrong.

Uh oh!

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

@rekram1-node

rekram1-node commented Jan 21, 2026

Copy link
Copy Markdown
Member

Does this actually fix the memory issues for you guys? I guess if ur running noisy commands it can be problematic btu most of the memory issues ive seen arent related to bash tool invocations

All reactions

Sorry, something went wrong.

Uh oh!

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

@rekram1-node

rekram1-node commented Jan 21, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Member

Also for truncation it's fine to truncate the metadata stuff but the actual output should keep the same truncation logic as exists rn we shouldnt need to reimplement it right? For the llm at least but lemme read over this more

All reactions

Sorry, something went wrong.

Uh oh!

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

@kov

kov commented Jan 21, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Author

Yes it does. Ask opencode to run find / and watch the process memory usage. I have seen opencode use 70% of my test system's memory (16GB RAM, 24GB swap) while running nothing but a find / through either the bash tool or the interactive command (!find /). With this patch it never goes beyond 3%.

All reactions

Sorry, something went wrong.

Uh oh!

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

@kov

kov commented Jan 21, 2026

Copy link
Copy Markdown
Author

Also for truncation it's fine to truncate the metadata stuff but the actual output should keep the same truncation logic as exists rn we shouldnt need to reimplement it right? For the llm at least but lemme read over this more

The actual output gets saved in full to a file just like it does before the fix. The full path to that file is appended as a hint on the version of the metadata the agent sees, also the same behavior we have before the fix. I have tested it, the agent can see the full output no problem with this fix, it can tell me the first and last lines of the output, for instance. Is that what you mean, or are you talking about something else?

All reactions

Sorry, something went wrong.

Uh oh!

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

@kov

kov commented Jan 21, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Author

Oh... I think what you are asking is if we could just keep using the truncation logic provided by truncation.ts? That I'm afraid is not possible, as Truncate.output() requires that the full output is passed as a string so that it can save it to the file and then truncate the metadata.

For the fix to work we must avoid concatenating the full output to a string one step at a time, which is what causes garbage to accumulate, leading memory usage to explode way beyond what you'd expect from the output of the command itself.

That is the really big problem that gets fixed by streaming to the file when you cross the preview threshold. If we were able to accumulate the bytes without causing the garbage explosion we could keep things as they are and use Truncate.output(). It would still be very inefficient for very large outputs - there is no reason to keep tens or hundreds of MB of output in memory just to save it to a file and truncate later, but it would not cause the pathological case of tens of gigabytes being used, which happens today.

I don't know how that could be done reliably, though.

All reactions

Sorry, something went wrong.

Uh oh!

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

@rekram1-node

rekram1-node commented Jan 21, 2026

Copy link
Copy Markdown
Member

yeah i see whats going on

All reactions

Sorry, something went wrong.

Uh oh!

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

@kov

kov commented Jan 22, 2026

Copy link
Copy Markdown
Author

For completeness' sake and going back to your original message, I guess I should say it does fix this particular case of excessive memory use that was biting me a lot because I am running opencode on codebases whose commands produce lots of output, but I am sure there are other pathological cases like this in other parts of the code that need to be found. I haven't seen one since applying this patch, so for my particular workflow this one seems to be the main offender so far.

All reactions

Sorry, something went wrong.

Uh oh!

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

@github-actions github-actions Bot mentioned this pull request Jan 22, 2026
refactor: extract shared Output utility for command streaming #10076
Closed
@cgwalters

cgwalters commented Jan 22, 2026

Copy link
Copy Markdown

I think the only thing that it's missing compared to mine is that I am also fixing the memory usage blowing up on the interactive command side.

I think then the first fix is to deduplicate the interactive code vs the bash tool:

#10076

All reactions

Sorry, something went wrong.

Uh oh!

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

@rekram1-node

rekram1-node commented Jan 22, 2026

Copy link
Copy Markdown
Member

I talked to Dax he will look at these two prs

All reactions

Sorry, something went wrong.

Uh oh!

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

@kov

kov commented Jan 22, 2026

Copy link
Copy Markdown
Author

@rekram1-node FWIW I am happy to yield to @cgwalters PRs, his idea of adding filters will be helpful to avoid too many | tail and such. And with the refactor he proposed to deduplicate interactive command vs bash everything should be covered. Feel free to close this one and focus on both of his.

All reactions

Sorry, something went wrong.

Uh oh!

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

@cgwalters cgwalters mentioned this pull request Jan 23, 2026
feat(bash): stream large output to tmpfile with filtering and GC #8953
Closed
@cgwalters

cgwalters commented Jan 23, 2026

Copy link
Copy Markdown

I've updated #8953

All reactions

Sorry, something went wrong.

Uh oh!

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

@thdxr
thdxr force-pushed the dev branch from cbab81f to 2d3c7a0 Compare January 30, 2026 04:49
@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 2 times, most recently from f802701 to f1ae801 Compare January 30, 2026 14:36
@thdxr
thdxr force-pushed the dev branch from f1ae801 to 08fa7f7 Compare January 30, 2026 14:37
This was referenced Feb 11, 2026
[BUG/PERF] Severe Memory Leak and Disk Swell leading to System Kernel Panic (macOS) #12687
Closed
fix: resolve memory leaks and zombie processes from missing cleanup handlers #13183
Closed
@github-actions github-actions Bot mentioned this pull request Feb 11, 2026
feat(core): add memory usage (leak) monitoring #13194
Closed
vbuccigrossi pushed a commit to vbuccigrossi/opencode that referenced this pull request Mar 7, 2026
EBrown @claude
feat: port remaining Tier 1+2 upstream fixes and features
63e7373
Tier 1 bug fixes:
- Fix O(n²) bash output concatenation with StreamingOutput class (anomalyco#9693)
- Fix memory leaks in Bus.once, Format, Plugin, ShareNext, Bootstrap (anomalyco#13514)
- Fix FileTime race condition using actual file mtime instead of JS clock
- Free memory on compaction prune: clear output/attachments/metadata (anomalyco#7049)
- Throttle reasoning-delta storage writes to 50ms intervals (anomalyco#11328)
- Handle SIGHUP/SIGTERM to prevent orphaned processes (anomalyco#12718)
- Add process.once("close") handler for bash tool reliability

Tier 2 features:
- Support 1M context window for Anthropic models via beta header (anomalyco#14375)
- Input-only token counting for compaction with limit.input models
- MCP lazy loading: on-demand tool discovery via mcp_search tool (anomalyco#8771)
- MCP servers listed in system prompt when lazy mode enabled
- StreamingOutput: output_filter regex for build diagnostics
- LSP server cleanup callback for temp directory removal
- Extract formatSize utility from uninstall to shared util/format
- GitHub CI: fix Bus subscription leak in session event handler

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions

github-actions Bot commented Mar 25, 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 Mar 25, 2026
This was referenced Nov 8, 2026
fix(ci): resync codegen gate allowlists (#1655) developing-today-forks/opencode#2005
Closed
fix(script): re-sync httpapi-codegen template allowlist entries to the post-#1640 text (#1655) developing-today-forks/opencode#2029
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

1 more reviewer
@LucasArruda LucasArruda LucasArruda left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

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

Assignees

No one assigned

Labels

needs:issue

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.

4 participants

@kov @LucasArruda @cgwalters @rekram1-node
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.