wsl, masking: a hung WSL or a slow local model no longer holds requests

vsoullai on X (0.1.4190, Windows): the gateway froze. Each request waited
15s in turn on the local masking model, routing was held 30s and got a
504, and a stopped WSL distro's probe dragged everything down until
redactModel and WSL were turned off. #6167 (Codex held 30s then 504,
fixed by restarting WSL) and #4856 (masking timeouts, 504s) are the same.

WSL (internal/agent/wsl.go, wsl_links.go):
- wsl's lock was held through wsl.exe and through the stat of
  \\wsl.localhost\<distro>, which can't be cancelled. The GUI's look held
  it, and every request's Codex/Claude stand-in, wslUp, distroAt and
  Copilot's WSL folders queued behind it.
- A look (wslRefresh) now runs wsl.exe, the probes and the stat outside
  the lock. Looks take turns on wslRefreshMu, and the lock only guards
  reads and writes.
- wslRoot's stat is bounded (wslRootWait 5s); a distro whose / can't be
  opened fails its probe and is tried again later.
- What a request asks never waits on a look. "Which distros run" is
  asked single-flight in the background and waited for at most
  wslRunningWait (2s). A distro wsl.exe hasn't named as running counts
  as stopped, so nothing opens or wakes a distro on a guess.
- Copilot's WSL sign-in (internal/provider/copilot_cli.go) is read the
  same way: single-flight, waited for at most copilotWSLWait (2s), with
  the last answer kept. Before, its own mutex queued every request
  behind the first one's read.

Masking (internal/masking/masking.go):
- With redactModel on, each request waited up to strictWait (15s). In a
  burst the backlog grew and the requests waited one after another.
- Once a strict request runs out its wait with texts unread, the model
  is "behind". The next requests then wait only defaultWait (2s) until a
  request is read whole or a minute passes (behind, waitFor). The rules
  still mask everything the model hasn't read.

Docs: docs/subsystems/agent-wiring.md (WSL twins) and gateway-routing.md
(masking).

