carlos / platform Public

Preserve prune progress and trim idle analytics caches

Keep the resume position when discovery fails or times out. Start each box with eight keys and grow backlog pages so retained days do not consume the daily scan budget. Drop expired in-memory summaries during enabled passes.
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 3cf918d6e9b2fa802f169a636a1a275de2cd53d1 parent 744fdbe
4 files changed, +160 −2
  • internal/analytics/prune.go +28 −2
  • internal/analytics/prune_test.go +92 −0
  • internal/console/analyticsprune.go +16 −0
  • internal/console/analyticsprune_test.go +24 −0

Intent

Attributed to this commit: 8.41 g CO₂e (773,155 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stats-prune-400, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/analytics/prune.go b/internal/analytics/prune.go
index e5908ab50..815994bc1 100644
--- a/internal/analytics/prune.go
+++ b/internal/analytics/prune.go
@@ -14,7 +14,8 @@ import (
)
// PruneOptions bounds a console retention pass. StartAt resumes at a box's
-// days prefix, always listing that box from the beginning so failed deletes
+// days prefix (or its app/account prefix if discovery timed out), always
+// listing that box from the beginning so failed deletes
// are retried. A completed pass clears NextBox and the next pass starts over.
type PruneOptions struct {
DryRun bool
@@ -42,6 +43,7 @@ func RetentionCutoff(now time.Time) time.Time {
// stores without PageLister fail closed rather than materialising an unbounded
// day listing. The console supplies a timeout as well as these work limits.
func Prune(ctx context.Context, st release.Store, now time.Time, opt PruneOptions) (stats PruneStats, result error) {
+ stats.NextBox = opt.StartAt
if opt.Logf == nil {
opt.Logf = log.Printf
}
@@ -91,9 +93,18 @@ func Prune(ctx context.Context, st release.Store, now time.Time, opt PruneOption
malformed(accountDir)
continue
}
+ if accountDir < opt.StartAt && !strings.HasPrefix(opt.StartAt, accountDir) {
+ continue
+ }
+ if accountDir > stats.NextBox {
+ stats.NextBox = accountDir
+ }
apps, err := dirs(accountDir)
if err != nil {
fail(err)
+ if ctx.Err() != nil {
+ return stats, nil
+ }
continue
}
for _, appDir := range apps {
@@ -109,9 +120,15 @@ func Prune(ctx context.Context, st release.Store, now time.Time, opt PruneOption
continue
}
stats.Apps++
+ if prefix > stats.NextBox {
+ stats.NextBox = prefix
+ }
boxes, err := dirs(prefix)
if err != nil {
fail(err)
+ if ctx.Err() != nil {
+ return stats, nil
+ }
continue
}
for _, boxDir := range boxes {
@@ -135,6 +152,10 @@ func Prune(ctx context.Context, st release.Store, now time.Time, opt PruneOption
}
stats.Boxes++
after := ""
+ // A mature box normally has one expired day and about 400 retained
+ // days. Start small so retained files do not exhaust the pass budget;
+ // grow only while catching up an older backlog.
+ pageSize := min(8, opt.PageSize)
for {
if err := ctx.Err(); err != nil {
fail(err)
@@ -143,7 +164,7 @@ func Prune(ctx context.Context, st release.Store, now time.Time, opt PruneOption
if attempted >= opt.MaxDeletes || stats.Listed >= opt.MaxKeys {
return stats, nil
}
- limit := min(opt.PageSize, opt.MaxKeys-stats.Listed)
+ limit := min(pageSize, opt.MaxKeys-stats.Listed)
stats.ListCalls++
keys, err := pages.ListPage(ctx, days, after, limit)
if err != nil {
@@ -231,10 +252,15 @@ func Prune(ctx context.Context, st release.Store, now time.Time, opt PruneOption
break
}
after = keys[len(keys)-1]
+ pageSize = min(pageSize*2, opt.PageSize)
}
}
}
}
+ if err := ctx.Err(); err != nil {
+ fail(err)
+ return stats, nil
+ }
stats.NextBox = ""
return stats, nil
}
diff --git a/internal/analytics/prune_test.go b/internal/analytics/prune_test.go
index fb8234f8f..ee1b88012 100644
--- a/internal/analytics/prune_test.go
+++ b/internal/analytics/prune_test.go
@@ -734,3 +734,95 @@ func TestPruneListErrorIsCountedAndOtherBoxesContinue(t *testing.T) {
mustExist(t, st, b1)
mustNotExist(t, st, b2)
}
+
+func TestPruneDiscoveryFailurePreservesResume(t *testing.T) {
+ start, _ := BoxPrefix("bab", "shop", "box")
+ for _, prefix := range []string{"apps/", "apps/bab/", "apps/bab/shop/analytics/"} {
+ t.Run(prefix, func(t *testing.T) {
+ st := newPruneStore(t)
+ putKey(t, st, dayAgo(t, "bab", "shop", "box", 401))
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ st.dirs = func(p string) ([]string, error) {
+ if p == prefix {
+ cancel()
+ return nil, ctx.Err()
+ }
+ return st.inner.ListDirs(ctx, p)
+ }
+ stats, err := Prune(ctx, st, pruneNow, PruneOptions{StartAt: start, Logf: func(string, ...any) {}})
+ if !errors.Is(err, context.Canceled) || stats.NextBox != start || stats.Errors != 1 || stats.Deleted != 0 {
+ t.Fatalf("stats=%+v err=%v", stats, err)
+ }
+ })
+ }
+ st := newPruneStore(t)
+ st.dirs = func(string) ([]string, error) { return nil, errors.New("transient LIST error") }
+ stats, err := Prune(context.Background(), st, pruneNow, PruneOptions{StartAt: start, Logf: func(string, ...any) {}})
+ if err == nil || stats.NextBox != start {
+ t.Fatalf("lost resume after root LIST failure: %+v %v", stats, err)
+ }
+}
+
+func TestPruneDiscoveryTimeoutStopsOnceAndResumesNextApp(t *testing.T) {
+ st := newPruneStore(t)
+ for _, app := range []string{"aaa", "bbb", "ccc", "ddd"} {
+ putKey(t, st, dayAgo(t, "bab", app, "box", 401))
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ stopped := "apps/bab/bbb/analytics/"
+ st.dirs = func(p string) ([]string, error) {
+ if p == stopped {
+ cancel()
+ return nil, ctx.Err()
+ }
+ if p > stopped {
+ t.Errorf("continued discovery after timeout: %s", p)
+ }
+ return st.inner.ListDirs(ctx, p)
+ }
+ stats, err := Prune(ctx, st, pruneNow, PruneOptions{Logf: func(string, ...any) {}})
+ if !errors.Is(err, context.Canceled) || stats.Errors != 1 || stats.NextBox != stopped || stats.Deleted != 1 {
+ t.Fatalf("%+v %v", stats, err)
+ }
+ st.dirs = nil
+ next, _ := runPrune(t, st, PruneOptions{StartAt: stats.NextBox})
+ if next.Deleted != 3 || next.NextBox != "" {
+ t.Fatalf("resume: %+v", next)
+ }
+}
+
+func TestPruneSmallFirstPageReachesMatureBoxesWithinBudget(t *testing.T) {
+ st := newPruneStore(t)
+ st.dirs = func(p string) ([]string, error) {
+ switch p {
+ case "apps/":
+ return []string{"apps/bab/"}, nil
+ case "apps/bab/":
+ return []string{"apps/bab/shop/"}, nil
+ case "apps/bab/shop/analytics/":
+ var dirs []string
+ for i := 0; i < 12; i++ {
+ dirs = append(dirs, fmt.Sprintf("%sbox-%02d/", p, i))
+ }
+ return dirs, nil
+ }
+ t.Fatalf("unexpected directory: %s", p)
+ return nil, nil
+ }
+ st.page = func(ctx context.Context, p, after string, limit int) ([]string, error) {
+ if after != "" {
+ t.Fatalf("listed beyond cutoff: %q", after)
+ }
+ var keys []string
+ for age := 401; age >= 0 && len(keys) < limit; age-- {
+ keys = append(keys, p+pruneNow.AddDate(0, 0, -age).Format("2006-01-02")+".json")
+ }
+ return keys, nil
+ }
+ stats, _ := runPrune(t, st, PruneOptions{MaxKeys: 100})
+ if stats.Boxes != 12 || stats.Deleted != 12 || stats.Listed > 100 || stats.NextBox != "" {
+ t.Fatalf("mature boxes: %+v", stats)
+ }
+}
diff --git a/internal/console/analyticsprune.go b/internal/console/analyticsprune.go
index 624d8d0d7..630f1ff81 100644
--- a/internal/console/analyticsprune.go
+++ b/internal/console/analyticsprune.go
@@ -56,6 +56,9 @@ func (s *Server) analyticsPrunePass(ctx context.Context, now time.Time) error {
if err != nil {
return fmt.Errorf("analytics prune: daily admission: %w", err)
}
+ if mode == "on" {
+ s.pruneAnalyticsCaches(now)
+ }
stats, pruneErr := analytics.Prune(ctx, s.cfg.Releases, now, analytics.PruneOptions{
DryRun: mode == "dry-run", PageSize: 1000, MaxDeletes: 10000, MaxKeys: 100000, StartAt: cursor,
})
@@ -70,3 +73,16 @@ func (s *Server) analyticsPrunePass(ctx context.Context, now time.Time) error {
}
return pruneErr
}
+
+// Cache TTLs control reads; an idle entry can otherwise remain allocated long
+// after its last view. The daily on-mode sweep also drops those old summaries.
+func (s *Server) pruneAnalyticsCaches(now time.Time) {
+ s.usageDays.prune(now)
+ s.trafficMemo.mu.Lock()
+ defer s.trafficMemo.mu.Unlock()
+ for key, entry := range s.trafficMemo.m {
+ if now.Sub(entry.at) >= analyticsMemoTTL || now.Before(entry.at) {
+ delete(s.trafficMemo.m, key)
+ }
+ }
+}
diff --git a/internal/console/analyticsprune_test.go b/internal/console/analyticsprune_test.go
index 6d3b78a33..43d6e0afd 100644
--- a/internal/console/analyticsprune_test.go
+++ b/internal/console/analyticsprune_test.go
@@ -142,3 +142,27 @@ func TestAnalyticsPruneHostClaimRefuses(t *testing.T) {
t.Fatal("host-claim mutation was not refused")
}
}
+
+func TestAnalyticsPruneTrimsIdleCachesOnlyWhenOn(t *testing.T) {
+ for _, mode := range []string{"off", "dry-run", "on"} {
+ t.Run(mode, func(t *testing.T) {
+ now := time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC)
+ old := now.AddDate(0, 0, -401)
+ srv := &Server{store: openTestStore(t), cfg: Config{AnalyticsPrune: mode, Releases: release.NewDirStore(t.TempDir())}}
+ srv.trafficMemo.put("old", analytics.Summary{PV: 1}, old)
+ entry := usageDayEntry{date: old.Format("2006-01-02"), at: old, body: []byte("{}")}
+ srv.usageDays.entries = map[string]usageDayEntry{"old": entry}
+ srv.usageDays.bytes = entry.size("old")
+ if err := srv.analyticsPrunePass(context.Background(), now); err != nil {
+ t.Fatal(err)
+ }
+ kept := 1
+ if mode == "on" {
+ kept = 0
+ }
+ if n, _ := srv.usageDays.held(); n != kept || len(srv.trafficMemo.m) != kept {
+ t.Fatalf("cache entries: usage=%d memo=%d want=%d", n, len(srv.trafficMemo.m), kept)
+ }
+ })
+ }
+}