Files
magpie/internal/sessions/revision_cache.go
T
yetone 3b3bc359da sessions: a long Codex session being written is read on from where it was, not from its first line
yetone/magpie-releases#24 (LeiCheng42, v0.1.1280): a 30s profile while
Codex ran shows magpie at about a core, ~24% of it in
usage.prefetchSources -> sessions.ReadCallSource -> readCalls -> scanAt.
The tray's usage loop (watchTrayUsage -> usage.QueryPage(Today)), the
usage API and the Sessions page read every source whose size or mtime
changed, and an active Codex rollout changes each turn. A Codex
continuation's index weighs about six entries a call, so a session past
~1,365 calls was over the shared 8192-entry revision budget: its window
was dropped, and every append parsed the whole rollout again from offset
0, for the Requests reader and the summary (List) alike.

Now up to two (revisionActiveFiles) recently written Codex sessions keep
their window past the shared budget, each up to 16x it (131,072
entries), and only while the file changed in the last revisionIdle
(5 min). The full parse built the same index on every append anyway, so
this costs no more at its peak; an idle session still loses it.

Measured (Apple M4 Pro, BenchmarkLongCodexSessionAppend: a 2,000-call,
10.7 MB rollout, one turn appended, then ReadCallSource + List(0)):
  before: 0.87-1.09 s/op
  after:  26-60 ms/op

TestLongCodexSessionAppendReadsOnlyTheAppend (via a scanAt hook) checks
that each of three appends is read from the previous size by both
readers, and that the result DeepEquals a fresh read of the whole file
(calls and summary) after the caches are dropped. On the old code it
fails: "append 0: read from 0, not where the last read ended
(10691427)". TestRevisionEntryBudget covers the two-window cap and the
idle/oversize drops.

