agent: dsh's parsed entries and patch lists go when idle

Startup's RenameLegacy parses every dsh profile's patch list and entries
(dshNodes and filememo's "dsh list"; ~2 MB of YAML nodes in the t60 idle
heap with real accounts), and KeepDshWired's round reads none of them
while nothing changed, so they were kept for the life of the process for
nobody. Two minutes after the last look they are let go (dsh_idle.go, the
same pattern as usage, sessions and catalog); the drift poll and a round
that writes parse them again.

Run on mote at this head: go test ./internal/agent ok (255s); gofmt
clean; GOOS=windows go vet and GOOS=linux go vet -tags nogui
./internal/agent ok.
Broken by hand: without the dshNodes reset, TestIdleDshParsesLetGo fails
("idle: 1 parsed entries kept"); without DropKind("dsh list") it fails
("the patch list kept while idle").
Not tried: a fresh real-account heap at this head (next acrss run).
This commit is contained in:
yetone
2026-11-11 07:05:16 +08:00
parent d02bb81788
commit 8fa91a8520
3 changed files with 102 additions and 92 deletions
+2
View File
@@ -709,6 +709,7 @@ type dshParsed struct {
// read and parsed every profile's list again on each ask, a third of what
// forty asks allocated with real accounts.
func dshLook(path string) ([]string, []dshItem, error) {
dshUsed()
d, err := filememo.Read("dsh list", path, func(b []byte) (dshParsed, error) {
head, items, err := dshParse(path, string(edit.TrimBOM(b)))
return dshParsed{head, items}, err
@@ -779,6 +780,7 @@ func dshNodeShared(it dshItem) (*yaml.Node, error) {
// keyed by a hash of the lines, checked against a copy of them, so a
// look that finds the entry allocates nothing: joining the lines into a
// key each time was most of what the drift poll's dsh check still made
dshUsed()
key := dshLinesHash(it.lines)
dshNodes.Lock()
n, ok := dshNodes.find(key, it.lines)
+63
View File
@@ -0,0 +1,63 @@
package agent
import (
"runtime/debug"
satomic "sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/filememo"
)
// dshIdle is how long the parsed dsh entries and patch lists stay in
// memory after the last look at them. Startup's RenameLegacy filled them
// (~2 MB of YAML nodes with real accounts) and a round that finds nothing
// changed reads none, so they were kept for the life of the process for
// nobody. The window's drift poll and a round that writes parse them again.
const dshIdle = 2 * time.Minute
var dshKept struct {
last satomic.Int64
armed satomic.Bool
off bool
}
func init() { dshKept.off = testing.Testing() }
// dshAfter is time.AfterFunc, which a test holds so no check it arms runs
// after it.
var dshAfter = func(d time.Duration, f func()) { time.AfterFunc(d, f) }
// dshUsed notes a look at the parsed entries and arms the idle check.
func dshUsed() {
if dshKept.off {
return
}
dshKept.last.Store(time.Now().UnixNano())
if dshKept.armed.CompareAndSwap(false, true) {
dshAfter(dshIdle, dshIdleCheck)
}
}
func dshIdleCheck() {
if left := dshIdle - time.Since(time.Unix(0, dshKept.last.Load())); left > 0 {
dshAfter(left, dshIdleCheck)
return
}
at := time.Now().UnixNano()
dropDshParses()
dshKept.armed.Store(false)
if dshKept.last.Load() > at && dshKept.armed.CompareAndSwap(false, true) {
dshAfter(dshIdle, dshIdleCheck) // looked at again meanwhile
}
debug.FreeOSMemory()
}
// dropDshParses lets go of every parsed entry and patch list: the next
// look parses the file again.
func dropDshParses() {
dshNodes.Lock()
dshNodes.m, dshNodes.size = nil, 0
dshNodes.Unlock()
filememo.DropKind("dsh list")
}
+37 -92
View File
@@ -4,106 +4,51 @@ import (
"os"
"path/filepath"
"testing"
"gopkg.in/yaml.v3"
"time"
)
// dshRouteIdle is streamIdleTimeoutMs of each of magpie's routes in a
// llm-pi-ai providers mapping at path (a patch list's entry, or
// settings.yaml's section), 0 for a route without one.
func dshRouteIdle(t *testing.T, path string, list bool) map[string]int {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
// Once nothing has looked at the parsed dsh entries and patch lists for
// dshIdle they are let go, and the next look parses them again with the
// same answer; looked at just now, they stay.
func TestIdleDshParsesLetGo(t *testing.T) {
path := filepath.Join(t.TempDir(), "pi.patch.yml")
text := "- id: " + dshPiRow + "\n name: pi\n config:\n model: m1\n"
if err := os.WriteFile(path, []byte(text), 0o600); err != nil {
t.Fatal(err)
}
type route struct {
Idle int `yaml:"streamIdleTimeoutMs"`
look := func() string {
_, items, err := dshLook(path)
if err != nil || len(items) != 1 {
t.Fatalf("look: %d items, %v", len(items), err)
}
return dshConfig(items[0])["model"]
}
var providers map[string]route
if list {
var items []struct {
ID string `yaml:"id"`
Config struct {
Providers map[string]route `yaml:"providers"`
} `yaml:"config"`
}
if err := yaml.Unmarshal(b, &items); err != nil {
t.Fatalf("%v:\n%s", err, b)
}
for _, it := range items {
if it.ID == dshPiRow {
providers = it.Config.Providers
}
}
} else {
var doc map[string]struct {
Providers map[string]route `yaml:"providers"`
}
if err := yaml.Unmarshal(b, &doc); err != nil {
t.Fatalf("%v:\n%s", err, b)
}
providers = doc[dshPiRow].Providers
size := func() int { dshNodes.Lock(); defer dshNodes.Unlock(); return dshNodes.size }
if got := look(); got != "m1" || size() == 0 {
t.Fatalf("before: model %q, %d entries parsed", got, size())
}
out := map[string]int{}
for k, r := range providers {
if isDshRoute(k) {
out[k] = r.Idle
}
}
if len(out) == 0 {
t.Fatalf("no route of magpie's in %s:\n%s", path, b)
}
return out
}
_, before, _ := dshLook(path)
var armed int
dshAfter = func(time.Duration, func()) { armed++ }
t.Cleanup(func() { dshAfter = func(d time.Duration, f func()) { time.AfterFunc(d, f) } })
// tim on Discord: a first "who are you" to Gemini through the
// magpie-gemini-web plugin took minutes in dsh and ended in 499.
// llm-pi-ai gives a turn up after 5 minutes with no pi-ai event, and the
// gateway's keepalive comments aren't events: a turn queued behind dsh's
// own title request on a plugin serving one request at a time was cut
// while the gateway (10 minutes for headers) and the plugin still waited.
// magpie's routes, in every profile and in deepseek-acp's settings.yaml,
// now wait as long as the gateway does.
func TestDshRoutesWaitAsLongAsTheGateway(t *testing.T) {
home, dir, web := dshRouteHome(t)
os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"), 0o644)
a := dsh(home)
if err := a.Pick("model", "magpie/deepseek/pro"); err != nil {
t.Fatal(err)
dshKept.last.Store(time.Now().UnixNano())
dshKept.armed.Store(true)
dshIdleCheck() // looked at just now: kept, looked at again when due
if size() == 0 || armed != 1 {
t.Fatalf("looked at just now: %d parsed entries, %d checks armed; want kept and one", size(), armed)
}
for _, f := range []struct {
path string
list bool
}{{web, true}, {filepath.Join(dir, "settings.yaml"), false}} {
for k, ms := range dshRouteIdle(t, f.path, f.list) {
if ms != dshIdleWait {
t.Fatalf("%s: route %s waits %dms for the next event, want %d", f.path, k, ms, dshIdleWait)
}
}
}
if dshIdleWait != 10*60*1000 {
t.Fatalf("dshIdleWait %d is not the gateway's 10 minutes for a reply's headers", dshIdleWait)
}
}
// A wait set on magpie's route in dsh (or by hand), shorter or longer, is
// the user's: a sync keeps it.
func TestDshRouteKeepsTheUsersIdleWait(t *testing.T) {
home, dir, web := dshRouteHome(t)
dshKeyFixture(dir)
os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"+
"- id: llm-pi-ai\n name: \"@deepseek-ai/dsh-llm-pi-ai\"\n config:\n providers:\n"+
" magpie:\n displayName: Magpie\n apiKeyEnv: "+dshKeyRef+"\n api: openai-completions\n baseURL: "+gatewayV1()+"\n streamIdleTimeoutMs: 120000\n models:\n - id: deepseek/pro\n"+
"- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/pro\n"), 0o644)
a := dsh(home)
for i := 0; i < 2; i++ {
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if got := dshRouteIdle(t, web, true)[dshRoute]; got != 120000 {
b, _ := os.ReadFile(web)
t.Fatalf("sync %d: the user's 120000 became %d:\n%s", i+1, got, b)
}
dshKept.last.Store(time.Now().Add(-2 * dshIdle).UnixNano())
dshIdleCheck()
if n := size(); n != 0 || dshKept.armed.Load() {
t.Fatalf("idle: %d parsed entries kept, armed %v", n, dshKept.armed.Load())
}
_, after, _ := dshLook(path)
if &after[0] == &before[0] {
t.Error("the patch list kept while idle: the look after gave the same parse")
}
if got := look(); got != "m1" {
t.Errorf("after: model %q, want m1", got)
}
}