proc: a PATH folder that doesn't answer is left out of every look (ifccod7391564 on X)

Started with `open -a`, magpie ran but took over 60s to write
"started", while the same binary run from a shell started in 1s. The
reporter's trace: startUp → agent.RenameLegacy → onMachine →
vscodePortableData → binAt("code-insiders"). Without Insiders,
exec.LookPath walks all of PATH, and a folder on a mount that no longer
answers holds open()/stat() until it does, before applog.Start.

The block isn't binAt's alone: startUp builds every agent through
local() in RenameLegacy and again in moveEfforts (Cursor's and
Antigravity's), each asking for its command through binAt/proc, all
walking the same PATH, and lookStamp stats every PATH folder first. So
the bound is where all of them pass, in proc (reach.go): each PATH
folder is asked (a stat and an open) in a goroutine of its own, all at
once, and one that hasn't answered in 1s is left out of the stamp and of
the look until its probe returns; a probe still out isn't started again,
so later looks skip the folder at once. With such a folder, the command
is looked for in the others, each as a path (exec.LookPath on dir/name).
An answer is trusted for a minute. findMise and FindShell's last resort
used exec.LookPath directly and now go through Look.

Test: TestHungPathFolderIsLeftOut puts a folder whose probe never
returns before the folder with the tool: three looks find the tool, PATH
is never walked whole, the folder is probed once; once it answers, PATH
is walked as before.

Run: go test ./internal/proc ./internal/claudetui on mote ok; go vet for
darwin, linux and windows ok; the proc look tests on the Windows box
(win-run) ok.
Broken by hand: with lookPath not asking hungDirs, the test is red
("PATH was walked 3 times", wsl-run).
Not tried: a real dead network mount on PATH; the test fakes it at the
probe. Direct exec.LookPath calls outside proc (daemon, library, update)
aren't on the startup path and are unchanged.
This commit is contained in:
yetone
2026-11-10 18:33:35 +08:00
parent b2509b9a81
commit f03ec97b8f
6 changed files with 304 additions and 5 deletions
+12 -1
View File
@@ -6,6 +6,7 @@ import (
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"time"
@@ -155,10 +156,20 @@ func pathDirs() []string {
// lookPath is exec.LookPath, with a command no folder of PATH has a name
// for answered as not found without looking.
// A folder of PATH that doesn't answer (reach.go) is left out: the
// command is looked for in the others, each as a path.
func lookPath(name string) (string, error) {
if !mayBeIn(name, pathDirs()) {
dirs := pathDirs()
hung := hungDirs(dirs)
if hung != nil {
dirs = slices.DeleteFunc(slices.Clone(dirs), func(d string) bool { return hung[d] })
}
if !mayBeIn(name, dirs) {
return "", &exec.Error{Name: name, Err: exec.ErrNotFound}
}
if hung != nil && !strings.ContainsAny(name, `/\`) {
return lookIn(name, dirs)
}
return execLookPath(name)
}
+6
View File
@@ -148,12 +148,18 @@ func lookStamp() (string, bool) {
b.WriteString(os.Getenv("PATHEXT"))
dirs := filepath.SplitList(os.Getenv("PATH"))
dirs = append(dirs, findDirs()...)
hung := hungDirs(dirs)
for _, d := range dirs {
if d == "" {
continue
}
b.WriteByte(0)
b.WriteString(d)
if hung[d] {
// not asked (reach.go); the stamp changes once it answers
b.WriteString("!")
continue
}
if st, err := os.Stat(d); err == nil {
b.WriteByte('@')
b.WriteString(strconv.FormatInt(st.ModTime().UnixNano(), 36))
+1 -2
View File
@@ -5,7 +5,6 @@ package proc
import (
"context"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
@@ -315,7 +314,7 @@ func FindShell(name string) string {
}
}
}
p, _ := exec.LookPath(name)
p, _ := Look(name)
return p
}
+176
View File
@@ -0,0 +1,176 @@
package proc
import (
"os"
"os/exec"
"path/filepath"
"sync"
"time"
)
// A folder on PATH on a mount that no longer answers (a network share
// gone away, an autofs path whose server is down) holds every stat and
// open in it until the mount comes back, which can be never. Looking a
// command up walks PATH in order, so a command not found before such a
// folder blocked whoever asked: magpie's start-up asks for every agent's
// command (agent.RenameLegacy → vscodePortableData → code-insiders), and
// `open -a` took over a minute to start while the same binary run from a
// shell, with another PATH, took one second (ifccod7391564 on X). A PATH
// folder is now asked in a goroutine of its own first, and one that
// hasn't answered in reachWait is left out of every look until it does.
// reachWait is how long a PATH folder has to answer; reachKeep how long
// its answer is trusted before it is asked again.
var (
reachWait = time.Second
reachKeep = time.Minute
)
// probeDir is the asking: a stat and an open of the folder, as a lookup
// does. Whatever either answers, the folder answered. A var for the tests.
var probeDir = func(dir string) {
if st, err := os.Stat(dir); err == nil && st.IsDir() {
if f, err := os.Open(dir); err == nil {
f.Close()
}
}
}
var reach struct {
sync.Mutex
m map[string]*reachProbe
}
type reachProbe struct {
done chan struct{}
deadline time.Time // when a probe not done counts as hung
at time.Time // when it answered, set before done closes
}
// answers reports whether dir answers within reachWait. A probe still out
// past its deadline isn't started again: every look leaves the folder out
// at once until that probe returns.
func answers(dir string) bool {
if dir == "" {
return true
}
now := time.Now()
reach.Lock()
p := reach.m[dir]
if p != nil {
select {
case <-p.done:
if now.Sub(p.at) < reachKeep {
reach.Unlock()
return true
}
p = nil // stale: asked again below
default:
}
}
if p == nil {
p = &reachProbe{done: make(chan struct{}), deadline: now.Add(reachWait)}
if reach.m == nil {
reach.m = map[string]*reachProbe{}
}
reach.m[dir] = p
go func(p *reachProbe) {
probeDir(dir)
p.at = time.Now()
close(p.done)
}(p)
}
reach.Unlock()
wait := time.Until(p.deadline)
if wait <= 0 {
select {
case <-p.done:
return true
default:
return false
}
}
t := time.NewTimer(wait)
defer t.Stop()
select {
case <-p.done:
return true
case <-t.C:
return false
}
}
// hungDirs are the folders of dirs that don't answer; nil when every one
// does. The folders are asked at once, so several gone mounts cost one
// reachWait, not one each.
func hungDirs(dirs []string) map[string]bool {
if allAnswered(dirs) {
return nil
}
var (
mu sync.Mutex
hung map[string]bool
wg sync.WaitGroup
)
for _, d := range dirs {
if d == "" {
continue
}
wg.Add(1)
go func(d string) {
defer wg.Done()
if !answers(d) {
mu.Lock()
if hung == nil {
hung = map[string]bool{}
}
hung[d] = true
mu.Unlock()
}
}(d)
}
wg.Wait()
return hung
}
// allAnswered reports whether every folder of dirs answered within
// reachKeep, so a look asks none of them (no goroutine each).
func allAnswered(dirs []string) bool {
now := time.Now()
reach.Lock()
defer reach.Unlock()
for _, d := range dirs {
if d == "" {
continue
}
p := reach.m[d]
if p == nil {
return false
}
select {
case <-p.done:
if now.Sub(p.at) >= reachKeep {
return false
}
default:
return false
}
}
return true
}
// lookIn is exec.LookPath over dirs alone, in their order: the command's
// name in each folder asked as a path, as exec.LookPath does along PATH.
// The current folder is left out, as exec.LookPath refuses a command
// found there (exec.ErrDot).
func lookIn(name string, dirs []string) (string, error) {
for _, d := range dirs {
if d == "" || d == "." {
continue
}
if p, err := execLookPath(filepath.Join(d, name)); err == nil {
return p, nil
}
}
return "", &exec.Error{Name: name, Err: exec.ErrNotFound}
}
+108
View File
@@ -0,0 +1,108 @@
package proc
import (
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// A PATH folder on a mount that doesn't answer is left out of a look, and
// the command is found in the folders after it: a look walking PATH past
// such a folder blocked magpie's start-up for over a minute, after `open
// -a` (ifccod7391564 on X). The gone mount is a probe that doesn't return
// and a walk of PATH that reports itself; the old lookup walked it.
func TestHungPathFolderIsLeftOut(t *testing.T) {
hung, good := t.TempDir(), t.TempDir()
tool := "magpie-reach-tool"
file := tool
if runtime.GOOS == "windows" {
file += ".exe"
}
if err := os.WriteFile(filepath.Join(good, file), []byte("#!/bin/sh\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", joinList([]string{hung, good}))
t.Setenv("NoDefaultCurrentDirectoryInExePath", "1")
release := make(chan struct{})
var probes atomic.Int32
oldProbe, oldWait := probeDir, reachWait
probeDir = func(d string) {
if d == hung {
probes.Add(1)
<-release
}
oldProbe(d)
}
reachWait = 200 * time.Millisecond
var once sync.Once
free := func() { once.Do(func() { close(release) }) }
resetReach := func() {
reach.Lock()
reach.m = nil
reach.Unlock()
}
resetReach()
t.Cleanup(func() {
free()
probeDir, reachWait = oldProbe, oldWait
resetReach()
})
var walked atomic.Int32
oldLook := execLookPath
execLookPath = func(name string) (string, error) {
if !strings.ContainsAny(name, `/\`) {
walked.Add(1) // exec.LookPath along all of PATH, the gone mount too
}
return oldLook(name)
}
t.Cleanup(func() { execLookPath = oldLook })
for i := 0; i < 3; i++ {
Forget()
done := make(chan struct{})
var p string
var err error
go func() {
p, err = Look(tool)
close(done)
}()
select {
case <-done:
case <-time.After(30 * time.Second):
t.Fatal("the look waited on the folder that doesn't answer")
}
if err != nil || filepath.Dir(p) != good {
t.Fatalf("look %d: %q, %v; want it in %s", i, p, err, good)
}
}
if n := walked.Load(); n != 0 {
t.Fatalf("PATH was walked %d times with a folder on it that doesn't answer", n)
}
// the folder is asked once while its first probe is out, not per look
if n := probes.Load(); n != 1 {
t.Fatalf("the folder was probed %d times, want 1", n)
}
// the mount answers again: PATH is walked as it was
free()
deadline := time.Now().Add(30 * time.Second)
for !answers(hung) {
if time.Now().After(deadline) {
t.Fatal("the folder never counted as answering again")
}
time.Sleep(10 * time.Millisecond)
}
Forget()
if p, err := Look(tool); err != nil || filepath.Dir(p) != good {
t.Fatalf("after: %q, %v", p, err)
}
if walked.Load() == 0 {
t.Fatal("a PATH whose folders all answer wasn't walked as exec.LookPath does")
}
}
+1 -2
View File
@@ -13,7 +13,6 @@ import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
@@ -239,7 +238,7 @@ func findMise(named string) string {
}
}
for _, n := range []string{filepath.Base(named), "mise"} {
if p, err := exec.LookPath(n); err == nil {
if p, err := Look(n); err == nil {
return p
}
if p := toolIn(n, runtime.GOOS, UserBinDirs()); p != "" {