An agent module loads and connects under limit, whose timer interrupts the module once its second has passed. When the timer fired just as the call returned, Stop didn't wait for its func, which could still be on its way to Interrupt when limit read fired. The interrupt then landed on an idle runtime, and moejs keeps one that lands while nothing runs for the next call, whatever it is (its Interrupt doc). That call's own limit never fired, so nothing cleared it: the agent's every connect after failed with "connect: interrupted: took too long" until magpie loaded the module again. A module that takes about its second, on a busy machine, is the case. limit now waits for the timer's func when Stop says it has begun, then clears the interrupt it gave. A call the timer ran out on reads took too long when it failed, as before, and keeps what it returned when it finished; before, which of the two it got depended on the same race. afterFunc stands in for time.AfterFunc, so a test can hold the timer's func. internal/middleware's timer func can run late the same way; there it stops only the next call, not every one after: #3742. What was run (tree 0199ae4d, on origin/main68ee4117, go1.26.8, linux/amd64): - TestLimitRunsOutAsTheCallEnds, new: in a synctest bubble the timer's func is held as the call returns. limit hasn't returned while it is held; once it is let go, a call that finished keeps its nil, one that failed reads took too long, and the connect after answers at once. - TestLimitStopsAModuleStillRunning, new, green with main's limit too: limit's everyday case. A connect that never ends, at once or after an await, reads "connect: took too long" and the three connects after it answer; a load that never ends reads took too long. - Each 50 of 50 ok, and -race -count=40 -cpu 1,2 ok with no race. - Broken by hand, each red with its own message: - main's limit, through afterFunc: both cases, limit returning while the func was held and the connect after failing "connect: interrupted: took too long", and the failed call returning the module's own error; - no wait for the timer's func: both, returning while it was held, and the connect after; - the interrupt cleared before the wait: both, the connect after; - the interrupt also cleared as each call starts, with no wait: both, returning while the func was held; - no clear: both tests, every connect after; - the timer never stopped, so every call waits for its func: both cases, the connect after taking its whole second; - a call the timer ran out on always reading took too long: the one that finished; - one that failed keeping its own error: the one that failed, and TestLimitStopsAModuleStillRunning's three cases, with the runtime's "interrupted: took too long". - The issue's case, with a pause put into the timer's func before it interrupts, a connect that busy-waits 100ms and connectLimit at 50ms for that one call: on68ee4117the three connects after all failed "connect: interrupted: took too long"; here that call returned once the pause ended, and all three answered. - gofmt -l lists nothing; 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 the tag on linux: exit 1, pkg-config finding no fontconfig, libsoup-3.0 or gio-unix-2.0 (no GTK or WebKitGTK headers on this box). - Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout 45m, log kept): 66 ok, internal/agentplug among them, and 7 red, none in what this changes: - agent TestCodexDriftReached and TestCodexBehindReverseProxy: #3398; TestInstalledVersion, TestCursorFolderFromTheEditorIsNotTheCLI, TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir and TestZedAppPath: #3141; TestReasonixCLIRequiresSupportedNativeVersion and TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git, #3641. - davsync TestSyncTeraCloudStillSeesOtherWrites: #3420. - edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram: this box's umask 077, #3640. - gateway TestPluginToldWhereTheAgentWorks: this box's /tmp/.git, #3675. - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie: this box's millions of open fds, #3649. - provider: "fatal error: close of synctest channel from outside bubble", #3632; the package's tests after it didn't run. Not tried: Windows or macOS, and a real plugin's module that takes about its second; the timing is injected. Reviewed on macOS arm64, go1.26.8, rebased on430e3050d: -race -count=40 -cpu 1,2 on internal/agentplug ok (and -count=20 again after the rebase). Broken by hand: main's limit through afterFunc turned both new cases red with the messages above; dropping ClearInterrupt turned all four red. internal/plugin, internal/library and internal/cli ok; gofmt clean; vet ok for linux nogui, windows, darwin. Not run: internal/agent (slow, no change there beyond the import).
130 lines
4.7 KiB
Go
130 lines
4.7 KiB
Go
package agentplug
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"testing/synctest"
|
|
"time"
|
|
)
|
|
|
|
// A call can end just as its limit runs out: the timer's func has begun
|
|
// and not yet given its interrupt. Stop doesn't wait for it, and moejs
|
|
// keeps an interrupt that lands while nothing runs for the next call,
|
|
// whatever it is. That call's limit never fired, so nothing cleared it,
|
|
// and the module's every connect after failed with "interrupted: took too
|
|
// long" until magpie loaded it again (#3727). Here the timer's func is
|
|
// held at that moment, and limit waits for it: it hasn't returned before
|
|
// the func is let go. A call that finished keeps what it returned, one that
|
|
// failed reads took too long, and the next connect answers in time.
|
|
func TestLimitRunsOutAsTheCallEnds(t *testing.T) {
|
|
dir := t.TempDir()
|
|
file := filepath.Join(dir, "agent.js")
|
|
if err := os.WriteFile(file, []byte(`export const agent = { id: "late", config: "~/.late.json", model: "model" };
|
|
export function connect() { return { model: "m" }; }
|
|
`), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, c := range []struct {
|
|
name string
|
|
ends error // what the call returns as its limit runs out
|
|
want error
|
|
}{
|
|
{"finished", nil, nil},
|
|
{"failed", errors.New("the module threw"), errTimeout},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
synctest.Test(t, func(t *testing.T) {
|
|
// a runtime of the case's own, loaded under the bubble's time
|
|
a, err := Compile(dir, file)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
begun, release := make(chan struct{}), make(chan struct{})
|
|
afterFunc = func(d time.Duration, f func()) *time.Timer {
|
|
return time.AfterFunc(d, func() {
|
|
close(begun)
|
|
<-release
|
|
f()
|
|
})
|
|
}
|
|
t.Cleanup(func() { afterFunc = time.AfterFunc })
|
|
got := make(chan error, 1)
|
|
go func() {
|
|
got <- a.limit(time.Second, func() error {
|
|
<-begun // the second has passed, and the timer's func began
|
|
return c.ends
|
|
})
|
|
}()
|
|
<-begun
|
|
synctest.Wait() // limit waits for the func
|
|
if len(got) != 0 {
|
|
t.Error("limit returned while its timer's func hadn't given its interrupt")
|
|
}
|
|
close(release)
|
|
if err := <-got; !errors.Is(err, c.want) {
|
|
t.Errorf("limit returned %v, want %v", err, c.want)
|
|
}
|
|
synctest.Wait() // the timer's func has given its interrupt
|
|
afterFunc = time.AfterFunc
|
|
start := time.Now()
|
|
keys, err := a.Connect(map[string]any{})
|
|
if err != nil || keys["model"] != "m" {
|
|
t.Fatalf("the connect after: %v, %v; want the module's model", keys, err)
|
|
}
|
|
if d := time.Since(start); d != 0 {
|
|
t.Errorf("the connect after, in time, took %v of its limit", d)
|
|
}
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
// A module still running when its time is up, limit's everyday case: a
|
|
// connect that never ends, at once or after an await, reads took too long,
|
|
// and the connects after it answer; a load that never ends reads took too
|
|
// long. Nothing here ends but by the interrupt, so the 50ms limits bound how
|
|
// long the test takes, not whether it passes.
|
|
func TestLimitStopsAModuleStillRunning(t *testing.T) {
|
|
for _, c := range []struct{ name, src string }{
|
|
{"loop", `export function connect() { if (++n === 1) for (;;) {} return { model: "m" }; }`},
|
|
{"after an await", `export async function connect() { if (++n === 1) { await null; for (;;) {} } return { model: "m" }; }`},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
file := filepath.Join(dir, "agent.js")
|
|
if err := os.WriteFile(file, []byte("export const agent = { id: \"slow\", config: \"~/.slow.json\", model: \"model\" };\nlet n = 0;\n"+c.src+"\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
a, err := Compile(dir, file)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
connectLimit = 50 * time.Millisecond
|
|
t.Cleanup(func() { connectLimit = time.Second })
|
|
if _, err := a.Connect(map[string]any{}); err == nil || err.Error() != "connect: took too long" {
|
|
t.Errorf("the connect that runs out: %v, want connect: took too long", err)
|
|
}
|
|
connectLimit = time.Second
|
|
for i := 1; i <= 3; i++ {
|
|
if keys, err := a.Connect(map[string]any{}); err != nil || keys["model"] != "m" {
|
|
t.Errorf("connect %d after it: %v, %v; want the module's model", i, keys, err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
t.Run("load", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
file := filepath.Join(dir, "agent.js")
|
|
if err := os.WriteFile(file, []byte("for (;;) {}\nexport const agent = { id: \"slow\", config: \"~/.slow.json\", model: \"model\" };\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
loadLimit = 50 * time.Millisecond
|
|
t.Cleanup(func() { loadLimit = time.Second })
|
|
if _, err := Compile(dir, file); err == nil || err.Error() != "took too long" {
|
|
t.Errorf("the load that runs out: %v, want took too long", err)
|
|
}
|
|
})
|
|
}
|