Files
magpie/internal/usage/derived_idle.go
T
yetone 80a315a70a gui: a closed or hidden page lets its Sessions and Usage caches go in 30 s
What a visit to the app's page read stayed until each cache's own idle
timer fired: the Sessions stats after 2 minutes, the Requests chunks
trimmed at 2 and forgotten 5 after that, each chunk's derived keys at 3.
On a real history (acctp, requests-v1.bin 71.5 MB) a web page open 70 s
and closed held 123 MB at the close, 108 MB a minute on, 74-76 MB three
to five minutes on, and was back to the tray's 52 MB only at ten.

The page now says it has gone from view (POST /api/page-away, sent from
the visibilitychange listener every window already has, when hidden: a
browser fires it as a tab closes, and the Mac window's orderOut
dispatches it too). 30 s later (pageAwayFor), unless a Sessions or Usage read
was in flight or ended since, the stats, overviews and tags go
(letGoStats, split out of forgetIdleStats), the Requests chunks and each
chunk's derived caches go (usage.ForgetPages: trim(0) + dropDerived,
idle timers stopped) and the pages go back to the system. A second tab
still polling, or a tab looked away from for under 30 s, keeps them. The
beacon writes nothing, so held's provider.Changed passes it by. The panel
sends it as well when it hides; it reads no Sessions or Usage page, so
there is nothing of its own to keep.

Tests: TestPageAwayLetsStatsGo (red with the forget skipped, and red
when a read after the beacon is ignored, both broken by hand) and
TestForgetPagesLetsChunksGoAtOnce.

The core script budget goes up 83 bytes, with the reason in its
comment: the beacon is folded into the existing listener and packed to
its shortest form (335 over as first written, with a pagehide listener
and a panel check).

Measured on mote (pageclose2.sh, the acctp history, a web page open
70 s and closed, footprint-overlay build like the release):
  before (w88): close 123 MB, +60 s 108, +180 s 76, +300 s 74, +600 s 52;
                peak 154
  after  (w89): close 123 MB, +45 s 92, +90 s 90, +180 s 54, +600 s 53;
                peak 149, 3.08 s CPU over 11 min
  final (w90, visibilitychange only): close 122 MB, +45 s 93, +90 s 90,
                +180 s 55, +600 s 52; peak 152

Run: go test ./internal/gui ./internal/usage on mote (ok);
GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... (ok);
16 visibility GUI files + i18n-keys in chromium and webkit: red only in
routing-pin-away (the same subtest red alone at origin/main 4739ec92c,
2026-11-14 17:00:00 +08:00

149 lines
4.1 KiB
Go

package usage
import (
"runtime/debug"
"sync/atomic"
"testing"
"time"
)
// derivedIdle is how long what is kept of each chunk by its serial (its
// message keys, match hints, first time and heat before a cut) stays
// after the last pairing or heatmap that read it. Each is read again from
// its chunk on the next ask. They were kept by turns, and with no turn
// while nobody looked they stayed for the life of the process: ~4 MB of
// message keys alone in a real history's idle heap.
const derivedIdle = 3 * time.Minute
var derivedKept struct {
last atomic.Int64
armed atomic.Bool
off bool
}
func init() { derivedKept.off = testing.Testing() }
// derivedUsed notes a read of the per-chunk caches and arms the idle
// check.
func derivedUsed() {
if derivedKept.off {
return
}
derivedKept.last.Store(time.Now().UnixNano())
if derivedKept.armed.CompareAndSwap(false, true) {
time.AfterFunc(derivedIdle, derivedIdleCheck)
}
}
// derivedIdleCheck lets the per-chunk caches go once nothing has read
// them for derivedIdle, or looks again when that will be.
func derivedIdleCheck() {
if derivedKept.off { // a test's timer, after it ended
derivedKept.armed.Store(false)
return
}
if left := derivedIdle - time.Since(time.Unix(0, derivedKept.last.Load())); left > 0 {
time.AfterFunc(left, derivedIdleCheck)
return
}
at := time.Now().UnixNano()
n := dropDerived()
derivedKept.armed.Store(false)
if derivedKept.last.Load() > at && derivedKept.armed.CompareAndSwap(false, true) {
time.AfterFunc(derivedIdle, derivedIdleCheck) // read again meanwhile
}
if n > 0 {
debug.FreeOSMemory()
}
}
// dropDerived lets go of what is kept of every chunk by its serial and
// says how many were kept.
func dropDerived() int {
n := 0
msgKeys.Lock()
n += len(msgKeys.by)
msgKeys.by = nil
msgKeys.Unlock()
matchHints.Lock()
n += len(matchHints.by)
matchHints.by = nil
matchHints.Unlock()
firsts.Lock()
n += len(firsts.by)
firsts.by = map[uint64]chunkFirst{} // written below an unlock, never nil
firsts.Unlock()
heatBefores.Lock()
n += len(heatBefores.by)
heatBefores.by = nil
heatBefores.Unlock()
n += dropEffortPeriods()
n += dropDigestTurns()
return n
}
// dropDigestTurns lets go of the serials sourceDigest met this turn and
// the one before (577 KB of a real history's idle heap). They only order
// which digests heat-digests.bin keeps first when there are more than it
// holds; what was made is written out before they go.
func dropDigestTurns() int {
sourceDigestsSave()
d := &sourceDigests
d.Lock()
defer d.Unlock()
if len(d.made) != 0 { // made meanwhile: written with them next time
return 0
}
n := len(d.by) + len(d.last)
d.by, d.last = nil, nil
return n
}
// dropEffortPeriods lets go of every period's kept CodexModelEffort answer
// but one being built: each thread's consumption by model, ~7 MB of a real
// history's idle heap after one visit to the Sessions page. The next ask
// builds it again, waiting for it as a first ask does. The effort before
// the last few days (effortOlds, ~2 MB more) goes too when no build is
// under way: it is in effort-v1.json, read back by the next build.
func dropEffortPeriods() int {
n := 0
if codexEffortBuilding.TryLock() {
n += len(effortOlds)
clear(effortOlds)
codexEffortBuilding.Unlock()
}
codexEffort.Lock()
defer codexEffort.Unlock()
for p, e := range codexEffort.periods {
if e.building == nil {
delete(codexEffort.periods, p)
n++
}
}
return n
}
// ForgetPages lets go at once of what the Requests page and its heatmap
// keep for their next ask: the chunks (as requestForget does) and what is
// kept of each by its serial (as derivedIdle does). The app calls it once
// its page has gone away, closed or hidden, so that what a visit read
// goes in seconds, not the 7 minutes the idle timers take; the next visit
// reads the chunks back from the file of them. Says whether anything went.
func ForgetPages() bool {
idx := &requestCache
idx.Lock()
n := len(idx.chunks)
if idx.idle != nil {
idx.idle.Stop()
idx.idle = nil
}
if idx.forget != nil {
idx.forget.Stop()
idx.forget = nil
}
idx.trim(0)
idx.Unlock()
n += dropDerived()
return n > 0
}