Files
magpie/internal/proc/look.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

148 lines
4.0 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 (
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
// Looking a command up on PATH stats every candidate name in every PATH
// folder: on Windows 47 folders × PATHEXT's 11 extensions took 111ms for
// one that isn't there, and the pages asked once per known agent (59) and
// once per Pi session (297) on every request, so every page's first load
// took seconds and Sessions half a minute (#1771). LookPath and FindTool
// keep their answers while the folders they look in are unchanged: a tool
// installed or removed changes its folder's modification time, a changed
// PATH is another key, and Forget (the Agents page's refresh) looks again
// at once.
// lookFresh is how long the folders' stamp is trusted before it is taken
// again; within it an answer kept is given without a stat.
const lookFresh = 2 * time.Second
// lookFreshInTests is lookFresh in a test binary testenv isolated: none,
// so a test that installs a tool finds it at once, unless a test says.
var lookFreshInTests time.Duration
var looks struct {
sync.Mutex
gen int
env string // PATH and PATHEXT the stamp was taken with
stamp string
checked time.Time
m map[string]lookAnswer
}
type lookAnswer struct {
path string
err error
}
// LookPath is exec.LookPath, with a version manager's wrapper script found
// there given as the program it runs (Unwrap). Where it is on PATH is kept
// while the PATH folders are unchanged (Look); Unwrap keeps its own answer
// by the script's size and time.
func LookPath(name string) (string, error) {
p, err := Look(name)
if err != nil {
return p, err
}
return Unwrap(name, p), nil
}
// Look is exec.LookPath as it is, a wrapper script given as itself, the
// answer kept while the PATH folders are unchanged.
func Look(name string) (string, error) {
a := looked("look\x00"+name, func() lookAnswer {
p, err := lookPath(name)
return lookAnswer{p, err}
})
return a.path, a.err
}
// Forget drops every answer kept by LookPath and FindTool, so the next
// asks again: the reader asked to look for agents again.
func Forget() {
looks.Lock()
looks.m, looks.env, looks.stamp, looks.checked = nil, "", "", time.Time{}
looks.gen++
looks.Unlock()
forgetListings()
}
// looked is the answer kept for key, or ask's, kept.
func looked(key string, ask func() lookAnswer) lookAnswer {
env := os.Getenv("PATH") + "\x00" + os.Getenv("PATHEXT")
looks.Lock()
if looks.env != env || looks.checked.IsZero() || time.Since(looks.checked) >= lookWindow() {
looks.Unlock()
stamp := lookStamp() // a few stats, not under the lock
looks.Lock()
if stamp != looks.stamp {
looks.m, looks.stamp = nil, stamp
}
looks.env, looks.checked = env, time.Now()
}
if a, ok := looks.m[key]; ok {
looks.Unlock()
return a
}
gen, stamp := looks.gen, looks.stamp
looks.Unlock()
a := ask()
looks.Lock()
// an answer asked across a Forget or a change of the folders isn't kept
if looks.gen == gen && looks.stamp == stamp {
if looks.m == nil {
looks.m = map[string]lookAnswer{}
}
looks.m[key] = a
}
looks.Unlock()
return a
}
// lookWindow is lookFresh, or lookFreshInTests in a test binary.
func lookWindow() time.Duration {
if os.Getenv(sandboxVar) != "" {
return lookFreshInTests
}
return lookFresh
}
// lookStamp names what the answers depend on: PATH, PATHEXT, and each
// folder looked in with its modification time.
func lookStamp() string {
var b strings.Builder
b.WriteString(os.Getenv("PATH"))
b.WriteByte(0)
b.WriteString(os.Getenv("PATHEXT"))
dirs := filepath.SplitList(os.Getenv("PATH"))
dirs = append(dirs, findDirs()...)
for _, d := range dirs {
if d == "" {
continue
}
b.WriteByte(0)
b.WriteString(d)
if st, err := os.Stat(d); err == nil {
b.WriteByte('@')
b.WriteString(strconv.FormatInt(st.ModTime().UnixNano(), 36))
}
}
return b.String()
}
// findDirs are the folders FindTool looks in after PATH.
func findDirs() []string {
dirs := UserBinDirs()
if runtime.GOOS == "windows" {
dirs = append(dirs, SystemDirs(LoginPath()...)...)
}
return dirs
}