Skip to content

[BUG] Tree tool crashes the process with "concurrent map read and map write" (unsynchronized gitignoreCache) #712

Closed

Description

@edenreich

Summary

TreeTool crashes the entire infer process with an unrecoverable fatal error: concurrent map read and map write when two or more Tree tool calls execute concurrently within the same process.

The tool's per-directory gitignore cache — gitignoreCache map[string]*ignore.GitIgnore (internal/agent/tools/tree.go:24) — is read and written from getOrLoadDirGitignore with no synchronization. TreeTool is a process-singleton, and a turn's tool calls run concurrently in goroutines, so two Tree executions can read/write that map at the same time. Because this is a Go fatal error (not a panic), it cannot be recovered with recover() and takes the whole agent down.

GrepTool has the identical gitignoreCache field but already guards it with a sync.RWMutex (cacheMutex). TreeTool is the un-mutexed twin — it was simply never given the same protection.

Steps to Reproduce

  1. Run an agent (chat or headless) whose model emits two or more Tree tool calls in a single assistant turn — e.g. a subagent given the task "List the files in the current working directory and report what you find."
  2. The agent executes the batched tool calls concurrently in goroutines, bounded by a semaphore MaxConcurrentTools (default 5) — internal/agent/agent.go (batch spawn ~L815-858, per-tool goroutine ~L990) — all against the one shared *TreeTool returned by registry.GetTool("Tree").
  3. Two Tree executions enter getOrLoadDirGitignore at the same time — one reads gitignoreCache (tree.go:492) while the other writes it (tree.go:500/505). The Go runtime detects the concurrent map access and aborts the process.

Deterministic reproduction under the race detector (illustrative — two concurrent executions on one instance):

tool := NewTreeTool(cfg)
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        _, _ = tool.Execute(ctx, map[string]any{"path": "."})
    }()
}
wg.Wait()
// `go test -race` reports a DATA RACE on gitignoreCache; without -race it can fatal-crash.

Expected Behavior

Concurrent Tree tool calls within a process complete without racing. The gitignore cache is safe for concurrent use — exactly as GrepTool.gitignoreCache already is. No fatal error, no process death.

Actual Behavior

The process dies:

fatal error: concurrent map read and map write

goroutine 846 [running]:
internal/runtime/maps.fatal(...)
  /nix/store/.../src/runtime/panic.go:1181
github.com/inference-gateway/cli/internal/agent/tools.(*TreeTool).getOrLoadDirGitignore(...)
  internal/agent/tools/tree.go:492
github.com/inference-gateway/cli/internal/agent/tools.(*TreeTool).isPathExcludedByGitignore(...)
  internal/agent/tools/tree.go:431
github.com/inference-gateway/cli/internal/agent/tools.(*TreeTool).shouldExclude(...)
github.com/inference-gateway/cli/internal/agent/tools.(*TreeTool).buildTextTree(...)
  internal/agent/tools/tree.go:342
github.com/inference-gateway/cli/internal/agent/tools.(*TreeTool).buildTreeFallback(...)
  internal/agent/tools/tree.go:280
github.com/inference-gateway/cli/internal/agent/tools.(*TreeTool).executeTree(...)
  internal/agent/tools/tree.go:253
github.com/inference-gateway/cli/internal/agent/tools.(*TreeTool).Execute(...)
  internal/agent/tools/tree.go:130
github.com/inference-gateway/cli/internal/services.(*LLMToolService).ExecuteToolDirect(...)
  internal/services/tools.go:158
github.com/inference-gateway/cli/internal/services.(*LLMToolService).ExecuteTool(...)
  internal/services/tools.go:142
github.com/inference-gateway/cli/internal/agent.(*AgentServiceImpl).executeToolInternal.func4()
  internal/agent/agent.go:991
created by github.com/inference-gateway/cli/internal/agent.(*AgentServiceImpl).executeToolInternal
  internal/agent/agent.go:990

Root Cause

internal/agent/tools/tree.go:

  • gitignoreCache map[string]*ignore.GitIgnore (line 24) has no mutex.
  • getOrLoadDirGitignore reads it (line 492) and writes it (lines 500 and 505).
  • TreeTool is a process-singleton: registry.go registers one NewTreeTool(cfg) and GetTool("Tree") returns that same pointer on every call.
  • A turn's tool calls execute concurrently in goroutines, so two Tree runs mutate the map simultaneously.

This is a data race under the Go memory model; concurrent map read+write is specifically detected by the runtime and turned into an unrecoverable fatal error.

Note: this is intra-process, not a parent/subagent memory-sharing bug — subagents are separate OS processes (internal/services/agentrunner/runner.go uses exec.CommandContext), each with its own registry. The race happens inside a single process when it runs multiple Tree calls at once.

Proposed Fix

Mirror the existing, proven pattern in the sibling GrepTool (internal/agent/tools/grep.go:977-1003): add a sync.RWMutex guarding gitignoreCache and use a double-checked read/write lock.

type TreeTool struct {
    // ...
    gitignoreCache map[string]*ignore.GitIgnore
    cacheMutex     sync.RWMutex
    // ...
}

func (t *TreeTool) getOrLoadDirGitignore(dirPath string) *ignore.GitIgnore {
    t.cacheMutex.RLock()
    if cached, exists := t.gitignoreCache[dirPath]; exists {
        t.cacheMutex.RUnlock()
        return cached
    }
    t.cacheMutex.RUnlock()

    t.cacheMutex.Lock()
    defer t.cacheMutex.Unlock()
    if cached, exists := t.gitignoreCache[dirPath]; exists { // re-check after upgrade
        return cached
    }

    gitignorePath := filepath.Join(dirPath, ".gitignore")
    if _, err := os.Stat(gitignorePath); err == nil {
        if gi, err := ignore.CompileIgnoreFile(gitignorePath); err == nil {
            t.gitignoreCache[dirPath] = gi
            return gi
        }
    }
    t.gitignoreCache[dirPath] = nil
    return nil
}

t.gitignore needs no lock — it is written only in loadGitignore, called once from the constructor, and read-only thereafter.

Add a -race regression test mirroring TestRegistry_ConcurrentMCPToolAccess (added in #709) that runs concurrent Tree executions and passes under go test -race ./internal/agent/tools/.

Related

A second, lower-severity unsynchronized race exists in GetLatestScreenshotTool (internal/agent/tools/get_latest_screenshot.go): lastCallTime time.Time is read and written in Execute without a lock. Same class of bug (shared singleton + concurrent tool goroutines). A time.Time race won't fatal-crash the way a map does, but it is still a data race under -race and is worth fixing in the same change (guard it with a small sync.Mutex).

Environment

Activity

  1. added
    bug
    on Jul 1, 2026
  2. added theissue type on Jul 1, 2026
  3. moved this to Todo in 2026on Jul 1, 2026
  4. inference-gateway-releaser commented on Jul 2, 2026

    @inference-gateway-releaser
    Contributor

    🎉 This issue has been resolved in version 0.127.0 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

  5. moved this from Todo to Done in 2026on Jul 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugreleased

    Type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions