diff --git a/internal/cli/signals.go b/internal/cli/signals.go index 2d8620319..b5af80d59 100644 --- a/internal/cli/signals.go +++ b/internal/cli/signals.go @@ -7,10 +7,12 @@ import ( "sync" "sync/atomic" "syscall" + "time" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/sessions" ) // endProbesOnSignal: the probes magpie asks a CLI with lead a session of @@ -43,12 +45,33 @@ func endProbesOnSignal() { if !handled { provider.FlushServed() // a gateway's last answers, noted and not yet written gateway.FlushSticks() // and who answered which conversation + // and the session index, or the next start reads every + // file a scan read since the last save again + savedWithin(sessionsSaved, saveOnSignal) die(s) } } }(onSignal) } +// saveOnSignal bounds how long a signal waits for the session index to be +// written: a long history's takes a second or two, and a signal is asked to +// end magpie now. +var saveOnSignal = 5 * time.Second + +// sessionsSaved is sessions.Saved; a var so tests can hold it. +var sessionsSaved = sessions.Saved + +// savedWithin runs save and waits for it up to d. +func savedWithin(save func(), d time.Duration) { + done := make(chan struct{}) + go func() { save(); close(done) }() + select { + case <-done: + case <-time.After(d): + } +} + // caught are the signals endProbesOnSignal asked for; onSignal is where // they come. var ( diff --git a/internal/cli/signals_test.go b/internal/cli/signals_test.go index 9e1bd94bc..49bdd30a6 100644 --- a/internal/cli/signals_test.go +++ b/internal/cli/signals_test.go @@ -146,3 +146,30 @@ func TestTUIKeepsSignalsWhileLoading(t *testing.T) { t.Fatal(err) } } + +// a signal writes the session index before magpie dies of it: `magpie web` +// or `serve` ended by a service manager or a terminal's Ctrl+C kept none of +// a scan's last minute, so the next start read those files again; an index +// that won't write doesn't hold the signal past saveOnSignal +func TestSignalSavesTheSessionIndex(t *testing.T) { + died := deaths(t, syscall.SIGTERM) + oldSave, oldWait := sessionsSaved, saveOnSignal + t.Cleanup(func() { sessionsSaved, saveOnSignal = oldSave, oldWait }) + saved := make(chan struct{}, 1) + sessionsSaved = func() { saved <- struct{}{} } + endProbesOnSignal() + send(t, syscall.SIGTERM) + diesOf(t, died, syscall.SIGTERM) + select { + case <-saved: + default: + t.Fatal("died without the session index saved") + } + + saveOnSignal = 50 * time.Millisecond + stuck := make(chan struct{}) + t.Cleanup(func() { close(stuck) }) + sessionsSaved = func() { <-stuck } + send(t, syscall.SIGTERM) + diesOf(t, died, syscall.SIGTERM) +} diff --git a/internal/sessions/save_gap_test.go b/internal/sessions/save_gap_test.go index adcbef270..77d6ef3c7 100644 --- a/internal/sessions/save_gap_test.go +++ b/internal/sessions/save_gap_test.go @@ -1,6 +1,8 @@ package sessions import ( + "os" + "path/filepath" "sync/atomic" "testing" "time" @@ -43,3 +45,47 @@ func TestSaveWaitsOutTheGap(t *testing.T) { t.Fatalf("%d writes once Saved, want the two saves in a row folded into one", n) } } + +// A scan's last save is written at once, not saveGap after the save before +// it: a magpie quit or updated within that minute kept none of the scan, +// and each start read 22 GB of rollouts again. A poll's few files still +// wait out the gap. +func TestScanSavedWithoutTheGap(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + var writes atomic.Int32 + old, oldScan := saveGap, scanFiles + saveGap, scanFiles = time.Hour, 8 + saveHook = func() { writes.Add(1) } + t.Cleanup(func() { saved(); saveGap, scanFiles, saveHook = old, oldScan, nil }) + statsAt(0, statsNow) + saved() + gapFromNow := func() { + saving.Lock() + saving.wrote = time.Now() + saving.Unlock() + writes.Store(0) + } + + gapFromNow() + moreSessions(t, claude, 12) + statsAt(0, statsNow) + for end := time.Now().Add(10 * time.Second); writes.Load() == 0; { + if time.Now().After(end) { + t.Fatal("a scan's last save waited out saveGap") + } + time.Sleep(10 * time.Millisecond) + } + + saved() + gapFromNow() + p := filepath.Join(claude, "projects", "-work-many", "33333333-2222-3333-4444-000000000000.jsonl") + if err := os.WriteFile(p, []byte(ccMsg("m0", "2026-09-21T10:00:00.000Z", 200, 20)), 0o644); err != nil { + t.Fatal(err) + } + statsAt(0, statsNow) + time.Sleep(100 * time.Millisecond) // room for a write the gap should hold back + if n := writes.Load(); n != 0 { + t.Fatalf("a poll's save written %d times inside saveGap", n) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 7f048055a..c0a002ce0 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -1114,19 +1114,32 @@ func loadCache() { // parse starts from a clone), so a copy of the map is a snapshot; saves in a // row are folded into the latest, and one is written saveGap after the // last at the soonest. -func saveCache() { +func saveCache() { saveCacheWithin(saveGap) } + +// saveCacheWithin is saveCache written gap after the last save at the +// soonest; saves folded into one wait the shortest gap any of them asked. +func saveCacheWithin(gap time.Duration) { snap := save{cacheFile{Version: cacheVersion, Zone: zone(), Parsers: parseVersions, Files: savable()}, CachePath()} saving.Lock() defer saving.Unlock() + if saving.next == nil || gap < saving.gap { + saving.gap = gap + } saving.next = &snap if saving.running { + if gap < saveGap { + select { // a save waiting out a longer gap looks again + case saveNow <- struct{}{}: + default: + } + } return } saving.running = true go func() { for { saving.Lock() - wait := saveGap - time.Since(saving.wrote) + wait := saving.gap - time.Since(saving.wrote) if saving.hurry { wait = 0 } @@ -1135,6 +1148,7 @@ func saveCache() { select { case <-time.After(wait): case <-saveNow: + continue // hurried, or a shorter gap asked: look again } } saving.Lock() @@ -1167,6 +1181,18 @@ func saveCache() { // read again then. Saved does not wait it out. var saveGap = time.Minute +// A refresh that reads scanFiles files or more is a scan (a first start, a +// lost or outdated index), not a poll catching up with a live session. Its +// checkpoints wait scanSaveGap, not saveGap, and its last save waits for +// nothing: under saveGap a scan's later checkpoints and its end waited a +// minute after its first checkpoint, and a magpie quit or updated within +// it kept a few hundred of 17,000 files, so each start read 22 GB of +// rollouts again (15 to 28 s before Sessions showed, 70 to 94 s of CPU). +var ( + scanFiles = 32 + scanSaveGap = 15 * time.Second +) + // saveNow wakes a save waiting out saveGap once saving.hurry is set. var saveNow = make(chan struct{}, 1) @@ -1175,8 +1201,9 @@ var saving struct { *sync.Cond running bool next *save - wrote time.Time // when the last save was written - hurry bool // Saved is waiting: no save waits out saveGap + gap time.Duration // the shortest gap the saves folded into next asked + wrote time.Time // when the last save was written + hurry bool // Saved is waiting: no save waits out saveGap } type save struct { @@ -1370,6 +1397,10 @@ func refresh(want, all []file) { // end: a first read of a long history on a slow disk runs for minutes, // and a magpie quit before the end (its CPU full, #1665) kept nothing // of it, so the next start read it all again. + checkpointGap, endGap := saveGap, saveGap + if len(jobs) >= scanFiles { + checkpointGap, endGap = min(scanSaveGap, saveGap), 0 + } tick := time.NewTicker(checkpointEvery) defer tick.Stop() unsaved := false @@ -1387,7 +1418,7 @@ func refresh(want, all []file) { } mu.Lock() if generation == cacheGeneration { - saveCache() + saveCacheWithin(checkpointGap) } mu.Unlock() unsaved = false @@ -1396,7 +1427,7 @@ func refresh(want, all []file) { mu.Lock() progress.finish() if generation == cacheGeneration { - saveCache() + saveCacheWithin(endGap) } }