Repository navigation
feat: add tool result truncation to prevent context overflow - #49
Conversation
Tool outputs (readfile, webfetch, fetchdoc) can be arbitrarily large. A single oversized result can consume the entire context window. Add a universal truncation safety net in the agentic loop that caps tool output at MaxResultBytes (default 32KB) before sending it to the LLM. Also fix all pre-existing errcheck lint violations across the codebase (unchecked resp.Body.Close and fmt.Fprintf return values). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThis PR applies two independent improvements: (1) standardizes HTTP response body closing across multiple modules to explicitly suppress close errors via deferred closures, and suppresses unused ChangesCode Quality & Error Handling
Tool Result Truncation
Sequence Diagram(s)sequenceDiagram
participant LLM
participant ToolLoop as RunToolLoop
participant Tool
participant Truncate as truncateResult
LLM->>ToolLoop: sends tool call request
ToolLoop->>Tool: executes tool
Tool-->>ToolLoop: returns Output (potentially large)
ToolLoop->>Truncate: Output, MaxResultBytes
Truncate->>Truncate: check byte length vs limit
alt Output within limit or MaxResultBytes = 0
Truncate-->>ToolLoop: Output (unchanged)
else Output exceeds limit
Truncate->>Truncate: truncate to max bytes (UTF-8 safe)
Truncate->>Truncate: log warning with byte counts
Truncate-->>ToolLoop: Output + "[Truncated…]" suffix
end
ToolLoop->>ToolLoop: create ToolResultContent with truncated Output
ToolLoop->>LLM: returns truncated result
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
- Use strings.ToValidUTF8 to avoid splitting multi-byte characters at the truncation boundary - Add UTF-8 regression test with CJK characters - Fix MaxResultBytes comment: 0 disables truncation, not "uses default" Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/tools/loop.go`:
- Around line 116-125: The truncation notice in truncateResult currently reports
maxBytes instead of the actual retained byte count when ToValidUTF8 can shorten
the slice; update truncateResult to compute actualBytes := len(truncated) after
calling strings.ToValidUTF8 and use actualBytes in the final message (e.g.,
"[Truncated: showing first %d bytes of %d total]") so the notice accurately
reflects bytes retained, and adjust the slog.Warn call if you want to log both
original_bytes and actual_retained_bytes for clarity.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Enterprise
Run ID: 844d6612-7d6b-4573-90d5-d35b91efd026
📒 Files selected for processing (7)
internal/cmd/chat.gointernal/cmd/serve.gointernal/logger/logger.gointernal/openai/openai.gointernal/webfetch/webfetch.gopkg/tools/loop.gopkg/tools/loop_test.go
Use len(truncated) after UTF-8 cleanup instead of maxBytes, so the notice accurately reflects bytes kept when ToValidUTF8 strips trailing partial characters. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Summary
MaxResultBytesfield toLoopConfig(default 32KB) to cap tool output before sending to the LLM[Truncated: showing first N bytes of M total]resp.Body.Closeandfmt.Fprintf)The exec tool already had its own
MaxOutputtruncation, but readfile, webfetch, and fetchdoc had none. This prevents a single large tool result from consuming the entire context window.Test plan
make testpasses — new unit tests fortruncateResultand integration test for large tool outputmake lintpasses — zero issues (down from 8 pre-existing)Closes #46
🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
New Features