Run:
- New tests, on mote, -race -count=3: TestWSLHangHoldsNoRequest (wsl.exe
  --running, a distro's probe, the stat; each hang injected),
  TestWSLRootHangFailsProbe, TestCopilotWSLHangHoldsNoRequest and
  TestStrictModelBehindWaitsTheDefault, with the other WSL, Copilot WSL
  and masking tests. All ok.
- Broken by hand: the same tests on the old code (origin/main's files
  with only the new tests added). Each WSL hang case failed ("a Codex
  stand-in waited on a hung WSL past 2.2s", "the GUI's look didn't wait
  on the hung WSL"). The Copilot test failed ("13 requests waited on a
  hung WSL past 2.2s"). The masking test failed ("request 2 after the
  model fell behind waited 2.0s").
- Full suite on mica at f08597a58 (this change on b754cb095):
  `go test -timeout 45m ./...`, exit 0, 101 packages ok.
- Rebased on f03869520 (a gateway/provider change). At this head, on
  mica: go test -count=1 ./internal/agent ./internal/provider
  ./internal/masking ./internal/gateway all ok, go vet ./internal/... and
  GOOS=windows vet of those four ok, gofmt clean. The full suite ran at
  the base before it, not again at this head.
- Rebased again on c0cf352a8 (four commits: gateway, provider Codex
  hold, providers base URL, LESSONS). At this pushed head, on mica:
  go test -count=1 ./internal/provider ./internal/masking ok, the WSL and
  Copilot tests of internal/agent ok, go vet of agent, provider and
  gateway (darwin and GOOS=windows) ok.
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
  GOOS=windows: ok.
- Windows (xiaomi-gpu, win-run), internal/agent, internal/provider and
  internal/masking. masking: ok. agent and provider: 52 reds, all in the
  53 that origin/main f03869520 has on the same box (#6068, #1827,
  #5068, #5344, #5950; this run's list is on #6068). None touch WSL,
  Copilot's WSL or masking.

Not tried: a real hung WSL. On xiaomi-gpu, wsl -l -q and -l --running
answered in ~55ms, and a terminated distro's \\wsl.localhost path failed
in 131ms, so the hang was injected in the tests, not reproduced live.

(vsoullai on X, #6167, #4856)
This commit is contained in:
yetone
2026-11-15 06:20:15 +08:00
parent c0cf352a8d
commit f1c9014cd9
11 changed files with 673 additions and 101 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+269 -77
View File
@@ -1210,8 +1210,12 @@ func wslHomes() []sessions.WSLHome {
if !wslLooks() {
return nil
}
return wslHomesOf(wslDistros())
}
func wslHomesOf(ds []distro) []sessions.WSLHome {
var out []sessions.WSLHome
for _, d := range wslDistros() {
for _, d := range ds {
if d.Root == "" || d.Home == "" {
continue
}
@@ -1255,10 +1259,14 @@ var wslAntigravityDirs = []string{".gemini/antigravity", ".gemini/antigravity-in
// copilotWSLDirs are the Copilot CLI's folders, as magpie opens them (where
// a link leads, #4502), in the running distros it was found in, for
// provider to read its sign-in in; none off Windows. A stopped distro is
// left out: reading it would start it.
// left out: reading it would start it. It is asked on a request's path
// (provider's accounts), so it waits for WSL at most wslRunningWait.
func copilotWSLDirs() []string {
if !wslLooks() {
return nil
}
var out []string
for _, h := range wslHomes() {
for _, h := range wslHomesOf(wslDistrosWithin(wslRunningWait)) {
if h.Running && wslHasCopilot(h.Distro) {
out = append(out, h.Open(filepath.Join(h.Home, wslCopilotDir)))
}
@@ -1301,8 +1309,7 @@ const (
// which would start it again (TJHHHH on Discord)
wslRunningAge = 3 * time.Second
// wslRunningFailedAge is how long wsl.exe failing to say is kept: each
// ask that times out holds wsl's lock, and so the GUI, for 10s, and
// leaves a wsl.exe behind (#2341)
// ask that times out takes 10s and leaves a wsl.exe behind (#2341)
wslRunningFailedAge = 30 * time.Second
)
@@ -1371,12 +1378,34 @@ var wslRun = func(timeout time.Duration, args ...string) ([]byte, error) {
return out, err
}
// wslRoot is where magpie opens a running distro's / from; a var for tests.
// wslRootWait is how long wslRoot waits for Windows to open a distro's
// /: a stat of WSL's file share can't be cancelled, and hangs while WSL
// does. A var for tests.
var wslRootWait = 5 * time.Second
// wslStat is os.Stat, for wslRoot; a var for tests.
var wslStat = os.Stat
// wslRoot is where magpie opens a running distro's / from, "" when
// Windows didn't open it within wslRootWait (the probe failed, and is
// tried again in wslRetryAge); a var for tests.
var wslRoot = func(name string) string {
if _, err := os.Stat(`\\wsl.localhost\` + name + `\`); err == nil {
return `\\wsl.localhost\` + name
ok, stat := make(chan bool, 1), wslStat
go func() {
_, err := stat(`\\wsl.localhost\` + name + `\`)
ok <- err == nil
}()
t := time.NewTimer(wslRootWait)
defer t.Stop()
select {
case found := <-ok:
if found {
return `\\wsl.localhost\` + name
}
return `\\wsl$\` + name // before Windows 11 / WSL 0.50
case <-t.C:
return ""
}
return `\\wsl$\` + name // before Windows 11 / WSL 0.50
}
// wslHungPath, while recent, says a wsl.exe listing timed out: each
@@ -1405,39 +1434,48 @@ func wslHung(hung bool) {
func wslStatePath() string { return filepath.Join(filepath.Dir(provider.Path()), "wsl.json") }
func wslDistros() []distro {
// wslRefreshMu is held by the one refresh of what magpie knows of WSL
// (wslRefresh) at a time. wsl.exe and the distros' files are asked while
// it is held, never under wsl's own lock: that is taken only to read and
// write what they said. A probe, a listing or an open of a distro's /
// that hangs held wsl's lock before, so the GUI listing agents, a
// request's stand-in and Copilot's sign-in all waited on a hung wsl.exe,
// and the gateway sent 504s after 30s (vsoullai on X, #6167).
var wslRefreshMu sync.Mutex
// wslRefresh lists the distros again when the list is older than
// wslListAge, asks which run, and probes the running ones not probed yet.
func wslRefresh() {
wslRefreshMu.Lock()
defer wslRefreshMu.Unlock()
wsl.Lock()
defer wsl.Unlock()
if wsl.seen == nil {
wsl.seen, wsl.probed, wsl.failed = map[string]*distro{}, map[string]bool{}, map[string]time.Time{}
if b, err := os.ReadFile(wslStatePath()); err == nil {
json.Unmarshal(b, &wsl.seen)
}
wslForgetOldBins()
}
if time.Since(wsl.at) > wslListAge {
if wsl.at.IsZero() && wslHungLately() {
// another magpie waited out a hung wsl.exe moments ago: a
// command doesn't wait 10s more (this one lists again in a minute)
wsl.names, wsl.listed = nil, false
} else {
wslLoadLocked()
list := time.Since(wsl.at) > wslListAge
// another magpie waited out a hung wsl.exe moments ago: a command
// doesn't wait 10s more (this one lists again in a minute)
skip := list && wsl.at.IsZero() && wslHungLately()
wsl.Unlock()
if list {
var names []string
var listed bool
if !skip {
start := time.Now()
wsl.names, wsl.listed = wslList("-l", "-q")
wslHung(!wsl.listed && time.Since(start) >= wslHungAfter)
names, listed = wslList("-l", "-q")
wslHung(!listed && time.Since(start) >= wslHungAfter)
}
wsl.at = time.Now()
if !wsl.listed || len(wsl.names) == 0 {
wsl.Lock()
wsl.names, wsl.listed, wsl.at = names, listed, time.Now()
if !listed || len(names) == 0 {
// none to run: a wsl.exe that couldn't list them isn't asked
// again which run, another timeout under the lock the GUI waits on
wsl.running, wsl.runOK, wsl.runAt = map[string]bool{}, wsl.listed, time.Now()
// again which run
wsl.running, wsl.runOK, wsl.runAt = map[string]bool{}, listed, time.Now()
}
wsl.Unlock()
}
wslRunningLocked()
installed := map[string]bool{}
cfg := wslConfig()
var out []distro
wslRunningWithin(-1)
wsl.Lock()
var probe []string
for _, n := range wsl.names {
installed[n] = true
// a distro that stopped is probed again once it runs: WSL may have
// been restarted meanwhile in another networking mode
if !wsl.running[n] {
@@ -1445,41 +1483,126 @@ func wslDistros() []distro {
}
if wsl.running[n] && !wsl.probed[n] {
if t, ok := wsl.failed[n]; !ok || time.Since(t) > wslRetryAge {
if d := wslProbe(n); d == nil {
wsl.failed[n] = time.Now()
} else {
wsl.probed[n] = true
if wslKept(*d) {
if old := wsl.seen[n]; old != nil {
d.Values = old.Values
d.Was = wslWas(old.Was, old.Gateway, d.Gateway)
}
wsl.seen[n] = d
} else {
delete(wsl.seen, n)
}
wsl.dirty = true
}
probe = append(probe, n)
}
}
}
wsl.Unlock()
for _, n := range probe {
d := wslProbe(n)
wsl.Lock()
if d == nil {
wsl.failed[n] = time.Now()
} else {
wsl.probed[n] = true
if wslKept(*d) {
if old := wsl.seen[n]; old != nil {
d.Values = old.Values
d.Was = wslWas(old.Was, old.Gateway, d.Gateway)
}
wsl.seen[n] = d
} else {
delete(wsl.seen, n)
}
wsl.dirty = true
}
wsl.Unlock()
}
wsl.Lock()
defer wsl.Unlock()
// an unregistered distro is forgotten
if wsl.listed {
installed := map[string]bool{}
for _, n := range wsl.names {
installed[n] = true
}
for n := range wsl.seen {
if !installed[n] {
delete(wsl.seen, n)
wsl.dirty = true
}
}
}
wslSaveLocked()
}
// wslLoadLocked reads wsl.json the first time it is wanted.
func wslLoadLocked() {
if wsl.seen != nil {
return
}
wsl.seen, wsl.probed, wsl.failed = map[string]*distro{}, map[string]bool{}, map[string]time.Time{}
if b, err := os.ReadFile(wslStatePath()); err == nil {
json.Unmarshal(b, &wsl.seen)
}
wslForgetOldBins()
}
// wslDistros are the distros agents were found in, after a refresh
// (wslRefresh), which this waits for: for the GUI and what runs in the
// background. A request's path takes wslDistrosWithin.
func wslDistros() []distro {
wslRefresh()
return wslKnown()
}
// wslBg is the refresh wslDistrosWithin started, while it runs.
var wslBg struct {
sync.Mutex
done chan struct{}
}
// wslDistrosWithin is wslDistros waiting at most wait for the refresh,
// one at a time in the background: what is known then is answered, and
// a distro whose running wsl.exe hasn't said in time is taken as stopped.
func wslDistrosWithin(wait time.Duration) []distro {
wslBg.Lock()
if wslBg.done == nil {
done := make(chan struct{})
wslBg.done = done
go func() {
wslRefresh()
wslBg.Lock()
wslBg.done = nil
wslBg.Unlock()
close(done)
}()
}
done := wslBg.done
wslBg.Unlock()
t := time.NewTimer(wait)
defer t.Stop()
select {
case <-done:
case <-t.C:
}
return wslKnown()
}
// wslKnown are the distros as last refreshed, each with whether it runs:
// none does while wsl.exe is being asked and its last answer is older
// than wslRunningAge.
func wslKnown() []distro {
asking := wslRunAsking()
cfg := wslConfig()
wsl.Lock()
wslLoadLocked()
known := !asking || wslRunFreshLocked()
var out []distro
for _, n := range wsl.names {
d := wsl.seen[n]
if d == nil {
continue
}
c := *d
c.Running = wsl.running[n]
c.Running = known && wsl.running[n]
c.up = func() bool { return wslUp(n) }
c.mirror(cfg)
out = append(out, c)
}
// an unregistered distro is forgotten
for n := range wsl.seen {
if wsl.listed && !installed[n] {
delete(wsl.seen, n)
wsl.dirty = true
}
wsl.Unlock()
for i := range out {
out[i].mirror(cfg)
}
wslSaveLocked()
return out
}
@@ -1522,25 +1645,86 @@ func wslForgetOldBins() {
}
}
// wslRunningLocked lists the running distros again (wsl.exe -l --running,
// which starts none) when the last list is older than wslRunningAge. When
// wsl.exe can't say, none is taken to run: a distro is never opened on a
// guess.
func wslRunningLocked() {
// wslRunAsk is the wsl.exe -l --running in flight, and when it started.
// It is asked outside wsl's lock, once at a time however many wait on it.
var wslRunAsk struct {
sync.Mutex
done chan struct{}
start time.Time
}
// wslRunningWait is how long what reads a distro's files waits for
// wsl.exe to say which run, from when it was asked: one that hangs is
// taken as running none, and a stand-in, a request's or Copilot's
// sign-in, goes without the distro's files rather than waiting out its
// 10s (vsoullai on X, #6167). A var for tests.
var wslRunningWait = 2 * time.Second
// wslRunFreshLocked is whether which distros run is as wsl.exe said at
// most wslRunningAge ago (wslRunningFailedAge when it couldn't say).
func wslRunFreshLocked() bool {
age := wslRunningAge
if !wsl.runOK {
age = wslRunningFailedAge
}
if !wsl.runAt.IsZero() && time.Since(wsl.runAt) <= age {
return
return !wsl.runAt.IsZero() && time.Since(wsl.runAt) <= age
}
// wslRunAsking is whether wsl.exe is being asked which distros run.
func wslRunAsking() bool {
wslRunAsk.Lock()
defer wslRunAsk.Unlock()
return wslRunAsk.done != nil
}
// wslRunningWithin lists the running distros again (wsl.exe -l
// --running, which starts none) when the last list is older than
// wslRunningAge, and waits for the answer at most wait from when it was
// asked (a negative wait: until wsl.exe answers or times out). false:
// wsl.exe hasn't said in time, and none is to be taken to run. When
// wsl.exe can't say, none is taken to run either: a distro is never
// opened on a guess. Never called under wsl's lock.
func wslRunningWithin(wait time.Duration) bool {
wsl.Lock()
fresh := wslRunFreshLocked()
wsl.Unlock()
if fresh {
return true
}
run, ok := wslList("-l", "--running", "-q")
wsl.runOK = ok
wsl.running = map[string]bool{}
for _, n := range run {
wsl.running[n] = true
wslRunAsk.Lock()
if wslRunAsk.done == nil {
done := make(chan struct{})
wslRunAsk.done, wslRunAsk.start = done, time.Now()
go func() {
run, ok := wslList("-l", "--running", "-q")
wsl.Lock()
wsl.runOK = ok
wsl.running = map[string]bool{}
for _, n := range run {
wsl.running[n] = true
}
wsl.runAt = time.Now()
wsl.Unlock()
wslRunAsk.Lock()
wslRunAsk.done = nil
wslRunAsk.Unlock()
close(done)
}()
}
done, start := wslRunAsk.done, wslRunAsk.start
wslRunAsk.Unlock()
if wait < 0 {
<-done
return true
}
t := time.NewTimer(time.Until(start.Add(wait)))
defer t.Stop()
select {
case <-done:
return true
case <-t.C:
return false
}
wsl.runAt = time.Now()
}
// wslUp is whether distro runs, as wsl.exe said at most wslRunningAge ago:
@@ -1548,9 +1732,11 @@ func wslRunningLocked() {
// catalog synced, requests counted, sessions listed) asks it first, so a
// distro stopped since its agent was made isn't started again.
func wslUp(distro string) bool {
if !wslRunningWithin(wslRunningWait) {
return false
}
wsl.Lock()
defer wsl.Unlock()
wslRunningLocked()
return wsl.running[distro]
}
@@ -1623,7 +1809,7 @@ func wslLastSeen(name, key string) string {
// wslReady are the distros running now that the probe found kind in, each
// with its mirrored networking settled, ready for a read of its files.
// Only magpie's memory of them and which run (wslRunningLocked) are
// Only magpie's memory of them and which run (wslRunningWithin) are
// asked — nothing is probed, and a stopped distro is never opened.
// Detection off (wslLooks) reads none: a request's stand-in asks wsl.exe
// nothing, which on a machine without WSL would answer with a console
@@ -1632,8 +1818,10 @@ func wslReady(kind string) []distro {
if !wslLooks() {
return nil
}
if !wslRunningWithin(wslRunningWait) {
return nil
}
wsl.Lock()
wslRunningLocked()
var ds []distro
for _, n := range wsl.names {
if d := wsl.seen[n]; d != nil && wsl.running[n] && wslKindOf(kind).found(*d) {
@@ -1667,8 +1855,10 @@ func wslClaudeClassifier(model string) string {
if !wslLooks() {
return ""
}
if !wslRunningWithin(wslRunningWait) {
return ""
}
wsl.Lock()
wslRunningLocked()
var ds []distro
for _, n := range wsl.names {
if d := wsl.seen[n]; d != nil && wsl.running[n] && wslKindOf("claude").found(*d) {
@@ -1824,7 +2014,9 @@ func wslProbe(name string) *distro {
return nil
}
if wslKept(*d) {
d.Root = wslRoot(name)
if d.Root = wslRoot(name); d.Root == "" {
return nil
}
}
return d
}
+6 -1
View File
@@ -29,10 +29,13 @@ func FakeWSL(probes, roots map[string]string) func() {
names = append(names, n)
}
list := []byte(strings.Join(names, "\n"))
var stoppedMu sync.Mutex // wsl.exe is asked outside wsl's lock
stopped := map[string]bool{}
fakeStop = func(name string, stop bool) {
wsl.Lock()
stoppedMu.Lock()
stopped[name] = stop
stoppedMu.Unlock()
wsl.Lock()
wsl.runAt = time.Time{}
wsl.Unlock()
}
@@ -46,11 +49,13 @@ func FakeWSL(probes, roots map[string]string) func() {
return list, nil
case "-l --running -q":
var run []string
stoppedMu.Lock()
for _, n := range names {
if !stopped[n] {
run = append(run, n)
}
}
stoppedMu.Unlock()
return []byte(strings.Join(run, "\n")), nil
}
if len(args) > 2 && args[0] == "-d" {
+153
View File
@@ -0,0 +1,153 @@
package agent
import (
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// vsoullai on X, #6167: a WSL that hangs (a distro stopping, WSL's file
// share wedged) held wsl's lock while the GUI listed agents, so a
// request's stand-in and Copilot's sign-in (provider's accounts, on every
// request's path) waited on it, the gateway's unrouted watch sent 504s
// after 30s, and the Copilot sign-in's own lock queued every request
// behind the first. Whatever hangs, wsl.exe listing which run, a distro's
// probe or the open of its /, what a request asks of WSL answers within
// wslRunningWait, as running none when wsl.exe hasn't said.
func TestWSLHangHoldsNoRequest(t *testing.T) {
for _, hang := range []string{"-l --running -q", "-d Ubuntu", "stat"} {
t.Run(hang, func(t *testing.T) {
root, home := codexDistroHome(t, "model_provider = \"magpie\"\nmodel = \"relay/main\"\n")
os.MkdirAll(filepath.Join(home, ".copilot"), 0o755)
fakeWSL(t, "Ubuntu\r\n", "Ubuntu\r\n", map[string]string{
"Ubuntu": "home:/home/me\ndir:.codex\ndir:.copilot\nroute:default via 172.20.0.1 dev eth0\n",
}, map[string]string{"Ubuntu": root})
// a first look while WSL answered: Ubuntu is known, with Codex
if ds := wslDistros(); len(ds) != 1 || !ds[0].Running {
t.Fatalf("%+v", ds)
}
wait := wslRunningWait
wslRunningWait = 200 * time.Millisecond
t.Cleanup(func() { wslRunningWait = wait })
release := make(chan struct{})
var once sync.Once
free := func() { once.Do(func() { close(release) }) }
hung := make(chan struct{}, 8)
run, root0 := wslRun, wslRoot
wslRun = func(d time.Duration, args ...string) ([]byte, error) {
if strings.HasPrefix(strings.Join(args, " "), hang) {
hung <- struct{}{}
<-release
}
return run(d, args...)
}
if hang == "stat" {
// Windows' open of the distro's / over WSL's share hangs
wslRoot = func(name string) string {
hung <- struct{}{}
<-release
return root0(name)
}
}
gui := make(chan struct{})
t.Cleanup(func() {
free()
<-gui
wslSettle()
wslRun, wslRoot = run, root0
})
// the GUI looks again (a rescan): it waits on the hung wsl.exe
wsl.Lock()
wsl.runAt = time.Time{}
wsl.probed, wsl.failed = map[string]bool{}, map[string]time.Time{}
wsl.Unlock()
go func() { defer close(gui); wslDistros() }()
select {
case <-hung:
case <-time.After(10 * time.Second):
t.Fatal("the hang was never reached")
}
bar := wslRunningWait + 2*time.Second
within := func(name string, f func()) {
t.Helper()
done := make(chan struct{})
start := time.Now()
go func() { defer close(done); f() }()
select {
case <-done:
case <-time.After(bar):
t.Errorf("%s waited on a hung WSL past %v", name, bar)
free()
<-done
}
if d := time.Since(start); d > bar {
t.Errorf("%s took %v", name, d)
}
}
within("a Codex stand-in", func() { wslCodexStandIn() })
within("a Claude classifier stand-in", func() { wslClaudeClassifier("claude-haiku-4-5") })
within("whether Ubuntu runs", func() { wslUp("Ubuntu") })
within("Copilot's folders", func() { copilotWSLDirs() })
within("a path's distro", func() { distroAt(filepath.Join(root, "home", "me")) })
within("a host a distro reached Windows at", func() { wslHost("http://172.20.0.1:3425") })
within("what WSLKeep kept", func() { WSLKept("Ubuntu", "x") })
select {
case <-gui:
t.Fatal("the GUI's look didn't wait on the hung WSL")
default:
}
// many requests at once don't queue behind each other
var wg sync.WaitGroup
start := time.Now()
for range 13 {
wg.Add(1)
go func() { defer wg.Done(); copilotWSLDirs(); wslCodexStandIn() }()
}
wg.Wait()
if d := time.Since(start); d > bar {
t.Errorf("13 requests at once took %v", d)
}
})
}
}
// wslSettle waits for a look and an ask of wsl.exe started in the
// background to end.
func wslSettle() {
for _, m := range []func() chan struct{}{
func() chan struct{} { wslBg.Lock(); defer wslBg.Unlock(); return wslBg.done },
func() chan struct{} { wslRunAsk.Lock(); defer wslRunAsk.Unlock(); return wslRunAsk.done },
} {
if ch := m(); ch != nil {
<-ch
}
}
}
// A distro's / that Windows can't open in wslRootWait (a stat of WSL's
// share can't be cancelled) fails its probe, tried again in wslRetryAge,
// instead of holding the look for ever.
func TestWSLRootHangFailsProbe(t *testing.T) {
stat, w := wslStat, wslRootWait
release := make(chan struct{})
t.Cleanup(func() { close(release); wslStat, wslRootWait = stat, w })
wslRootWait = 100 * time.Millisecond
wslStat = func(string) (os.FileInfo, error) { <-release; return nil, os.ErrNotExist }
start := time.Now()
if r := wslRoot("Ubuntu"); r != "" {
t.Fatalf("root %q", r)
}
if d := time.Since(start); d > 2*time.Second {
t.Fatalf("waited %v", d)
}
wslStat = func(string) (os.FileInfo, error) { return nil, nil }
if r := wslRoot("Ubuntu"); r != `\\wsl.localhost\Ubuntu` {
t.Fatalf("root %q", r)
}
}
+4 -2
View File
@@ -26,10 +26,12 @@ var wslExec = func(distro string, argv ...string) ([]byte, error) {
// distroAt is the running distro local, a path as magpie opens it, is in:
// under its root, or under where one of its Links leads (distro.native).
func distroAt(local string) (distro, bool) {
// a command run in a stopped distro would start it (wslUp)
if !wslRunningWithin(wslRunningWait) {
return distro{}, false
}
wsl.Lock()
defer wsl.Unlock()
// a command run in a stopped distro would start it (wslUp)
wslRunningLocked()
for name, d := range wsl.seen {
if d == nil || d.Root == "" || !wsl.running[name] {
continue
+1 -1
View File
@@ -327,7 +327,7 @@ func TestWSLListFails(t *testing.T) {
// requests it made. None of them opens the stopped distro, which would
// start it: its fields read as last seen, and the next look neither probes
// #2341: wsl.exe failing to say which distros run (a hung WSL times out
// after 10s, under wsl's lock) is asked again only after
// after 10s) is asked again only after
// wslRunningFailedAge, not every wslRunningAge; an answer still lasts only
// wslRunningAge.
func TestWSLRunningFailedKept(t *testing.T) {
+39 -6
View File
@@ -192,11 +192,38 @@ var defaultWait = 2 * time.Second
// the same history, finds it. A var for tests.
var strictWait = 15 * time.Second
// behind is when a request last ran out its strictWait with text of its
// own the model hadn't read (0: none since one was read in full). The
// model is behind then, on a CPU too slow for what the agents send, and
// every request waited all of strictWait for it: on Windows, with
// AstrLink Guard turned on, each request sat 15s, one after another
// (vsoullai on X, #4856). For behindAge after, or until a request is read
// in full, a request waits defaultWait, as the model on by default does:
// what it read is masked with its finds and the rest by the rules, so
// nothing the rules mask goes as written, and what it reads meanwhile is
// kept for the next turn.
var behind atomic.Int64
const behindAge = time.Minute
// waitFor is how long a request waits for the model: strictWait when the
// user turned it on, unless it is behind.
func waitFor(strict bool) time.Duration {
if !strict {
return defaultWait
}
if t := behind.Load(); t != 0 && time.Since(time.Unix(0, t)) < behindAge {
return min(defaultWait, strictWait)
}
return strictWait
}
// model is the local model m (internal/pii) as redact's Model, keeping
// what it is at least min sure of, waited for until ctx ends or the wait
// runs out: defaultWait for the model on by default, strictWait for one
// the user turned on (strict), from now. A wait that runs out, or a ctx
// that ends, keeps what the model had read of the texts by then (a
// the user turned on (strict) unless it is behind (waitFor), from now. A
// wait that runs out, or a ctx that ends, keeps what the model had read
// of the texts by then (a
// pii.Partial), and the rules mask the rest alone. A model that fails
// (didn't load, isn't on disk, held back after a failure) panics where
// the user turned it on, and the request is held back (gwmw.Safely)
@@ -204,10 +231,7 @@ var strictWait = 15 * time.Second
// model's, and it is broken, not busy. On by default, it finds nothing
// then: the rules mask alone.
func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Model {
wait := defaultWait
if strict {
wait = strictWait
}
wait := waitFor(strict)
by := time.Now().Add(wait)
return func(texts []string) [][]redact.Found {
if !strict {
@@ -221,6 +245,11 @@ func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Mo
switch {
case errors.As(err, &p):
notePartial(p, wait)
if strict && p.Missing > 0 && errors.Is(p.Err, context.DeadlineExceeded) {
// its own text wasn't read in time (not only a backlog
// sent before, nor a client that went away)
behind.Store(time.Now().UnixNano())
}
if len(got) != len(texts) {
got = make([][]redact.Found, len(texts))
}
@@ -228,6 +257,10 @@ func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Mo
panic(err)
case err != nil:
return make([][]redact.Found, len(texts))
default:
if strict {
behind.Store(0)
}
}
out := make([][]redact.Found, len(got))
for i, fs := range got {
+52 -1
View File
@@ -220,6 +220,7 @@ func TestDefaultModelHangingIsTheRules(t *testing.T) {
// TestStrictModelStalledIsTheRulesForWhatItDidntRead's)
wasStrict := strictWait
strictWait = time.Hour
behind.Store(0) // not behind: a strict wait is waited whole
t.Cleanup(func() { strictWait = wasStrict })
done := make(chan any, 1)
go func() {
@@ -276,7 +277,7 @@ func TestStrictModelStalledIsTheRulesForWhatItDidntRead(t *testing.T) {
fetch = func(pii.Model, bool) {}
onDisk = func() bool { return true }
strictWait = 200 * time.Millisecond
t.Cleanup(func() { picked, fetch, onDisk, strictWait = wasPicked, wasFetch, wasDisk, wasWait })
t.Cleanup(func() { picked, fetch, onDisk, strictWait = wasPicked, wasFetch, wasDisk, wasWait; behind.Store(0) })
key := "sk-ant-api03-" + strings.Repeat("a", 40)
mask := func(body []byte) ([]byte, int, any) {
@@ -322,6 +323,56 @@ func TestStrictModelStalledIsTheRulesForWhatItDidntRead(t *testing.T) {
}
}
// slow is a model that reads a text it has "seen" at once and needs
// longer than any wait for one it hasn't: a CPU too slow for what the
// agents send.
type slow struct{ fake }
func (slow) Find(ctx context.Context, texts []string) ([][]redact.Found, error) {
missing := 0
for _, s := range texts {
if strings.Contains(s, "unread") {
missing++
}
}
if missing == 0 {
return make([][]redact.Found, len(texts)), nil
}
<-ctx.Done()
return make([][]redact.Found, len(texts)), &pii.Partial{Missing: missing, Of: len(texts), Err: ctx.Err()}
}
// vsoullai on X, #4856 (Windows, the local model turned on): the model
// couldn't keep up, and each request waited all of strictWait for it, one
// after another. Once a request's own text wasn't read in its strictWait,
// the next wait defaultWait, until a request is read in full again. The
// rules mask what the model didn't read either way.
func TestStrictModelBehindWaitsTheDefault(t *testing.T) {
wasStrict, wasDefault := strictWait, defaultWait
strictWait, defaultWait = 2*time.Second, 50*time.Millisecond
behind.Store(0)
t.Cleanup(func() { strictWait, defaultWait = wasStrict, wasDefault; behind.Store(0) })
m := slow{fake{installed: true}}
took := func(text string) time.Duration {
start := time.Now()
model(context.Background(), m, 0.8, true)([]string{text})
return time.Since(start)
}
if d := took("unread tool result"); d < strictWait {
t.Fatalf("the first request didn't wait strictWait: %v", d)
}
for i := range 3 {
if d := took("unread tool result"); d >= strictWait/2 {
t.Fatalf("request %d after the model fell behind waited %v", i+2, d)
}
}
// a request read in full: the model caught up, strictWait again
took("read before")
if d := took("unread tool result"); d < strictWait {
t.Fatalf("after one read in full, a request waited %v", d)
}
}
// bounds is a model that says whether it was asked Bounded.
type bounds struct {
fake
+41 -11
View File
@@ -66,11 +66,21 @@ var CopilotWSLDirs func() []string
// read: its files are read over WSL's file share, slower than a disk's.
var copilotWSLAge = 20 * time.Second
// copilotWSLWait is how long a request waits for a distro's sign-in to
// be read again, from when that read started: one read at a time, outside
// copilotWSL's lock, and a read WSL holds up answers the sign-in read
// before. Held under the lock, a hung WSL queued every request behind
// the first, and the gateway sent 504s after 30s (vsoullai on X, #6167).
// A var for tests.
var copilotWSLWait = 2 * time.Second
var copilotWSL struct {
sync.Mutex
at time.Time
app copilotApp
ok bool
at time.Time
app copilotApp
ok bool
done chan struct{} // closed when the read in flight ends
start time.Time // when it started
}
// copilotCLILogin is the account the Copilot CLI is signed in to, with its
@@ -90,18 +100,38 @@ func copilotCLILogin() (copilotApp, bool) {
}
c := &copilotWSL
c.Lock()
defer c.Unlock()
if !c.at.IsZero() && time.Since(c.at) < copilotWSLAge {
defer c.Unlock()
return c.app, c.ok
}
c.app, c.ok = copilotApp{}, false
for _, dir := range CopilotWSLDirs() {
if app, ok := copilotCLILoginIn(dir, nil); ok {
c.app, c.ok = app, true
break
}
if c.done == nil {
done, dirs := make(chan struct{}), CopilotWSLDirs
c.done, c.start = done, time.Now()
go func() {
var found copilotApp
ok := false
for _, dir := range dirs() {
if app, in := copilotCLILoginIn(dir, nil); in {
found, ok = app, true
break
}
}
c.Lock()
c.app, c.ok, c.at, c.done = found, ok, time.Now(), nil
c.Unlock()
close(done)
}()
}
c.at = time.Now()
done, start := c.done, c.start
c.Unlock()
t := time.NewTimer(time.Until(start.Add(copilotWSLWait)))
defer t.Stop()
select {
case <-done:
case <-t.C:
}
c.Lock()
defer c.Unlock()
return c.app, c.ok
}
+106
View File
@@ -0,0 +1,106 @@
package provider
import (
"os"
"path/filepath"
"sync"
"testing"
"time"
)
// vsoullai on X, #6167: the Copilot CLI's sign-in in a WSL distro is read
// on every request's path (the accounts), and was read under
// copilotWSL's lock: a WSL that hung held the first request and queued
// every other behind it until the gateway sent 504s. A read that hangs
// holds no request past copilotWSLWait, all of them at once included,
// and the sign-in read before is answered meanwhile.
func TestCopilotWSLHangHoldsNoRequest(t *testing.T) {
home := signIn(t)
os.Remove(filepath.Join(home, ".config", "github-copilot", "apps.json"))
t.Setenv("COPILOT_HOME", filepath.Join(home, "no-copilot-here"))
oldSecret, oldDirs, oldWait := copilotCLISecret, CopilotWSLDirs, copilotWSLWait
copilotCLISecret = func(string) string { return "" }
copilotWSLWait = 200 * time.Millisecond
distro := filepath.Join(t.TempDir(), "home", "jia")
os.MkdirAll(filepath.Join(distro, ".copilot"), 0o700)
os.WriteFile(filepath.Join(distro, ".copilot", "config.json"), []byte(`{
"lastLoggedInUser": {"host": "https://github.com", "login": "jia2"},
"loggedInUsers": [{"host": "https://github.com", "login": "jia2"}],
"copilotTokens": {"https://github.com:jia2": "gho_wsl"}
}`), 0o600)
release := make(chan struct{})
var mu sync.Mutex
hang := false
CopilotWSLDirs = func() []string {
mu.Lock()
h := hang
mu.Unlock()
if h {
<-release
}
return []string{filepath.Join(distro, ".copilot")}
}
copilotWSL.Lock()
copilotWSL.at = time.Time{}
copilotWSL.Unlock()
var once sync.Once
free := func() { once.Do(func() { close(release) }) }
t.Cleanup(func() {
free()
for {
copilotWSL.Lock()
busy := copilotWSL.done != nil
copilotWSL.Unlock()
if !busy {
break
}
time.Sleep(time.Millisecond)
}
copilotCLISecret, CopilotWSLDirs, copilotWSLWait = oldSecret, oldDirs, oldWait
copilotWSL.Lock()
copilotWSL.at = time.Time{}
copilotWSL.Unlock()
})
if app, ok := copilotCLILogin(); !ok || app.User != "jia2" {
t.Fatalf("first read: %+v %v", app, ok)
}
// older than copilotWSLAge, and WSL hangs now
mu.Lock()
hang = true
mu.Unlock()
copilotWSL.Lock()
copilotWSL.at = time.Now().Add(-copilotWSLAge - time.Second)
copilotWSL.Unlock()
bar := copilotWSLWait + 2*time.Second
var wg sync.WaitGroup
start := time.Now()
errs := make(chan string, 13)
for range 13 {
wg.Add(1)
go func() {
defer wg.Done()
if app, ok := copilotCLILogin(); !ok || app.User != "jia2" {
errs <- "the sign-in read before wasn't answered"
}
}()
}
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
select {
case <-done:
case <-time.After(bar):
t.Errorf("13 requests waited on a hung WSL past %v", bar)
free()
<-done
}
if d := time.Since(start); d > bar {
t.Errorf("13 requests at once took %v", d)
}
close(errs)
for e := range errs {
t.Error(e)
break
}
}