Files
magpie/internal/filememo/filememo_test.go
T
JoeyWu-tech 4842f69be5 filememo: a write in a synctest bubble no longer crashes the next test (#3632)
091153bf (#3185) has Forget close the channel Written gives and make the
next one, and de49433f's wake, for another process's write that Watch
sees, does the same. A test that saves inside a synctest bubble writes
through Forget too, and a channel made in a bubble is that bubble's:
the next write from outside it, in another bubble or in none, closing
it is a fatal error. TestUnreadLoginsWriteErrorsKeepCredentials saves
in a bubble per case, so internal/provider's test binary dies in its
second bubble, on CI's ubuntu and macOS runs at 8299409e and 81a58d2f
and still at c158b043 (run 40265917236; a local -run prints the same
frames):

    fatal error: close of synctest channel from outside bubble

    goroutine 6032 [running, synctest bubble 2]:
    github.com/yetone/magpie/internal/filememo.Forget()
    	internal/filememo/filememo.go:91
    github.com/yetone/magpie/internal/provider.Changed()
    	internal/provider/hold.go:146
    github.com/yetone/magpie/internal/provider.writeLogins(...)
    	internal/provider/logins.go:272

Now Written makes the channel when there is none, and Forget and wake
close it only when one was taken, and make none (endWaits). Nothing
changes for the loops: the channel a loop takes is closed by the next
write, magpie's or another process's, and two loops taking it between
writes share one. A write with nothing taken since the last one had no
wait to end. Only the loops that follow magpie's files take it
(middleware's observer, OTel's session watch, pluginrt.KeepFresh,
awake's loop and the agent's Codex daemon check), so every channel is
made outside a bubble, and a bubble's write may close it.

A loop that took Written inside a bubble would make the channel that
bubble's in the same way, and it would outlive the bubble. None does. A
bubble lives only inside a synctest.Test call, and those are all in the
tests of internal/filememo, provider, plugin, otlp and gateway
(TestConcurrentClassification*, its only ones). With a probe in Forget,
wake and Written over those (a bubble's clock starts at 2000-01-01
00:00 UTC), provider's tests write twice in bubbles, filememo's new
test once in each of its four, and nothing takes Written in one.
provider's, plugin's and filememo's test binaries link none of those
five loops, so none of them can; otlp's and gateway's bubbles run an
exporter's send and classify. Written's comment says so.
internal/gateway's claudeRoom closes and remakes its freed channel the
same way, and no bubble reaches it either: #3690.

What was run (tree 8d629438, on origin/main c158b043, go1.26.8,
linux/amd64):
- TestWrittenAcrossBubbles (new), for Forget and for wake, each in
  bubbles of its own: two waits taken outside, two bubbles that each
  write, then a write outside; both waits are closed by the bubbles'
  writes, and the next one by the write after. Broken by hand, each put
  back after: c158b043's filememo.go under it, "fatal error: close of
  synctest channel from outside bubble"; Forget making the next channel
  again, the same; wake as on c158b043 (close, then make), the same, in
  wake's half; Written making a new channel on each call (two loops no
  longer share one), "Forget in a bubble left a wait taken outside it
  open"; endWaits without its nil check, "panic: close of nil channel".
  With the change ok, and -race -shuffle=on -count=20 ok. TestWritten
  and TestWatchWakesOnOthersWrites, unchanged, ok.
- TestUnreadLoginsWriteErrorsKeepCredentials: on c158b043 the fatal
  error in 4 of 4 runs; with the change it and the tests beside it
  (-run '^(TestUnreadLogins|TestReadableLoginsNotKeptAside)') ok at
  -count=20, and internal/provider whole ok with Bun 1.4.2.
- The probe above, not committed (with -v, since go test hides a passing
  package's output), over the tests with bubbles: Forget in a bubble 4,
  two in provider and two in filememo's new test; wake 2, filememo's;
  Written 0. Over the loops' packages (middleware, pluginrt, awake,
  agent), which have no synctest tests: nothing. In that run
  internal/plugin's TestPiPackage was red at its plugins' start
  ("starting plugins: context deadline exceeded"), #2865, and
  internal/agent with tests of #3141, #3398 and #3641; internal/plugin
  was ok in the suite below.
- gofmt -l clean; GOOS=linux, windows and darwin go vet -tags nogui
  ./..., GOOS=windows go vet ./..., GOOS=linux and darwin go build -tags
  nogui ./... and GOOS=windows go build ./...: exit 0 each. go vet and
  go build ./... without a tag on linux stop at pkg-config here (no
  GTK, WebKitGTK or fontconfig headers on this box, exit 1).
- Full suite, outside graftcp (the proxy this box wraps commands in),
  through systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI,
  -timeout 45m, log kept: 66 ok, provider among them, and 6 red, none
  in what this changes:
  - agent TestInstalledVersion,
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI,
    TestOmpDetectedWithPiDir and TestZedAppPath: #3141;
    TestCodexDriftReached: #3398;
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: #3641.
  - davsync TestSync: #3420.
  - edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram: this
    box's umask 077, #3640.
  - gateway TestPluginToldWhereTheAgentWorks: this box's /tmp/.git,
    #3675.
  - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie:
    #3649.

Not tried: macOS and Windows, vet and build only here (nothing in the
change depends on the OS; CI's macOS job runs every package's tests, its
Windows job compiles them); an idle `magpie serve`'s wakeups as 091153bf
measured them (the loops take and are woken by the channel at the same
points), and Watch with a second process writing:
TestWatchWakesOnOthersWrites writes the files from the test.

Merged from JoeyWu-tech's fix/3632-filememo-synctest (0576b5893, ggbdpq's
pick on the issue), cherry-picked onto origin/main a1222c539. Run on mote
at this tree:
- go test -race -shuffle=on -count=10 ./internal/filememo/: ok.
- TestWrittenAcrossBubbles with a1222c539's filememo.go put back: fatal
  error: close of synctest channel from outside bubble. With the fix: ok.
