Files
magpie/internal/proc/listing.go
T
yetone 8a4cfe0e4e proc: a command that isn't installed is answered from each PATH folder's listing, not a stat per extension, so a Library change after a start no longer looks for ~100 agents' commands one file at a time on Windows (#1624, Hipple)
On every Library create, switch or delete, Targets() asks agent.Detected for
about a hundred agents. Each one's command is looked up with exec.LookPath,
and on Windows with FindTool's findDirs as well. A command that isn't
installed costs a stat of name+each PATHEXT extension in every folder. The
answers are cached (looked), but that cache is empty after a start and is
dropped whenever any PATH folder's mtime changes. With an antivirus slowing
every stat, that is the slow first change Hipple sees.

Each folder's listing is now read once (lower-cased names, also each name up
to every dot) and read again only when the folder's mtime changes. A
command that no folder has a name for is not found without a stat. One a
folder may hold, and any folder that can't be read, goes to exec.LookPath
and toolIn as before. On Windows the current folder is included unless
NoDefaultCurrentDirectoryInExePath is set, as exec.LookPath does.

Measured on the Windows test box (47 PATH folders, WSL agents off,
library ops through a throwaway test in a sandbox HOME):
- the first create after a start went from 486ms to 285ms; the old CPU
  profile was mostly exec.LookPath/GetFileAttributesEx;
- warm ops ~10ms either way.
With WSL agents on, the first op costs ~3.0s on both builds, about 2.7s of
it in wsl.exe list and probe spawns. This commit doesn't change that. On the
box, wsl -l -q, wsl -l --running -q and a docker-desktop probe each take
40-75ms, so a failed-probe retry every 10 min doesn't explain the report
there. The 5-8s after 10 min idle wasn't reproduced: ops after 4, 8 and 12
min idle took ~120ms.

Run: go test ./internal/proc ./internal/agent ./internal/library (ok);
gofmt -l; GOOS=linux and GOOS=windows go vet on the three packages.
I broke the fix by hand (look.go/find.go back to exec.LookPath, mayBeIn
check off), and TestMissingCommandsReadEachFolderOnce failed: "100 missing
commands were looked for on PATH 200 times, want 0".
2026-10-14 08:08:50 +08:00

165 lines
4.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package proc
import (
"errors"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
// A command that isn't installed was looked for with a stat of every
// name it could have (11 PATHEXT extensions on Windows) in every folder
// of PATH and of findDirs: hundreds of stats a command, and the Library
// and Agents pages ask for about a hundred agents' commands. The answers
// are kept (looked), but every one of them is asked again when any of
// those folders changes, and at the app's start, so the first change on
// the Library page after a start, or after some folder on PATH changed
// while it sat idle, took 5–8s on a Windows machine with 11 agents and an
// antivirus that slows each stat (#1624, Hipple). Each folder's listing is
// read once instead and kept while its modification time is unchanged: a
// command none of them has a name for isn't there, without a stat of its
// own; one that may be is looked for as before.
// listingRead is how many folders were read, and execLookPath what looks
// for a command that may be there; the tests count both.
var (
listingRead int
execLookPath = exec.LookPath
)
var listings struct {
sync.Mutex
m map[string]*listing
}
type listing struct {
mod time.Time
checked time.Time
// names are the folder's entries, lower-cased, each also as it is up
// to each dot in it: claude.exe is there as "claude" and "claude.exe"
names map[string]bool
}
// mayBeIn is whether name could be a program in one of dirs: false only
// when every folder was read and none has an entry name could be (name,
// or name and an extension, in any case). A folder that can't be read
// may have it.
func mayBeIn(name string, dirs []string) bool {
if name == "" || strings.ContainsAny(name, `/\:`) {
return true
}
key := strings.ToLower(name)
for _, d := range dirs {
if d == "" {
continue
}
if !filepath.IsAbs(d) {
abs, err := filepath.Abs(d)
if err != nil {
return true
}
d = abs
}
names, ok := listed(d)
if !ok || names[key] {
return true
}
}
return false
}
// listed is the names in dir, read again when its modification time
// changed (checked once a lookWindow); false when it can't be read.
func listed(dir string) (map[string]bool, bool) {
now := time.Now()
listings.Lock()
l := listings.m[dir]
if l != nil && now.Sub(l.checked) < lookWindow() {
listings.Unlock()
return l.names, true
}
listings.Unlock()
st, err := os.Stat(dir)
if errors.Is(err, os.ErrNotExist) {
// nothing is in a folder that isn't there
listings.Lock()
if listings.m == nil {
listings.m = map[string]*listing{}
}
listings.m[dir] = &listing{checked: now}
listings.Unlock()
return nil, true
}
if err != nil || !st.IsDir() {
return nil, false
}
if l != nil && l.names != nil && l.mod.Equal(st.ModTime()) {
listings.Lock()
l.checked = now
listings.Unlock()
return l.names, true
}
es, err := os.ReadDir(dir)
if err != nil {
return nil, false
}
names := make(map[string]bool, len(es))
for _, e := range es {
n := strings.ToLower(e.Name())
names[n] = true
for i := 1; i < len(n); i++ {
if n[i] == '.' {
names[n[:i]] = true
}
}
}
listings.Lock()
if listings.m == nil {
listings.m = map[string]*listing{}
}
listings.m[dir] = &listing{mod: st.ModTime(), checked: now, names: names}
listingRead++
listings.Unlock()
return names, true
}
// pathDirs are the folders exec.LookPath looks in: PATH's (an empty
// entry the current folder, but on Windows), and on Windows the current
// folder first unless NoDefaultCurrentDirectoryInExePath is set.
func pathDirs() []string {
dirs := filepath.SplitList(os.Getenv("PATH"))
if runtime.GOOS != "windows" {
// an empty entry is the current folder there
for i, d := range dirs {
if d == "" {
dirs[i] = "."
}
}
} else {
if _, off := os.LookupEnv("NoDefaultCurrentDirectoryInExePath"); !off {
dirs = append([]string{"."}, dirs...)
}
}
return dirs
}
// lookPath is exec.LookPath, with a command no folder of PATH has a name
// for answered as not found without looking.
func lookPath(name string) (string, error) {
if !mayBeIn(name, pathDirs()) {
return "", &exec.Error{Name: name, Err: exec.ErrNotFound}
}
return execLookPath(name)
}
// forgetListings drops the folders read.
func forgetListings() {
listings.Lock()
listings.m = nil
listings.Unlock()
}