Skip to content

feat: parallel tool execution and AfterToolCall hook - #50

Merged
pavelanni merged 4 commits into
mainfrom
feature/parallel-tool-execution
May 4, 2026
Merged

pavelanni merged 4 commits into
mainfrom
feature/parallel-tool-execution

Conversation

@pavelanni

@pavelanni pavelanni commented May 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Replace sequential tool execution with errgroup so independent tool calls run concurrently
  • Results are written to a pre-allocated slice indexed by position for deterministic ordering
  • Extend Hook interface with AfterToolCall for post-execution logging and audit
  • Wire Hook from LoopConfig instead of hardcoded nil
  • Promote golang.org/x/sync from indirect to direct dependency

Design

See docs/superpowers/specs/2026-05-04-parallel-tool-execution-design.md for the full spec.

Test plan

  • make test passes
  • make lint passes (0 issues)
  • TestRunToolLoopParallelExecution — 3 tools with 100ms delay each finish in <200ms (proves parallelism)
  • TestAfterToolCallHook — verifies hook receives correct tool name, args, and result
  • TestBeforeToolCallHookDenial — verifies denied tools don't trigger AfterToolCall
  • All existing loop tests pass unchanged

Closes #45

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features
    • Tools now execute in parallel, improving response times when multiple tools are called simultaneously.
    • Added lifecycle hooks to intercept tool execution before and after completion.

pavelanni added 2 commits May 4, 2026 18:12
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]>
@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 25 minutes and 48 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: d7e5529c-893a-47ce-be1a-58ce64215d77

📥 Commits

Reviewing files that changed from the base of the PR and between 59966de and 4d9f3b8.

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

Walkthrough

This PR implements parallel tool execution in the agentic loop by replacing sequential tool invocation with errgroup-based concurrent execution, adding an AfterToolCall hook method for post-execution interception, and introducing comprehensive tests to validate parallel behavior and hook integration.

Changes

Parallel Tool Execution with Hook Integration

Layer / File(s) Summary
Design Specification
docs/superpowers/specs/2026-05-04-parallel-tool-execution-design.md
Design document specifies transition from sequential RunToolLoop to errgroup.Group-based parallel execution, pre-allocated indexed results slice for deterministic ordering, and addition of AfterToolCall hook method to the Hook interface.
Dependency Management
go.mod
golang.org/x/sync v0.19.0 promoted from indirect to direct dependency to support errgroup usage.
Hook Interface Extension
pkg/tools/hooks.go
Hook interface extended with AfterToolCall(ctx context.Context, name string, args map[string]any, result \\*ToolResult) method; concurrent-use documentation added.
Configuration Wiring
pkg/tools/loop.go
LoopConfig adds optional Hook field for tool-call interception; executeTool now passes hook instance instead of nil.
Core Parallel Execution
pkg/tools/loop.go
RunToolLoop replaces sequential tool-call iteration with errgroup.WithContext, preallocates results slice, runs executeTool per tool in goroutines, invokes hook.AfterToolCall after each tool completion, and captures results by index.
Tests and Validation
pkg/tools/loop_test.go
Added slowMockTool for timing-based tests, mockHook for hook recording with mutex protection, TestRunToolLoopParallelExecution validating concurrent execution timing, TestAfterToolCallHook verifying hook callback correctness, and TestBeforeToolCallHookDenial ensuring denial prevents execution and hook invocation.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive The PR implements most requirements from #45: parallel execution via errgroup, AfterToolCall hook addition, and Hook wiring. However, per-tool ExecutionMode is not implemented. Verify whether per-tool ExecutionMode (parallel vs sequential override) is deferred to a future PR, or confirm it was intentionally omitted from this PR's scope.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the two main changes: parallel tool execution and the new AfterToolCall hook addition.
Out of Scope Changes check ✅ Passed All changes align with #45 requirements: design spec, parallel execution, AfterToolCall hook, Hook wiring, and x/sync dependency promotion. No extraneous changes detected.

✏️ 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/parallel-tool-execution

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.

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

🧹 Nitpick comments (2)
pkg/tools/loop.go (1)

70-85: ⚡ Quick win

Honor context cancellation after g.Wait().

The errgroup goroutines always return nil, so g.Wait() only returns an error if gctx was cancelled by a goroutine returning one — which never happens here. That means an externally cancelled ctx is silently swallowed: the loop appends partial/erroring tool results and proceeds to another provider.CompleteWithTools(ctx, …) call that will fail anyway. Short-circuit on ctx.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 value

Document mutation semantics of *ToolResult in AfterToolCall.

The hook receives the same *ToolResult that RunToolLoop then feeds into truncateResult and the assistant message, so any mutation of result.Output/result.Error is 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

📥 Commits

Reviewing files that changed from the base of the PR and between fdd4ab4 and 59966de.

📒 Files selected for processing (5)
  • docs/superpowers/specs/2026-05-04-parallel-tool-execution-design.md
  • go.mod
  • pkg/tools/hooks.go
  • pkg/tools/loop.go
  • pkg/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]>
@pavelanni
pavelanni merged commit 9d5794a into main May 4, 2026
2 checks passed
@pavelanni
pavelanni deleted the feature/parallel-tool-execution branch May 4, 2026 23:53
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: parallel tool execution in agentic loop

1 participant