- go test ./internal/provider/: no fatal; only #3854's three TestFetch*
  reds are left, the same as on main. internal/awake, middleware, otlp,
  pluginrt (the other Written users): ok. internal/agent -run CodexDaemon: ok.
- GOOS=linux and GOOS=windows go vet ./internal/filememo/ ./internal/agent/: ok.
skygunner's c9e34bbd has the same mechanism and wasn't taken.
2026-10-28 06:32:43 +08:00

211 lines
6.0 KiB
Go

package filememo
import (
"fmt"
"os"
"path/filepath"
"testing"
"testing/synctest"
"time"
)
func TestRead(t *testing.T) {
p := filepath.Join(t.TempDir(), "f")
os.WriteFile(p, []byte("a"), 0o600)
n := 0
parse := func(b []byte) (string, error) { n++; return string(b), nil }
for range 3 {
if v, err := Read("t", p, parse); err != nil || v != "a" {
t.Fatal(v, err)
}
}
if n != 1 {
t.Fatalf("parsed %d times", n)
}
os.WriteFile(p, []byte("bb"), 0o600)
os.Chtimes(p, time.Now(), time.Now().Add(time.Second))
if v, _ := Read("t", p, parse); v != "bb" || n != 2 {
t.Fatalf("after a change: %q, parsed %d times", v, n)
}
os.Remove(p)
if _, err := Read("t", p, parse); err == nil {
t.Fatal("a file gone is an error")
}
}
// two writes of one size inside one tick of the file system's clock (Linux
// stamps a file's time from a clock a few milliseconds coarse) leave the
// same time and size: the second is still read, not the first's parse
func TestReadSameSizeSameTick(t *testing.T) {
p := filepath.Join(t.TempDir(), "f")
parse := func(b []byte) (string, error) { return string(b), nil }
for i := range 200 {
a, b := fmt.Sprintf("a%03d,b", i), fmt.Sprintf("b%03d,a", i)
os.WriteFile(p, []byte(a), 0o600)
if v, _ := Read("tick", p, parse); v != a {
t.Fatalf("read %q, want %q", v, a)
}
os.WriteFile(p, []byte(b), 0o600)
if v, _ := Read("tick", p, parse); v != b {
t.Fatalf("read %q after writing %q: the first write's parse", v, b)
}
}
}
// While a request holds what was read, a file found unchanged is not looked
// at again (the GUI's state looked a few thousand times, seconds on a slow
// disk); a write magpie makes (Forget), a second gone by or the release has
// it looked at, and a file just written is always read again.
func TestHold(t *testing.T) {
p := filepath.Join(t.TempDir(), "f")
os.WriteFile(p, []byte("a"), 0o600)
old := time.Now().Add(-time.Minute)
os.Chtimes(p, old, old)
parse := func(b []byte) (string, error) { return string(b), nil }
write := func(s string) {
os.WriteFile(p, []byte(s), 0o600)
at := old.Add(time.Duration(len(s)) * time.Second)
os.Chtimes(p, at, at)
}
release := Hold()
if v, _ := Read("hold", p, parse); v != "a" {
t.Fatal(v)
}
write("bb")
if v, _ := Read("hold", p, parse); v != "a" {
t.Fatalf("looked at again while held: %q", v)
}
Forget()
if v, _ := Read("hold", p, parse); v != "bb" {
t.Fatalf("after a write magpie made: %q", v)
}
write("ccc")
release()
release()
if v, _ := Read("hold", p, parse); v != "ccc" {
t.Fatalf("released: %q", v)
}
if holds != 0 {
t.Fatalf("holds left: %d", holds)
}
// a file written just now is read each time, held or not
defer Hold()()
os.WriteFile(p, []byte("d"), 0o600)
Read("hold", p, parse)
os.WriteFile(p, []byte("e"), 0o600)
if v, _ := Read("hold", p, parse); v != "e" {
t.Fatalf("a file written just now: %q", v)
}
}
// A file not there is, while a request holds what was read, taken as
// still not there as a file found unchanged is: a provider with no list
// fetched was a look at the disk for each of its models, each request. A
// write magpie makes (Forget), another's (Look), or the hold's end has it
// looked at again; unheld, every read looks.
func TestHoldMissing(t *testing.T) {
p := filepath.Join(t.TempDir(), "none")
parse := func(b []byte) (string, error) { return string(b), nil }
looks := func() int {
mu.Lock()
defer mu.Unlock()
return stats
}
release := Hold()
before := looks()
for range 100 {
if _, err := Read("missing", p, parse); !os.IsNotExist(err) {
t.Fatalf("a file not there: %v", err)
}
}
if n := looks() - before; n != 1 {
t.Fatalf("%d looks at a file not there, held", n)
}
os.WriteFile(p, []byte("a"), 0o600)
if _, err := Read("missing", p, parse); !os.IsNotExist(err) {
t.Fatalf("looked at again while held: %v", err)
}
Forget()
if v, err := Read("missing", p, parse); v != "a" || err != nil {
t.Fatalf("after a write magpie made: %q %v", v, err)
}
os.Remove(p)
Read("missing", p, parse)
os.WriteFile(p, []byte("b"), 0o600)
Look(p)
if v, err := Read("missing", p, parse); v != "b" || err != nil {
t.Fatalf("after another's write: %q %v", v, err)
}
os.Remove(p)
Read("missing", p, parse)
release()
os.WriteFile(p, []byte("c"), 0o600)
if v, err := Read("missing", p, parse); v != "c" || err != nil {
t.Fatalf("released: %q %v", v, err)
}
os.Remove(p)
before = looks()
for range 3 {
Read("missing", p, parse)
}
if n := looks() - before; n != 3 {
t.Fatalf("unheld, %d looks for 3 reads", n)
}
}
// Written is closed by the next Forget, and a wait begun after it waits for
// the one after.
func TestWritten(t *testing.T) {
w := Written()
select {
case <-w:
t.Fatal("closed before any write")
default:
}
Forget()
select {
case <-w:
case <-time.After(5 * time.Second):
t.Fatal("not closed by Forget")
}
select {
case <-Written():
t.Fatal("the next wait is closed already")
default:
}
}
// A test that saves inside a synctest bubble writes through Forget too,
// and neither the channel it closes nor the next one may be the bubble's:
// the next write from outside the bubble, another bubble's or none's,
// closing it is a fatal error that took internal/provider's tests down
// (#3632). Another process's write (wake) is held to the same, each in
// bubbles of its own, so neither cleans up after the other. Loops
// waiting outside are still told of a write made in a bubble, two of them
// on the one wait they share.
func TestWrittenAcrossBubbles(t *testing.T) {
for _, write := range []struct {
name string
do func()
}{{"Forget", Forget}, {"wake", wake}} {
w, also := Written(), Written() // two loops waiting
for range 2 {
synctest.Test(t, func(t *testing.T) { write.do() })
}
for _, c := range []<-chan struct{}{w, also} {
select {
case <-c:
default:
t.Fatalf("%s in a bubble left a wait taken outside it open", write.name)
}
}
w = Written()
write.do()
select {
case <-w:
default:
t.Fatalf("not closed by the %s after the bubbles'", write.name)
}
}
}