From 466cafa0cf681de30ce4cc68616db55f5de10cd9 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 26 Oct 2026 10:27:01 +0800 Subject: [PATCH] idle: the loops that look every few seconds wake together on the clock's beat (#3185) An idle magpie serve still woke ~6 times a second with nothing to do. Its loops each kept a ticker of their own, started at their own instant: awake.Keep (5s), the plugin config's KeepFresh (5s), the middleware observer (5s), OTel's session watch (5s idle), the Codex daemon check (15s), dsh's wiring (30s), the model lists' look (1m). Every one woke the process apart, a few threads each time. internal/beat's Next(every) fires at the next multiple of every on the clock, so the 5s loops come due at one instant, the 15s and 30s ones on every third and sixth of it, and the runtime runs timers due together in one wakeup. Each loop now waits on beat.Next instead of its ticker. No channel is shared between callers (a synctest bubble's channel reached from another crashes the process, #3632). Run at this head (05ea29ac8 + this): - Sandbox HOME serve, idle, 90s warm-up then 120s of proc_pid_rusage (pkg_idle_wkups + interrupt_wkups), old (origin/main 19253f67b) and new taking turns: old 6.1, 5.3, 6.2 wakeups/s; new 2.7, 2.6 (an earlier shared-timer form of beat), 3.0 (this one). CPU 0.20-0.36 ms/s old, 0.11-0.22 new. - TestIntervalsMeet (5s/15s/30s/1m beats from 09:00:03.2 and on a beat), TestNextFires; go test ./internal/beat ./internal/awake ./internal/middleware ./internal/otlp -count=3, ./internal/pluginrt, ./internal/agent -run 'Dsh|CodexDaemon', ./internal/provider -skip TestUnreadLoginsWriteErrorsKeepCredentials (#3632): ok. ./internal/pluginrt -count=3 fails TestKeepFreshFollowsPluginsYml ("two plugins fresh-test") on origin/main too; -count=1 is ok. - gofmt; go vet darwin, GOOS=linux and GOOS=windows -tags nogui. Not tried: a GUI build's wakeups (the tray process has AppKit's own). --- internal/agent/codex_daemon.go | 5 ++--- internal/agent/dsh.go | 3 ++- internal/awake/awake.go | 6 +++--- internal/beat/beat.go | 21 ++++++++++++++++++ internal/beat/beat_test.go | 39 ++++++++++++++++++++++++++++++++++ internal/middleware/points.go | 5 ++--- internal/otlp/otel_sessions.go | 15 ++++--------- internal/pluginrt/config.go | 5 ++--- internal/provider/autolist.go | 6 +++++- 9 files changed, 80 insertions(+), 25 deletions(-) create mode 100644 internal/beat/beat.go create mode 100644 internal/beat/beat_test.go diff --git a/internal/agent/codex_daemon.go b/internal/agent/codex_daemon.go index 75bcdff18..43cd8cff5 100644 --- a/internal/agent/codex_daemon.go +++ b/internal/agent/codex_daemon.go @@ -8,6 +8,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/beat" "github.com/yetone/magpie/internal/provider" ) @@ -84,13 +85,11 @@ func KeepCodexDaemonCurrent(ctx context.Context) { return } path := filepath.Join(here(home).codexHome(), "config.toml") - t := time.NewTicker(codexDaemonEvery) - defer t.Stop() for { select { case <-ctx.Done(): return - case <-t.C: + case <-beat.Next(codexDaemonEvery): } if _, err := os.Stat(path); err == nil { if c := codexDaemonCheck(path); c.Restarted { diff --git a/internal/agent/dsh.go b/internal/agent/dsh.go index b81e5e639..538dc2097 100644 --- a/internal/agent/dsh.go +++ b/internal/agent/dsh.go @@ -43,6 +43,7 @@ import ( "gopkg.in/yaml.v3" "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/beat" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/gateway" @@ -1848,7 +1849,7 @@ func keepDshWired(ctx context.Context, every time.Duration) { select { case <-ctx.Done(): return - case <-time.After(every): + case <-beat.Next(every): } } } diff --git a/internal/awake/awake.go b/internal/awake/awake.go index 8e135fbc9..fd8ef80e9 100644 --- a/internal/awake/awake.go +++ b/internal/awake/awake.go @@ -21,6 +21,8 @@ import ( "context" "log" "time" + + "github.com/yetone/magpie/internal/beat" ) // Grace is how long after the last request ended sleep is still held off. @@ -68,8 +70,6 @@ func Keep(ctx context.Context, level func() Level, state func() State) { } defer let() failed := false - t := time.NewTicker(tick) - defer t.Stop() for { if l := level(); l != Off && want(state(), time.Now()) { if release != nil && held != l { @@ -98,7 +98,7 @@ func Keep(ctx context.Context, level func() Level, state func() State) { select { case <-ctx.Done(): return - case <-t.C: + case <-beat.Next(tick): } } } diff --git a/internal/beat/beat.go b/internal/beat/beat.go new file mode 100644 index 000000000..e1263a932 --- /dev/null +++ b/internal/beat/beat.go @@ -0,0 +1,21 @@ +// Package beat wakes the loops that look at something every so often at +// one time: each waits for the next multiple of its interval on the clock, +// so a 5s loop, a 15s one and a 30s one wake together. An idle magpie woke +// apart for each of them, a few threads every time (#3185). Timers due at +// one instant are run by one wakeup, so the loops need no timer in common. +package beat + +import "time" + +// Next fires at the next multiple of every on the clock, after now. +func Next(every time.Duration) <-chan time.Time { + if every <= 0 { + every = time.Millisecond + } + return time.After(time.Until(after(time.Now(), every))) +} + +// after is the first multiple of every on the clock after now. +func after(now time.Time, every time.Duration) time.Time { + return now.Truncate(every).Add(every) +} diff --git a/internal/beat/beat_test.go b/internal/beat/beat_test.go new file mode 100644 index 000000000..a1a0d5398 --- /dev/null +++ b/internal/beat/beat_test.go @@ -0,0 +1,39 @@ +package beat + +import ( + "testing" + "time" +) + +// Loops whose intervals are multiples of one another wake at one time: a +// 5s loop's every third beat is a 15s loop's, and its every sixth a 30s +// loop's. +func TestIntervalsMeet(t *testing.T) { + now := time.Date(2026, 10, 26, 9, 0, 3, 200e6, time.UTC) + for _, c := range []struct { + every time.Duration + want time.Time + }{ + {5 * time.Second, time.Date(2026, 10, 26, 9, 0, 5, 0, time.UTC)}, + {15 * time.Second, time.Date(2026, 10, 26, 9, 0, 15, 0, time.UTC)}, + {30 * time.Second, time.Date(2026, 10, 26, 9, 0, 30, 0, time.UTC)}, + {time.Minute, time.Date(2026, 10, 26, 9, 1, 0, 0, time.UTC)}, + } { + if got := after(now, c.every); !got.Equal(c.want) { + t.Errorf("after(%s, %s) = %s, want %s", now.Format(time.TimeOnly), c.every, got.Format(time.TimeOnly), c.want.Format(time.TimeOnly)) + } + } + // on a beat, the next is the one after it + if got := after(time.Date(2026, 10, 26, 9, 0, 5, 0, time.UTC), 5*time.Second); !got.Equal(time.Date(2026, 10, 26, 9, 0, 10, 0, time.UTC)) { + t.Errorf("the beat after one on 9:00:05 is %s", got.Format(time.TimeOnly)) + } +} + +// A beat comes: a 10ms one well within 10s. +func TestNextFires(t *testing.T) { + select { + case <-Next(10 * time.Millisecond): + case <-time.After(10 * time.Second): + t.Fatal("a 10ms beat didn't come in 10s") + } +} diff --git a/internal/middleware/points.go b/internal/middleware/points.go index 9d781fce4..f32edcdc2 100644 --- a/internal/middleware/points.go +++ b/internal/middleware/points.go @@ -35,6 +35,7 @@ import ( "github.com/Calcium-Ion/moejs" + "github.com/yetone/magpie/internal/beat" "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/routes" @@ -413,14 +414,12 @@ func (o *observer) Serve() (stop func()) { // a plugin turned on here is seen once saved (Written); every // OthersEvery only catches one the CLI or a second magpie turned on // (#3185: a 1s tick woke an idle magpie every second) - t := time.NewTicker(filememo.OthersEvery) - defer t.Stop() for { select { case <-done: return case <-written: - case <-t.C: + case <-beat.Next(filememo.OthersEvery): } written = filememo.Written() o.refresh() diff --git a/internal/otlp/otel_sessions.go b/internal/otlp/otel_sessions.go index 6113ba2a0..17de70919 100644 --- a/internal/otlp/otel_sessions.go +++ b/internal/otlp/otel_sessions.go @@ -5,6 +5,7 @@ import ( "reflect" "time" + "github.com/yetone/magpie/internal/beat" "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/redact" "github.com/yetone/magpie/internal/sessions" @@ -110,8 +111,6 @@ func (e *otelExporter) offerSession(s sessions.TraceSpan, config settings.OTel) } func (e *otelExporter) watchSessions(ctx context.Context, started time.Time, every time.Duration) { - ticker := time.NewTicker(every) - defer ticker.Stop() var reader *sessions.TraceReader var prior settings.OTel written := filememo.Written() // before each look, so a save during it isn't missed @@ -128,7 +127,7 @@ func (e *otelExporter) watchSessions(ctx context.Context, started time.Time, eve select { case <-ctx.Done(): return - case <-ticker.C: + case <-beat.Next(wait): case <-written: } written = filememo.Written() @@ -136,16 +135,10 @@ func (e *otelExporter) watchSessions(ctx context.Context, started time.Time, eve if err != nil || !config.Enabled || !config.Sessions { reader = nil e.sessions.Store(nil) - if wait != filememo.OthersEvery { - wait = filememo.OthersEvery - ticker.Reset(wait) - } + wait = filememo.OthersEvery continue } - if wait != every { - wait = every - ticker.Reset(wait) - } + wait = every if reader == nil || !reflect.DeepEqual(config, prior) { reader = sessions.NewTraceReader(time.Now()) reader.SetSessionIndex(&e.identities) diff --git a/internal/pluginrt/config.go b/internal/pluginrt/config.go index 291a4cd6f..7e863eea3 100644 --- a/internal/pluginrt/config.go +++ b/internal/pluginrt/config.go @@ -16,6 +16,7 @@ import ( "gopkg.in/yaml.v3" "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/beat" "github.com/yetone/magpie/internal/filelock" "github.com/yetone/magpie/internal/filememo" ) @@ -373,8 +374,6 @@ func KeepFresh(ctx context.Context, every time.Duration, also ...string) { return b.String() } last := "" - tick := time.NewTicker(every) - defer tick.Stop() for { // taken before the look, so a write made during it isn't missed written := filememo.Written() @@ -389,7 +388,7 @@ func KeepFresh(ctx context.Context, every time.Duration, also ...string) { select { case <-ctx.Done(): return - case <-tick.C: + case <-beat.Next(every): case <-written: } } diff --git a/internal/provider/autolist.go b/internal/provider/autolist.go index 503506a88..2a070f68b 100644 --- a/internal/provider/autolist.go +++ b/internal/provider/autolist.go @@ -32,6 +32,8 @@ import ( "strings" "sync" "time" + + "github.com/yetone/magpie/internal/beat" ) // MinRefreshEvery is the shortest RefreshEvery: a vendor's list changes @@ -268,14 +270,16 @@ var listsEvery = time.Minute func KeepListsFresh(ctx context.Context) { t := time.NewTimer(30 * time.Second) defer t.Stop() + var wait <-chan time.Time for { select { case <-ctx.Done(): return case <-t.C: + case <-wait: } refreshDueLists(ctx, time.Now()) - t.Reset(listsEvery) + wait = beat.Next(listsEvery) } }