Skip to content

feat: add tool result truncation to prevent context overflow - #49

Merged
pavelanni merged 3 commits into
mainfrom
feature/tool-result-truncation
May 4, 2026
Merged

pavelanni merged 3 commits into
mainfrom
feature/tool-result-truncation

Conversation

@pavelanni

@pavelanni pavelanni commented May 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add MaxResultBytes field to LoopConfig (default 32KB) to cap tool output before sending to the LLM
  • Universal safety net applied after any tool returns, in the agentic loop
  • Truncated output includes notice: [Truncated: showing first N bytes of M total]
  • Fix all pre-existing errcheck lint violations (unchecked resp.Body.Close and fmt.Fprintf)

The exec tool already had its own MaxOutput truncation, but readfile, webfetch, and fetchdoc had none. This prevents a single large tool result from consuming the entire context window.

Test plan

  • make test passes — new unit tests for truncateResult and integration test for large tool output
  • make lint passes — zero issues (down from 8 pre-existing)

Closes #46

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved resource cleanup and error handling across HTTP response operations to prevent potential issues with connection management.
  • New Features

    • Tool outputs are now automatically truncated to prevent unbounded responses, with a 32KB default limit that can be configured.

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]>
@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@pavelanni has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 51 minutes and 33 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: fefe9367-ad5b-4560-a82a-1b253ffa5fe9

📥 Commits

Reviewing files that changed from the base of the PR and between 70dc6c9 and ec72691.

📒 Files selected for processing (1)
  • pkg/tools/loop.go
📝 Walkthrough

Walkthrough

This 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 fmt.Fprintf return values; (2) adds configurable truncation of large tool outputs (default 32KB) before returning results to the LLM, with UTF-8-safe truncation and warning logs.

Changes

Code Quality & Error Handling

Layer / File(s) Summary
Response Body Closing Refactor
internal/cmd/serve.go
fetchDocument now defers response body close via a nil-safe closure placed after the successful HTTP request, preventing nil dereference on request failure.
Response Error Suppression
internal/cmd/chat.go, internal/openai/openai.go, internal/webfetch/webfetch.go
Response bodies in fetchAgentCard, Complete, CompleteWithTools, and Execute now use defer func() { _ = resp.Body.Close() }() to explicitly ignore close errors instead of direct defer resp.Body.Close().
Return Value Suppression
internal/cmd/chat.go, internal/logger/logger.go
fmt.Fprintf and fmt.Fprintln calls assign return values to _, _ to suppress unused variable linting errors without changing logged output or control flow.

Tool Result Truncation

Layer / File(s) Summary
Configuration
pkg/tools/loop.go
LoopConfig gains MaxResultBytes field (default 32KB); defaultMaxResultBytes constant and DefaultLoopConfig() updated. Setting MaxResultBytes to 0 disables truncation.
Core Implementation
pkg/tools/loop.go
New truncateResult(s string, maxBytes int) helper truncates output by byte count, respects UTF-8 boundaries, logs warnings with original/max counts, and appends a truncation notice. RunToolLoop applies truncation to each tool result's Output before returning to the LLM.
Tests
pkg/tools/loop_test.go
TestRunToolLoopTruncatesLargeOutput verifies truncation occurs and final output is correct; TestTruncateResult covers no truncation below limit, truncation with notice, 0 limit behavior, and UTF-8 safety (no split runes or invalid characters).

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add tool result truncation to prevent context overflow' clearly and concisely summarizes the main change: adding tool result truncation to prevent context overflow.
Linked Issues check ✅ Passed The PR implements all primary coding objectives from issue #46: adds MaxResultBytes config to LoopConfig with 32KB default, implements truncation in the tool loop, appends truncation notice, and ensures UTF-8 safety.
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objectives: tool result truncation, lint fixes for errcheck violations, and supporting test coverage directly address issue #46 requirements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/tool-result-truncation

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

- 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]>
@pavelanni
pavelanni marked this pull request as ready for review May 4, 2026 21:10
@pavelanni

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 4, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between af2db00 and 70dc6c9.

📒 Files selected for processing (7)
  • internal/cmd/chat.go
  • internal/cmd/serve.go
  • internal/logger/logger.go
  • internal/openai/openai.go
  • internal/webfetch/webfetch.go
  • pkg/tools/loop.go
  • pkg/tools/loop_test.go

Comment thread pkg/tools/loop.go Resolved
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]>
@pavelanni
pavelanni merged commit fdd4ab4 into main May 4, 2026
2 checks passed
@pavelanni
pavelanni deleted the feature/tool-result-truncation branch May 4, 2026 22:05
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.

feat: tool result truncation to prevent context overflow

1 participant