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).
This commit is contained in:
yetone
2026-10-26 10:27:01 +08:00
parent 05ea29ac84
commit 466cafa0cf
9 changed files with 80 additions and 25 deletions
+2 -3
View File
@@ -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 {
+2 -1
View File
@@ -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):
}
}
}
+3 -3
View File
@@ -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):
}
}
}
+21
View File
@@ -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)
}
+39
View File
@@ -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")
}
}
+2 -3
View File
@@ -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()
+4 -11
View File
@@ -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)
+2 -3
View File
@@ -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:
}
}
+5 -1
View File
@@ -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)
}
}