Repository navigation
feat: parallel tool execution and AfterToolCall hook - #50
Conversation
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Replace sequential tool execution with errgroup so independent tool calls run concurrently. This reduces latency when the LLM requests multiple I/O-bound tools (webfetch, fetchdoc, readfile) in one batch. Also extend the Hook interface with AfterToolCall for post-execution logging, audit, and result observation. Wire Hook from LoopConfig instead of the hardcoded nil. 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 (2)
📝 WalkthroughWalkthroughThis PR implements parallel tool execution in the agentic loop by replacing sequential tool invocation with ChangesParallel Tool Execution with Hook Integration
Sequence DiagramsequenceDiagram
participant Runner as RunToolLoop
participant Hook as Hook Interface
participant Group as errgroup.Group
participant Executor as executeTool
participant Tool as Tool
Runner->>Hook: BeforeToolCall (sequential validation)
Hook-->>Runner: allow / deny
alt Tool Allowed
Runner->>Group: Create group with context
Group->>Group: For each allowed tool: spawn goroutine
par Parallel Execution
Executor->>Tool: Execute (goroutine 1)
Tool-->>Executor: ToolResult
Executor->>Hook: AfterToolCall (name, args, result)
and
Executor->>Tool: Execute (goroutine 2)
Tool-->>Executor: ToolResult
Executor->>Hook: AfterToolCall (name, args, result)
and
Executor->>Tool: Execute (goroutine 3)
Tool-->>Executor: ToolResult
Executor->>Hook: AfterToolCall (name, args, result)
end
Group->>Group: Wait for all goroutines
Runner->>Runner: Aggregate results (original order)
Runner-->>Runner: Return combined response
else Tool Denied
Hook-->>Runner: Denial reason
Runner-->>Runner: Return denial message
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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 |
- Document Hook thread-safety requirement for concurrent use - Add comment explaining why g.Wait() error is discarded - Verify result correctness in parallel test using AfterToolCall hook Slice data race concern (finding #1) is a false positive: writing to distinct indices of a pre-allocated slice is safe in Go, and g.Wait() provides the happens-before guarantee. 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.
🧹 Nitpick comments (2)
pkg/tools/loop.go (1)
70-85: ⚡ Quick winHonor context cancellation after
g.Wait().The errgroup goroutines always
return nil, sog.Wait()only returns an error ifgctxwas cancelled by a goroutine returning one — which never happens here. That means an externally cancelledctxis silently swallowed: the loop appends partial/erroring tool results and proceeds to anotherprovider.CompleteWithTools(ctx, …)call that will fail anyway. Short-circuit onctx.Err()to surface cancellation cleanly and avoid the extra LLM round-trip.♻️ Suggested change
// Tool errors are captured in ToolResult.Error, not returned from goroutines. _ = g.Wait() + if err := ctx.Err(); err != nil { + return "", fmt.Errorf("tool loop cancelled: %w", err) + }🤖 Prompt for 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. In `@pkg/tools/loop.go` around lines 70 - 85, The errgroup goroutines always return nil so g.Wait() never propagates external cancellation; after g.Wait() check ctx.Err() (or gctx.Err()) and short-circuit by returning the cancellation error to the caller instead of continuing to call provider.CompleteWithTools; update the code around the errgroup created with errgroup.WithContext(ctx) (symbols: g, gctx, g.Wait) where resp.ToolCalls are processed with executeTool and results are populated into results (llm.ToolResultContent) to detect context cancellation and stop further work when ctx.Err() != nil.pkg/tools/hooks.go (1)
11-12: 💤 Low valueDocument mutation semantics of
*ToolResultinAfterToolCall.The hook receives the same
*ToolResultthatRunToolLoopthen feeds intotruncateResultand the assistant message, so any mutation ofresult.Output/result.Erroris observable to the LLM. Either declare the value read-only or explicitly allow transformation; without a contract, implementations and the loop can drift. Given parallel invocation, also note that mutating shared state across hook calls requires the implementation's own synchronization.📝 Suggested doc
// Hook allows external systems to intercept tool calls. // Implementations must be safe for concurrent use — with parallel // tool execution, both methods may be called from multiple goroutines. type Hook interface { BeforeToolCall(ctx context.Context, name string, args map[string]any) (allow bool, reason string) + // AfterToolCall is invoked once per executed tool. The result pointer + // is the same value the loop will forward to the LLM; implementations + // may inspect it but must not mutate it concurrently or in ways the + // caller does not expect. AfterToolCall(ctx context.Context, name string, args map[string]any, result *ToolResult) }🤖 Prompt for 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. In `@pkg/tools/hooks.go` around lines 11 - 12, Document the mutation semantics of the AfterToolCall hook: explicitly state whether implementations may mutate the passed *ToolResult (including result.Output and result.Error) or must treat it as read-only; if mutation is allowed, require that callers rely on those changes (e.g., RunToolLoop and truncateResult will observe mutations) and mandate that hook implementations perform their own synchronization when invoked in parallel; if mutation is disallowed, require hook implementations to operate on a copy and assert immutability for the original ToolResult. Reference AfterToolCall, RunToolLoop, truncateResult, and ToolResult in the comment so implementers know the contract and concurrency obligations.
🤖 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.
Nitpick comments:
In `@pkg/tools/hooks.go`:
- Around line 11-12: Document the mutation semantics of the AfterToolCall hook:
explicitly state whether implementations may mutate the passed *ToolResult
(including result.Output and result.Error) or must treat it as read-only; if
mutation is allowed, require that callers rely on those changes (e.g.,
RunToolLoop and truncateResult will observe mutations) and mandate that hook
implementations perform their own synchronization when invoked in parallel; if
mutation is disallowed, require hook implementations to operate on a copy and
assert immutability for the original ToolResult. Reference AfterToolCall,
RunToolLoop, truncateResult, and ToolResult in the comment so implementers know
the contract and concurrency obligations.
In `@pkg/tools/loop.go`:
- Around line 70-85: The errgroup goroutines always return nil so g.Wait() never
propagates external cancellation; after g.Wait() check ctx.Err() (or gctx.Err())
and short-circuit by returning the cancellation error to the caller instead of
continuing to call provider.CompleteWithTools; update the code around the
errgroup created with errgroup.WithContext(ctx) (symbols: g, gctx, g.Wait) where
resp.ToolCalls are processed with executeTool and results are populated into
results (llm.ToolResultContent) to detect context cancellation and stop further
work when ctx.Err() != nil.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Enterprise
Run ID: f603d286-8ad2-4142-9fac-9ea2b4cfa2f6
📒 Files selected for processing (5)
docs/superpowers/specs/2026-05-04-parallel-tool-execution-design.mdgo.modpkg/tools/hooks.gopkg/tools/loop.gopkg/tools/loop_test.go
- Document AfterToolCall as read-only (must not mutate ToolResult) - Short-circuit on context cancellation after g.Wait() instead of continuing into the next LLM call Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Summary
errgroupso independent tool calls run concurrentlyHookinterface withAfterToolCallfor post-execution logging and auditHookfromLoopConfiginstead of hardcodednilgolang.org/x/syncfrom indirect to direct dependencyDesign
See
docs/superpowers/specs/2026-05-04-parallel-tool-execution-design.mdfor the full spec.Test plan
make testpassesmake lintpasses (0 issues)TestRunToolLoopParallelExecution— 3 tools with 100ms delay each finish in <200ms (proves parallelism)TestAfterToolCallHook— verifies hook receives correct tool name, args, and resultTestBeforeToolCallHookDenial— verifies denied tools don't trigger AfterToolCallCloses #45
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes