library: a skill probe's download goes when it is probed again or 15 minutes are up, and one a magpie that quit left behind goes at the next probe (#2321)

ProbeSkills kept each GitHub probe's download, a magpie-skill-* folder in
the temp dir, cached for 15 minutes. An expired one went only at the
*next* probe, so a magpie that quit, or a test that ended, left it there
for good. One go test ./internal/library left 22. This machine's temp dir
had 5477, and with old test homes they filled the disk under a full run
(gateway tests failed "no space left on device").

- keepProbe: each cached probe has a timer that removes its folder when
  probeLife is up. A probe of the same input replaces it and removes the
  old folder at once, outside the lock.
- sweepStaleDownloads, at each probe: a magpie-skill-* in the temp dir over
  an hour old goes. No live one is that old, since a probe is kept 15
  minutes and a fetch takes seconds.
- internal/library's TestMain gives the tests a temp dir of their own
  (TMPDIR, and TMP/TEMP for Windows), ends the cached probes, and fails a
  run that leaves a skill download there. A test binary started again by a
  test keeps its parent's temp dir.

Run (on origin/main 8b89b2e36): go test -count=1 -timeout 60m ./... all ok;
gofmt clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.

Broken by hand, each went red:
- a replaced probe's folder kept (TestProbeDownloadEndsWithIt)
- no removal at expiry (TestProbeDownloadEndsWithIt)
- the sweep ignores age, or the prefix, or doesn't run
  (TestStaleDownloadsSwept)
- TestMain doesn't end the probes: "the tests left 16 skill downloads"