Run: go test -tags nogui ./internal/sessions/ ok;
go test -tags nogui -timeout 45m ./... with the redact change on top,
under a load average of 440-610 from other sessions' suites: 59 ok, and
agent and gateway (45m timeout), gui (TestSetAnswersWhileDevinAndProvidersHang,
set took 1m30s), edit (TestTOMLBigFileParsesInLinearTime, 1.0s) and
middleware (TestStream, onEvent "took too long") failed on time. edit and
middleware rerun alone: ok. agent and gateway rerun at a lower load: ok; gui rerun: ok. (The first
rerun had TestPluginStreamLargeReplies red on time again, #2551, which
passes alone in 22s, and TestDiffLines at 2.04s against its 2s bound,
filed as #2766.)
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok.
2026-10-18 02:43:03 +08:00

209 lines
6.6 KiB
Go

package sessions
import (
"sort"
"time"
)
// Each cache retains at most eight files and 8192 index entries.
// Recent sources take priority over idle windows, then compete by reparse
// cost (source size). Cold-only historical Claude sources keep no window;
// an already retained idle window can use spare capacity. Codex still expires.
const revisionIdle = 5 * time.Minute
const revisionFiles = 8
const revisionEntries = 8192
// A Codex session being written keeps its window even past the shared
// budget. Its index holds every call (about six entries each), so a session
// over ~1,400 calls lost it, and every append (each turn, each poll that
// read it) parsed the whole rollout again from its first line: a full core
// while Codex ran (yetone/magpie-releases#24). The full parse built the same
// index each time anyway, so keeping it costs no more at its peak. At most
// revisionActiveFiles such windows, each up to revisionActiveEntries, and
// only while the file changed in the last revisionIdle.
const revisionActiveFiles = 2
const revisionActiveEntries = 16 * revisionEntries
// A pause longer than five minutes must not demote a large working session
// behind tiny subagent logs. After an hour, recent work takes priority; idle
// Claude windows are not discarded unless that capacity is actually needed.
const revisionWorking = time.Hour
func workingRevision(mod int64, now time.Time) bool {
return mod >= now.Add(-revisionWorking).UnixNano()
}
func recentRevision(mod int64, weight int, now time.Time) bool {
return weight > 0 && weight <= revisionActiveEntries && mod >= now.Add(-revisionIdle).UnixNano()
}
func (s *codexUsageState) weight() int {
if s == nil {
return 0
}
return len(s.Entries) + len(s.Intervals) + len(s.Responses) + len(s.Models) + len(s.Compactions) + len(s.CounterBases)
}
func (s *claudeUsageState) weight() int {
if s == nil {
return 0
}
n := len(s.Messages)
for _, branches := range s.Messages {
for _, m := range branches {
n += 1 + len(m.Previous) + len(m.Tools) + len(m.Blocks)
for _, tool := range m.Tools {
n += len(tool.Previous)
}
if n > revisionEntries {
return n
}
}
}
return n
}
func (s *state) revisionWeight() int { return s.Codex.weight() + s.Claude.weight() }
func (s *state) withoutRevisions() *state {
if s.Codex == nil && s.Claude == nil {
return s
}
c := *s
c.Codex, c.Claude = nil, nil
return &c
}
func (s *callFile) revisionWeight() int {
if s.CX == nil {
return s.Claude.weight()
}
return s.Claude.weight() + s.CX.Usage.weight() + len(s.CX.Contexts) + len(s.CX.Turns) + len(s.CX.Timings)
}
func (s *callFile) withoutRevisions() *callFile {
if s.CX == nil && s.Claude == nil {
return s
}
c := *s
c.CX, c.Claude = nil, nil
return &c
}
type revisionCandidate struct {
path string
mod int64
weight int
size int64
bounded bool
}
func (c revisionCandidate) eligible(now time.Time) bool {
if c.bounded {
return c.weight > 0 && c.weight <= claudeRevisionEntries
}
return recentRevision(c.mod, c.weight, now)
}
// Called with mu held. Reserve only windows already in memory or about to be
// parsed; an unchanged disk-only summary must not take a phantom cache slot.
func summaryRevisionWindows(todo []file, now time.Time) map[string]bool {
candidates := make(map[string]revisionCandidate)
for path, s := range cache {
if s.Claude != nil {
candidates[path] = revisionCandidate{path: path, mod: s.Mod, weight: claudeRevisionEntries, size: s.Size, bounded: true}
}
}
for _, f := range todo {
_, retained := candidates[f.path]
if parserFor(f.agent).claude && (retained || workingRevision(f.mod.UnixNano(), now)) {
candidates[f.path] = revisionCandidate{path: f.path, mod: f.mod.UnixNano(), weight: claudeRevisionEntries, size: f.size, bounded: true}
}
}
ranked := make([]revisionCandidate, 0, len(candidates))
for _, c := range candidates {
ranked = append(ranked, c)
}
return retainedRevisions(ranked, now)
}
func retainedRevisions(candidates []revisionCandidate, now time.Time) map[string]bool {
sort.Slice(candidates, func(i, j int) bool {
recentI, recentJ := workingRevision(candidates[i].mod, now), workingRevision(candidates[j].mod, now)
if recentI != recentJ {
return recentI
}
if candidates[i].size != candidates[j].size {
return candidates[i].size > candidates[j].size
}
if candidates[i].mod != candidates[j].mod {
return candidates[i].mod > candidates[j].mod
}
return candidates[i].path < candidates[j].path
})
keep := map[string]bool{}
used, active := 0, 0
for _, c := range candidates {
if !c.eligible(now) || len(keep) == revisionFiles {
continue
}
if !c.bounded && c.weight > revisionEntries {
// an active Codex session past the shared budget: outside it
if active < revisionActiveFiles {
keep[c.path] = true
active++
}
continue
}
if used+c.weight > revisionEntries {
continue
}
keep[c.path] = true
used += c.weight
}
return keep
}
// Called with mu held. Replace snapshots instead of mutating them: a parser
// may still be reading the previous snapshot outside the metadata lock.
func trimSummaryRevisions(now time.Time) {
var candidates []revisionCandidate
for path, s := range cache {
if n := s.revisionWeight(); n > 0 {
candidates = append(candidates, revisionCandidate{path: path, mod: s.Mod, weight: n, size: s.Size, bounded: s.Claude != nil})
}
}
keep := retainedRevisions(candidates, now)
for _, c := range candidates {
if !keep[c.path] {
cache[c.path] = cache[c.path].withoutRevisions()
}
}
}
// Called with callsMu held. The row cache and compact continuation cache have
// independent fixed bounds. A disk shard without a window stays disk-only.
func trimCallRevisions(now time.Time) {
var candidates []revisionCandidate
for path, s := range callCache {
if n := s.revisionWeight(); n > 0 {
candidates = append(candidates, revisionCandidate{path: path, mod: s.Mod, weight: n, size: s.Size, bounded: s.Claude != nil})
}
}
keep := retainedRevisions(candidates, now)
for _, c := range candidates {
if !keep[c.path] {
callCache[c.path] = callCache[c.path].withoutRevisions()
}
}
candidates = candidates[:0]
for path, entry := range callContinuations {
candidates = append(candidates, revisionCandidate{path: path, mod: entry.state.Mod, weight: entry.state.revisionWeight(), size: entry.state.Size, bounded: entry.state.Claude != nil})
}
keep = retainedRevisions(candidates, now)
order := callContinuationOrder[:0]
for _, path := range callContinuationOrder {
if keep[path] {
order = append(order, path)
} else {
delete(callContinuations, path)
}
}
callContinuationOrder = order
}