Not tried: the Windows box, though TMP/TEMP are set for it.
This commit is contained in:
yetone
2026-10-15 14:19:00 +08:00
parent 8b89b2e36c
commit 01c41e8ba2
5 changed files with 182 additions and 22 deletions
File diff suppressed because one or more lines are too long
+48 -2
View File
@@ -1,10 +1,56 @@
package library
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/testenv"
)
// The tests run in a home of their own, never the user's real files.
func TestMain(m *testing.M) { testenv.Main(m) }
// The tests run in a home of their own, never the user's real files, with
// a temp dir of their own: what they leave in it is theirs, and a skill's
// download left there fails the run (#2321).
func TestMain(m *testing.M) {
if os.Getenv(testenv.Marker) != "" {
testenv.Main(m) // started again by a test: in its temp dir already
}
tmp, err := os.MkdirTemp("", "magpie-library-test-")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
for _, k := range []string{"TMPDIR", "TMP", "TEMP"} { // TMP, TEMP: Windows'
os.Setenv(k, tmp)
}
code := testenv.Run(m)
forgetProbes()
if left := leftDownloads(tmp); len(left) > 0 && code == 0 {
fmt.Fprintf(os.Stderr, "library: the tests left %d skill downloads in the temp dir: %s\n", len(left), strings.Join(left, ", "))
code = 1
}
os.RemoveAll(tmp)
os.Exit(code)
}
// forgetProbes ends every cached probe, as its expiry would.
func forgetProbes() {
probes.Lock()
m := probes.m
probes.m = map[string]*probeEntry{}
probes.Unlock()
for _, e := range m {
e.timer.Stop()
os.RemoveAll(e.tmp)
}
}
func leftDownloads(dir string) []string {
got, _ := filepath.Glob(filepath.Join(dir, skillTemp+"*"))
for i, p := range got {
got[i] = filepath.Base(p)
}
return got
}
+78
View File
@@ -0,0 +1,78 @@
package library
import (
"os"
"path/filepath"
"testing"
"time"
)
// #2321: a probe's download goes when it is replaced or expires, not only
// at the next probe, which may never come.
func TestProbeDownloadEndsWithIt(t *testing.T) {
t.Cleanup(forgetProbes)
defer func(l time.Duration) { probeLife = l }(probeLife)
probeLife = time.Hour
first, second := t.TempDir(), t.TempDir()
keepProbe("owner/repo", &Probe{}, first)
keepProbe("owner/repo", &Probe{}, second)
if _, err := os.Stat(first); !os.IsNotExist(err) {
t.Fatalf("the replaced probe's download is still there: %v", err)
}
if _, err := os.Stat(second); err != nil {
t.Fatalf("the probe kept lost its download: %v", err)
}
probeLife = 20 * time.Millisecond
third := t.TempDir()
keepProbe("owner/other", &Probe{}, third)
deadline := time.Now().Add(time.Minute)
for {
probes.Lock()
_, cached := probes.m["owner/other"]
probes.Unlock()
_, err := os.Stat(third)
if !cached && os.IsNotExist(err) {
break
}
if time.Now().After(deadline) {
t.Fatalf("an expired probe is kept: cached %v, download %v", cached, err)
}
time.Sleep(10 * time.Millisecond)
}
}
// #2321: a download a magpie that quit left behind goes at the next probe;
// one that may be in use, and what isn't ours, stays.
func TestStaleDownloadsSwept(t *testing.T) {
dir := t.TempDir()
for _, k := range []string{"TMPDIR", "TMP", "TEMP"} {
t.Setenv(k, dir)
}
if os.TempDir() != dir {
t.Fatalf("the temp dir is %s, not %s", os.TempDir(), dir)
}
old := filepath.Join(dir, skillTemp+"1")
fresh := filepath.Join(dir, skillTemp+"2")
other := filepath.Join(dir, "someone-else-1")
for _, d := range []string{old, fresh, other} {
if err := os.MkdirAll(filepath.Join(d, "skills"), 0o755); err != nil {
t.Fatal(err)
}
}
long := time.Now().Add(-2 * time.Hour)
for _, d := range []string{old, other} {
if err := os.Chtimes(d, long, long); err != nil {
t.Fatal(err)
}
}
sweepStaleDownloads()
if _, err := os.Stat(old); !os.IsNotExist(err) {
t.Errorf("a download two hours old is still there: %v", err)
}
for _, d := range []string{fresh, other} {
if _, err := os.Stat(d); err != nil {
t.Errorf("%s was swept: %v", filepath.Base(d), err)
}
}
}
+54 -18
View File
@@ -634,9 +634,57 @@ var probes = struct {
}{m: map[string]*probeEntry{}}
type probeEntry struct {
p *Probe
tmp string
at time.Time
p *Probe
tmp string
timer *time.Timer // removes it when probeLife is up
}
// probeLife is how long a probe's download is kept for an install from it.
var probeLife = 15 * time.Minute
// skillTemp starts the name of a download's folder in the temp dir.
const skillTemp = "magpie-skill-"
// keepProbe caches p's download under input for probeLife, in place of
// one before it; the folder is removed when it is replaced or expires, not
// only at the next probe, which may never come (#2321).
func keepProbe(input string, p *Probe, tmp string) {
e := &probeEntry{p: p, tmp: tmp}
probes.Lock()
old := probes.m[input]
probes.m[input] = e
e.timer = time.AfterFunc(probeLife, func() {
probes.Lock()
if probes.m[input] == e {
delete(probes.m, input)
}
probes.Unlock()
os.RemoveAll(tmp)
})
probes.Unlock()
if old != nil {
old.timer.Stop()
os.RemoveAll(old.tmp)
}
}
// sweepStaleDownloads removes the downloads a magpie that quit left in the
// temp dir (#2321): a folder of ours over an hour old, longer than a probe
// is kept or a fetch takes, so none in use.
func sweepStaleDownloads() {
dir := os.TempDir()
ents, err := os.ReadDir(dir)
if err != nil {
return
}
for _, e := range ents {
if !e.IsDir() || !strings.HasPrefix(e.Name(), skillTemp) {
continue
}
if fi, err := e.Info(); err == nil && time.Since(fi.ModTime()) > time.Hour {
os.RemoveAll(filepath.Join(dir, e.Name()))
}
}
}
// githubSource reads a repository out of what the user typed: owner/repo,
@@ -746,7 +794,7 @@ func fetch(src Source) (string, error) {
case resp.StatusCode != 200:
return "", fmt.Errorf("GitHub answered %s", resp.Status)
}
tmp, err := os.MkdirTemp("", "magpie-skill-")
tmp, err := os.MkdirTemp("", skillTemp)
if err != nil {
return "", err
}
@@ -892,14 +940,7 @@ func ProbeSkills(input string) (*Probe, error) {
if input == "" {
return nil, fmt.Errorf("paste a GitHub link or a folder's path")
}
probes.Lock()
for k, e := range probes.m {
if time.Since(e.at) > 15*time.Minute {
os.RemoveAll(e.tmp)
delete(probes.m, k)
}
}
probes.Unlock()
sweepStaleDownloads()
p := &Probe{Source: input}
if dir := expand(input); filepath.IsAbs(dir) {
@@ -921,12 +962,7 @@ func ProbeSkills(input string) (*Probe, error) {
}
p.Candidates = candidates(tmp, src.Path)
p.Left = tookLeftOut(tmp, src.Path)
probes.Lock()
if old := probes.m[input]; old != nil {
os.RemoveAll(old.tmp)
}
probes.m[input] = &probeEntry{p: p, tmp: tmp, at: time.Now()}
probes.Unlock()
keepProbe(input, p, tmp)
} else {
return nil, fmt.Errorf("that's neither a GitHub repository nor a folder's full path")
}
+1 -1
View File
@@ -148,7 +148,7 @@ func fetchSkillFiles(src Source) (string, error) {
}
files = append(files, file{e.Path, e.SHA, e.Mode == "100755"})
}
tmp, err := os.MkdirTemp("", "magpie-skill-")
tmp, err := os.MkdirTemp("", skillTemp)
if err != nil {
return "", err
}