carlos / platform Public

Prune expired analytics from a bounded daily console pass

Keep files dated exactly 400 UTC days ago. Persist the daily attempt and resume box, validate every delete, and default CONSOLE_ANALYTICS_PRUNE to off. Host-claim mode refuses activation pending a separately authorized mutation path.
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 744fdbe373b1ca1f6acdbc712c5019a567fb0132 parent 6d8bd3a
9 files changed, +1,237 −0
  • cmd/console/main.go +1 −0
  • internal/analytics/prune.go +261 −0
  • internal/analytics/prune_test.go +736 −0
  • internal/console/analyticsprune.go +72 −0
  • internal/console/analyticsprune_test.go +144 −0
  • internal/console/economicspass.go +4 −0
  • internal/console/server.go +11 −0
  • internal/console/store.go +6 −0
  • internal/console/store_gate.go +2 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go
index e83ec8575..cba2ac4db 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -498,6 +498,7 @@ func serve() {
Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"),
Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"),
Releases: rel,
+ AnalyticsPrune: os.Getenv("CONSOLE_ANALYTICS_PRUNE"),
// The deployment bucket's NAME, from the same variable openStore()
// opens it with — /fleet/architecture draws the box -> bucket edge
// from it. Empty on a CARLOS_DEPLOYMENT_DIR deployment, which
diff --git a/internal/analytics/prune.go b/internal/analytics/prune.go
new file mode 100644
index 000000000..e5908ab50
--- /dev/null
+++ b/internal/analytics/prune.go
@@ -0,0 +1,261 @@
+package analytics
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// PruneOptions bounds a console retention pass. StartAt resumes at a box's
+// days prefix, 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
+ PageSize int
+ MaxDeletes int
+ MaxKeys int
+ StartAt string
+ Logf func(string, ...any)
+}
+
+type PruneStats struct {
+ Apps, Boxes, Listed, Deleted, WouldDelete, Malformed, Errors int
+ ListCalls, DeleteCalls int
+ NextBox string
+}
+
+// RetentionCutoff is midnight UTC 400 calendar days before today's UTC date.
+// Only dates strictly before it expire: exactly 400 days ago is kept,
+// 401 days ago is deleted, regardless of the current time of day or zone.
+func RetentionCutoff(now time.Time) time.Time {
+ return now.UTC().Truncate(24*time.Hour).AddDate(0, 0, -400)
+}
+
+// Prune removes expired analytics day files only. It requires bounded paging;
+// 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) {
+ if opt.Logf == nil {
+ opt.Logf = log.Printf
+ }
+ if opt.PageSize <= 0 || opt.PageSize > 1000 {
+ opt.PageSize = 1000
+ }
+ if opt.MaxDeletes <= 0 {
+ opt.MaxDeletes = 10000
+ }
+ if opt.MaxKeys <= 0 {
+ opt.MaxKeys = 100000
+ }
+ pages, ok := st.(release.PageLister)
+ if !ok {
+ stats.Errors++
+ return stats, fmt.Errorf("analytics prune: store has no bounded paging")
+ }
+ cutoff := RetentionCutoff(now)
+ var errs []error
+ fail := func(err error) { stats.Errors++; errs = append(errs, err); opt.Logf("analytics prune: %v", err) }
+ malformed := func(key string) { stats.Malformed++; opt.Logf("analytics prune: skipped malformed key %q", key) }
+ defer func() { result = errors.Join(append(errs, result)...) }()
+ dirs := func(prefix string) ([]string, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if counted, ok := st.(release.CountedDirLister); ok {
+ dirs, calls, err := counted.ListDirsWithCount(ctx, prefix)
+ stats.ListCalls += calls
+ sort.Strings(dirs)
+ return dirs, err
+ }
+ stats.ListCalls++
+ dirs, err := st.ListDirs(ctx, prefix)
+ sort.Strings(dirs)
+ return dirs, err
+ }
+ accounts, err := dirs("apps/")
+ if err != nil {
+ fail(err)
+ return stats, nil
+ }
+ attempted := 0
+ for _, accountDir := range accounts {
+ acct, valid := pruneChild("apps/", accountDir)
+ if !valid || !release.ValidAccount(acct) {
+ malformed(accountDir)
+ continue
+ }
+ apps, err := dirs(accountDir)
+ if err != nil {
+ fail(err)
+ continue
+ }
+ for _, appDir := range apps {
+ app, valid := pruneChild(accountDir, appDir)
+ if !valid || applog.CheckApp(acct, app) != nil {
+ malformed(appDir)
+ continue
+ }
+ // Account and app listings are small delimiter listings. Skip whole apps
+ // preceding the saved box, without listing their analytics again.
+ prefix, _ := Prefix(acct, app)
+ if opt.StartAt != "" && prefix < opt.StartAt && !strings.HasPrefix(opt.StartAt, prefix) {
+ continue
+ }
+ stats.Apps++
+ boxes, err := dirs(prefix)
+ if err != nil {
+ fail(err)
+ continue
+ }
+ for _, boxDir := range boxes {
+ box, valid := pruneChild(prefix, boxDir)
+ if !valid || applog.CheckSegment("box", box) != nil {
+ malformed(boxDir)
+ continue
+ }
+ days, err := BoxPrefix(acct, app, box)
+ if err != nil {
+ malformed(boxDir)
+ continue
+ }
+ if days < opt.StartAt {
+ continue
+ }
+ stats.NextBox = days
+ if err := ctx.Err(); err != nil {
+ fail(err)
+ return stats, nil
+ }
+ stats.Boxes++
+ after := ""
+ for {
+ if err := ctx.Err(); err != nil {
+ fail(err)
+ return stats, nil
+ }
+ if attempted >= opt.MaxDeletes || stats.Listed >= opt.MaxKeys {
+ return stats, nil
+ }
+ limit := min(opt.PageSize, opt.MaxKeys-stats.Listed)
+ stats.ListCalls++
+ keys, err := pages.ListPage(ctx, days, after, limit)
+ if err != nil {
+ fail(err)
+ break
+ }
+ // PageLister promises sorted, exclusive, bounded pages. Refuse a broken
+ // adapter before an early-stop decision could hide older keys.
+ previous := after
+ for _, key := range keys {
+ if key <= previous || len(keys) > limit {
+ fail(fmt.Errorf("analytics prune: invalid page after %q", after))
+ return stats, nil
+ }
+ previous = key
+ }
+ stats.Listed += len(keys)
+ var batch []string
+ stop := false
+ for _, key := range keys {
+ expired, valid := pruneEligible(days, key, cutoff)
+ if !valid {
+ malformed(key)
+ continue
+ }
+ if !expired {
+ stop = true
+ break
+ }
+ if attempted+len(batch) >= opt.MaxDeletes {
+ break
+ }
+ batch = append(batch, key)
+ }
+ // This is the sole deletion boundary: revalidate every key against the
+ // expected prefix and UTC cutoff immediately before handing it to Store.
+ guarded := batch[:0]
+ for _, key := range batch {
+ if expired, valid := pruneEligible(days, key, cutoff); valid && expired {
+ guarded = append(guarded, key)
+ } else {
+ malformed(key)
+ }
+ }
+ attempted += len(guarded)
+ if opt.DryRun {
+ for _, key := range guarded {
+ opt.Logf("analytics prune: would delete %q", key)
+ }
+ stats.WouldDelete += len(guarded)
+ } else if len(guarded) > 0 {
+ if batcher, ok := st.(release.BatchDeleter); ok {
+ stats.DeleteCalls++
+ err := batcher.DeleteKeys(ctx, guarded)
+ if err == nil {
+ stats.Deleted += len(guarded)
+ } else {
+ var partial *release.BatchDeleteError
+ if errors.As(err, &partial) {
+ for _, key := range guarded {
+ if perKey, failed := partial.Failed[key]; failed {
+ opt.Logf("analytics prune: delete %q: %v", key, perKey)
+ } else {
+ stats.Deleted++
+ }
+ }
+ }
+ fail(err)
+ }
+ } else {
+ for _, key := range guarded {
+ stats.DeleteCalls++
+ if err := st.Delete(ctx, key); err != nil {
+ fail(err)
+ } else {
+ stats.Deleted++
+ }
+ }
+ }
+ }
+ if attempted >= opt.MaxDeletes || stats.Listed >= opt.MaxKeys {
+ return stats, nil
+ }
+ if stop || len(keys) < limit {
+ break
+ }
+ after = keys[len(keys)-1]
+ }
+ }
+ }
+ }
+ stats.NextBox = ""
+ return stats, nil
+}
+
+func pruneChild(prefix, dir string) (string, bool) {
+ rest, ok := strings.CutPrefix(dir, prefix)
+ leaf, slash := strings.CutSuffix(rest, "/")
+ return leaf, ok && slash && leaf != "." && leaf != ".." && !strings.ContainsAny(leaf, "/\\") && leaf != ""
+}
+
+// pruneEligible accepts only one exact date leaf under the supplied days
+// prefix. Neither a nested object nor an adjacent family can become a delete.
+func pruneEligible(prefix, key string, cutoff time.Time) (expired, valid bool) {
+ leaf, ok := strings.CutPrefix(key, prefix)
+ if !ok || len(leaf) != len("2006-01-02.json") || !strings.HasSuffix(leaf, ".json") {
+ return false, false
+ }
+ date := strings.TrimSuffix(leaf, ".json")
+ d, err := time.Parse("2006-01-02", date)
+ if err != nil || d.Format("2006-01-02") != date {
+ return false, false
+ }
+ return d.Before(cutoff), true
+}
diff --git a/internal/analytics/prune_test.go b/internal/analytics/prune_test.go
new file mode 100644
index 000000000..fb8234f8f
--- /dev/null
+++ b/internal/analytics/prune_test.go
@@ -0,0 +1,736 @@
+package analytics
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// pruneNow is mid-afternoon UTC so a wrong time-of-day rule would show.
+// 400 days before 2026-11-11 is 2025-10-07: that date is kept, 2025-10-06 goes.
+var pruneNow = time.Date(2026, 11, 11, 15, 30, 0, 0, time.UTC)
+
+type pruneLog struct{ lines []string }
+
+func (l *pruneLog) logf(f string, a ...any) { l.lines = append(l.lines, fmt.Sprintf(f, a...)) }
+func (l *pruneLog) has(sub string) bool {
+ for _, s := range l.lines {
+ if strings.Contains(s, sub) {
+ return true
+ }
+ }
+ return false
+}
+
+// pruneStore is a Store wrapper that exposes PageLister (and nothing else
+// optional: no BatchDeleter), counts calls, and lets a test replace the
+// listings.
+type pruneStore struct {
+ release.Store
+ inner *release.DirStore
+ pageCalls int
+ dirCalls int
+ deletes []string
+ page func(ctx context.Context, prefix, after string, limit int) ([]string, error)
+ dirs func(prefix string) ([]string, error)
+ pageSeen []string
+ afterPage func(n int)
+}
+
+func newPruneStore(t *testing.T) *pruneStore {
+ t.Helper()
+ d := release.NewDirStore(t.TempDir())
+ return &pruneStore{Store: d, inner: d}
+}
+
+func (s *pruneStore) ListPage(ctx context.Context, prefix, after string, limit int) ([]string, error) {
+ s.pageCalls++
+ s.pageSeen = append(s.pageSeen, prefix)
+ if s.afterPage != nil {
+ defer s.afterPage(s.pageCalls)
+ }
+ if s.page != nil {
+ return s.page(ctx, prefix, after, limit)
+ }
+ return s.inner.ListPage(ctx, prefix, after, limit)
+}
+
+func (s *pruneStore) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ s.dirCalls++
+ if s.dirs != nil {
+ return s.dirs(prefix)
+ }
+ return s.inner.ListDirs(ctx, prefix)
+}
+
+func (s *pruneStore) Delete(ctx context.Context, key string) error {
+ s.deletes = append(s.deletes, key)
+ return s.inner.Delete(ctx, key)
+}
+
+// batchStore adds a BatchDeleter whose behaviour the test controls.
+type batchStore struct {
+ *pruneStore
+ batches [][]string
+ failing map[string]bool
+}
+
+func (b *batchStore) DeleteKeys(ctx context.Context, keys []string) error {
+ b.batches = append(b.batches, slices.Clone(keys))
+ failed := map[string]error{}
+ for _, k := range keys {
+ if b.failing[k] {
+ failed[k] = errors.New("denied")
+ continue
+ }
+ if err := b.inner.Delete(ctx, k); err != nil {
+ failed[k] = err
+ }
+ }
+ if len(failed) > 0 {
+ return &release.BatchDeleteError{Failed: failed}
+ }
+ return nil
+}
+
+func putKey(t *testing.T, st release.Store, key string) {
+ t.Helper()
+ if _, err := st.Put(context.Background(), key, []byte("{}"), ""); err != nil {
+ t.Fatalf("put %s: %v", key, err)
+ }
+}
+
+func dayAgo(t *testing.T, acct, app, box string, n int) string {
+ t.Helper()
+ k, err := DayKey(acct, app, box, pruneNow.AddDate(0, 0, -n).Format("2006-01-02"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return k
+}
+
+func allKeys(t *testing.T, st release.Store) []string {
+ t.Helper()
+ keys, err := st.List(context.Background(), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ slices.Sort(keys)
+ return keys
+}
+
+func mustNotExist(t *testing.T, st release.Store, keys ...string) {
+ t.Helper()
+ for _, k := range keys {
+ if _, _, err := st.Get(context.Background(), k); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("%s should be deleted, Get err = %v", k, err)
+ }
+ }
+}
+
+func mustExist(t *testing.T, st release.Store, keys ...string) {
+ t.Helper()
+ for _, k := range keys {
+ if _, _, err := st.Get(context.Background(), k); err != nil {
+ t.Errorf("%s should be kept: %v", k, err)
+ }
+ }
+}
+
+func runPrune(t *testing.T, st release.Store, opt PruneOptions) (PruneStats, *pruneLog) {
+ t.Helper()
+ l := &pruneLog{}
+ opt.Logf = l.logf
+ stats, err := Prune(context.Background(), st, pruneNow, opt)
+ if err != nil {
+ t.Fatalf("Prune: %v (stats %+v)", err, stats)
+ }
+ return stats, l
+}
+
+func TestPruneCutoffIsUTCDate(t *testing.T) {
+ want := time.Date(2025, 10, 7, 0, 0, 0, 0, time.UTC)
+ if got := RetentionCutoff(pruneNow); !got.Equal(want) {
+ t.Fatalf("cutoff = %v, want %v", got, want)
+ }
+ // 22:00 in UTC-8 on Nov 11 is already Nov 12 in UTC.
+ west := time.Date(2026, 11, 11, 22, 0, 0, 0, time.FixedZone("W", -8*3600))
+ want = time.Date(2025, 10, 8, 0, 0, 0, 0, time.UTC)
+ if got := RetentionCutoff(west); !got.Equal(want) {
+ t.Fatalf("zoned cutoff = %v, want %v", got, want)
+ }
+ // Midnight and the last second of the same UTC day agree.
+ a := RetentionCutoff(time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC))
+ b := RetentionCutoff(time.Date(2026, 11, 11, 23, 59, 59, 0, time.UTC))
+ if !a.Equal(b) {
+ t.Fatalf("cutoff moved within a day: %v vs %v", a, b)
+ }
+}
+
+func TestPruneBoundary399400401Days(t *testing.T) {
+ st := newPruneStore(t)
+ k399 := dayAgo(t, "acme", "shop", "b1", 399)
+ k400 := dayAgo(t, "acme", "shop", "b1", 400)
+ k401 := dayAgo(t, "acme", "shop", "b1", 401)
+ for _, k := range []string{k399, k400, k401} {
+ putKey(t, st, k)
+ }
+ if !strings.HasSuffix(k400, "2025-10-07.json") || !strings.HasSuffix(k401, "2025-10-06.json") {
+ t.Fatalf("fixture dates drifted: %s %s", k400, k401)
+ }
+ stats, _ := runPrune(t, st, PruneOptions{})
+ mustNotExist(t, st, k401)
+ mustExist(t, st, k399, k400)
+ if stats.Deleted != 1 || stats.Errors != 0 || stats.Malformed != 0 {
+ t.Fatalf("stats = %+v", stats)
+ }
+}
+
+func TestPruneBoundaryUsesUTCNotLocalZone(t *testing.T) {
+ st := newPruneStore(t)
+ k1007 := "apps/acme/shop/analytics/b1/days/2025-10-07.json"
+ k1008 := "apps/acme/shop/analytics/b1/days/2025-10-08.json"
+ putKey(t, st, k1007)
+ putKey(t, st, k1008)
+ west := time.Date(2026, 11, 11, 22, 0, 0, 0, time.FixedZone("W", -8*3600)) // UTC Nov 12
+ if _, err := Prune(context.Background(), st, west, PruneOptions{Logf: func(string, ...any) {}}); err != nil {
+ t.Fatal(err)
+ }
+ mustNotExist(t, st, k1007)
+ mustExist(t, st, k1008)
+}
+
+func TestPruneMultipleAppsAndBoxes(t *testing.T) {
+ st := release.NewDirStore(t.TempDir())
+ type loc struct{ acct, app, box string }
+ locs := []loc{
+ {"acme", "shop", "b1"}, {"acme", "shop", "b2"}, {"acme", "blog", "b1"},
+ {"zeta", "docs", "b9"}, {"zeta", "docs", "b10"},
+ }
+ var old, keep []string
+ for _, l := range locs {
+ for _, n := range []int{900, 500, 401} {
+ k := dayAgo(t, l.acct, l.app, l.box, n)
+ putKey(t, st, k)
+ old = append(old, k)
+ }
+ for _, n := range []int{400, 100, 0} {
+ k := dayAgo(t, l.acct, l.app, l.box, n)
+ putKey(t, st, k)
+ keep = append(keep, k)
+ }
+ }
+ stats, _ := runPrune(t, st, PruneOptions{})
+ mustNotExist(t, st, old...)
+ mustExist(t, st, keep...)
+ if stats.Apps != 3 || stats.Boxes != 5 || stats.Deleted != len(old) || stats.NextBox != "" {
+ t.Fatalf("stats = %+v", stats)
+ }
+ // Batch path was used (DirStore is a BatchDeleter): one call per box.
+ if stats.DeleteCalls != 5 {
+ t.Fatalf("DeleteCalls = %d, want 5", stats.DeleteCalls)
+ }
+}
+
+func TestPrunePagingFindsEveryOldKeyAndStopsEarly(t *testing.T) {
+ st := newPruneStore(t)
+ var old []string
+ var keep []string
+ for i := 0; i < 5; i++ {
+ k := dayAgo(t, "acme", "shop", "b1", 900-i)
+ putKey(t, st, k)
+ old = append(old, k)
+ }
+ for _, n := range []int{300, 200, 1} {
+ k := dayAgo(t, "acme", "shop", "b1", n)
+ putKey(t, st, k)
+ keep = append(keep, k)
+ }
+ stats, _ := runPrune(t, st, PruneOptions{PageSize: 2})
+ mustNotExist(t, st, old...)
+ mustExist(t, st, keep...)
+ // Pages: [o1 o2] [o3 o4] [o5 n1]; n1 is past the cutoff, so no 4th page.
+ if st.pageCalls != 3 {
+ t.Fatalf("ListPage calls = %d, want 3", st.pageCalls)
+ }
+ if stats.ListCalls != st.pageCalls+st.dirCalls {
+ t.Fatalf("ListCalls = %d, want %d", stats.ListCalls, st.pageCalls+st.dirCalls)
+ }
+ if stats.Deleted != 5 || stats.Listed != 6 {
+ t.Fatalf("stats = %+v", stats)
+ }
+}
+
+func TestPrunePagingAllOldExactPageMultiple(t *testing.T) {
+ st := newPruneStore(t)
+ var old []string
+ for i := 0; i < 4; i++ {
+ k := dayAgo(t, "acme", "shop", "b1", 700-i)
+ putKey(t, st, k)
+ old = append(old, k)
+ }
+ stats, _ := runPrune(t, st, PruneOptions{PageSize: 2})
+ mustNotExist(t, st, old...)
+ // [o o] [o o] [] : the empty third page ends the box.
+ if st.pageCalls != 3 || stats.Deleted != 4 {
+ t.Fatalf("pageCalls %d stats %+v", st.pageCalls, stats)
+ }
+}
+
+func TestPrunePagingTwoBoxesSmallPages(t *testing.T) {
+ st := newPruneStore(t)
+ var old []string
+ for _, box := range []string{"b1", "b2"} {
+ for i := 0; i < 7; i++ {
+ k := dayAgo(t, "acme", "shop", box, 800-i)
+ putKey(t, st, k)
+ old = append(old, k)
+ }
+ putKey(t, st, dayAgo(t, "acme", "shop", box, 10))
+ }
+ stats, _ := runPrune(t, st, PruneOptions{PageSize: 2})
+ mustNotExist(t, st, old...)
+ if stats.Deleted != 14 || len(allKeys(t, st)) != 2 {
+ t.Fatalf("stats %+v keys %v", stats, allKeys(t, st))
+ }
+}
+
+func TestPruneLeavesAdjacentKeysAndLogsMalformed(t *testing.T) {
+ st := newPruneStore(t)
+ oldKey := "apps/acme/shop/analytics/b1/days/2020-01-01.json"
+ putKey(t, st, oldKey)
+ untouched := []string{
+ // adjacent families with old-looking names
+ "apps/acme/shop/logs/b1/2020-01-01.json",
+ "apps/acme/shop/errors/b1/2020-01-01.json",
+ "apps/acme/shop/site/2020-01-01.json",
+ // sibling files in the box dir and the analytics dir
+ "apps/acme/shop/analytics/b1/2020-01-01.json",
+ "apps/acme/shop/analytics/b1/meta.json",
+ "apps/acme/shop/analytics/b1/days-old/2020-01-01.json",
+ "apps/acme/shop/analytics/2020-01-01.json",
+ // nested under days/
+ "apps/acme/shop/analytics/b1/days/nested/2020-01-01.json",
+ "apps/acme/shop/analytics/b1/days/2019-01-01/2020-01-01.json",
+ // malformed leaves directly under days/
+ "apps/acme/shop/analytics/b1/days/2025-13-40.json",
+ "apps/acme/shop/analytics/b1/days/2020-01-01.json.bak",
+ "apps/acme/shop/analytics/b1/days/2020-1-1.json",
+ "apps/acme/shop/analytics/b1/days/2020-01-01.JSON",
+ "apps/acme/shop/analytics/b1/days/notadate.json",
+ // another app's box
+ "apps/acme/shop2/analytics/b1/days/2020-01-01.json",
+ }
+ for _, k := range untouched {
+ putKey(t, st, k)
+ }
+ // shop2 is a real app and IS pruned; take it out of the untouched set.
+ untouched = untouched[:len(untouched)-1]
+ stats, l := runPrune(t, st, PruneOptions{})
+ mustNotExist(t, st, oldKey, "apps/acme/shop2/analytics/b1/days/2020-01-01.json")
+ mustExist(t, st, untouched...)
+ if stats.Deleted != 2 {
+ t.Fatalf("Deleted = %d, want 2 (shop and shop2)", stats.Deleted)
+ }
+ for _, bad := range []string{"2025-13-40.json", "2020-01-01.json.bak", "2020-1-1.json", "2020-01-01.JSON", "notadate.json", "nested/2020-01-01.json"} {
+ if !l.has("malformed") || !l.has(bad) {
+ t.Errorf("no malformed log for %s; log: %v", bad, l.lines)
+ }
+ }
+ if stats.Malformed < 7 {
+ t.Fatalf("Malformed = %d, want at least 7", stats.Malformed)
+ }
+}
+
+func TestPruneDryRunDeletesNothing(t *testing.T) {
+ st := newPruneStore(t)
+ old1 := dayAgo(t, "acme", "shop", "b1", 500)
+ old2 := dayAgo(t, "acme", "shop", "b2", 401)
+ keep := dayAgo(t, "acme", "shop", "b1", 400)
+ for _, k := range []string{old1, old2, keep} {
+ putKey(t, st, k)
+ }
+ before := allKeys(t, st)
+ stats, l := runPrune(t, st, PruneOptions{DryRun: true})
+ if got := allKeys(t, st); !slices.Equal(got, before) {
+ t.Fatalf("dry run changed the store: %v -> %v", before, got)
+ }
+ if stats.WouldDelete != 2 || stats.Deleted != 0 || stats.DeleteCalls != 0 || len(st.deletes) != 0 {
+ t.Fatalf("stats = %+v deletes %v", stats, st.deletes)
+ }
+ if !l.has(fmt.Sprintf("would delete %q", old1)) || !l.has(fmt.Sprintf("would delete %q", old2)) {
+ t.Fatalf("dry run did not log both keys: %v", l.lines)
+ }
+ if l.has(keep) {
+ t.Fatalf("dry run mentioned a kept key: %v", l.lines)
+ }
+}
+
+func TestPruneIsIdempotent(t *testing.T) {
+ st := newPruneStore(t)
+ for _, n := range []int{900, 450, 401, 400, 5} {
+ putKey(t, st, dayAgo(t, "acme", "shop", "b1", n))
+ }
+ first, _ := runPrune(t, st, PruneOptions{PageSize: 2})
+ if first.Deleted != 3 {
+ t.Fatalf("first = %+v", first)
+ }
+ after := allKeys(t, st)
+ second, _ := runPrune(t, st, PruneOptions{PageSize: 2})
+ if second.Deleted != 0 || second.DeleteCalls != 0 || second.WouldDelete != 0 || second.Errors != 0 {
+ t.Fatalf("second = %+v", second)
+ }
+ if got := allKeys(t, st); !slices.Equal(got, after) {
+ t.Fatalf("second run changed the store: %v -> %v", after, got)
+ }
+}
+
+func TestPruneFallsBackToPerKeyDeleteWithoutBatchDeleter(t *testing.T) {
+ st := newPruneStore(t) // PageLister yes, BatchDeleter no
+ if _, ok := release.Store(st).(release.BatchDeleter); ok {
+ t.Fatal("fixture unexpectedly has a BatchDeleter")
+ }
+ if _, ok := release.Store(st).(release.PageLister); !ok {
+ t.Fatal("fixture lost its PageLister")
+ }
+ var old []string
+ for i := 0; i < 5; i++ {
+ k := dayAgo(t, "acme", "shop", "b1", 600+i)
+ putKey(t, st, k)
+ old = append(old, k)
+ }
+ keep := dayAgo(t, "acme", "shop", "b1", 399)
+ putKey(t, st, keep)
+ stats, _ := runPrune(t, st, PruneOptions{PageSize: 2})
+ mustNotExist(t, st, old...)
+ mustExist(t, st, keep)
+ if stats.Deleted != 5 || stats.DeleteCalls != 5 || len(st.deletes) != 5 {
+ t.Fatalf("stats %+v deletes %v", stats, st.deletes)
+ }
+}
+
+func TestPruneFailsClosedWithoutPageLister(t *testing.T) {
+ d := release.NewDirStore(t.TempDir())
+ k := "apps/acme/shop/analytics/b1/days/2020-01-01.json"
+ putKey(t, d, k)
+ var bare release.Store = struct{ release.Store }{d} // hides ListPage and DeleteKeys
+ l := &pruneLog{}
+ stats, err := Prune(context.Background(), bare, pruneNow, PruneOptions{Logf: l.logf})
+ if err == nil || !strings.Contains(err.Error(), "paging") {
+ t.Fatalf("err = %v, want a bounded-paging refusal", err)
+ }
+ if stats.Deleted != 0 || stats.ListCalls != 0 {
+ t.Fatalf("stats = %+v", stats)
+ }
+ mustExist(t, d, k)
+}
+
+func TestPruneMaxDeletesAndNextBoxResume(t *testing.T) {
+ st := newPruneStore(t)
+ boxes := []string{"b1", "b2", "b3"}
+ var old []string
+ for _, b := range boxes {
+ for i := 0; i < 2; i++ {
+ k := dayAgo(t, "acme", "shop", b, 700+i)
+ putKey(t, st, k)
+ old = append(old, k)
+ }
+ putKey(t, st, dayAgo(t, "acme", "shop", b, 1))
+ }
+ opt := PruneOptions{MaxDeletes: 3}
+ first, _ := runPrune(t, st, opt)
+ if first.Deleted != 3 {
+ t.Fatalf("first pass deleted %d, want exactly 3: %+v", first.Deleted, first)
+ }
+ wantNext, _ := BoxPrefix("acme", "shop", "b2")
+ if first.NextBox != wantNext {
+ t.Fatalf("NextBox = %q, want %q", first.NextBox, wantNext)
+ }
+ remaining := 0
+ for _, k := range old {
+ if _, _, err := st.Get(context.Background(), k); err == nil {
+ remaining++
+ }
+ }
+ if remaining != 3 {
+ t.Fatalf("remaining old keys = %d, want 3", remaining)
+ }
+ // Resume the next day from the saved box until the pass completes.
+ next := first.NextBox
+ for pass := 0; pass < 5 && next != ""; pass++ {
+ opt.StartAt = next
+ s, _ := runPrune(t, st, opt)
+ if s.Deleted > 3 {
+ t.Fatalf("pass %d deleted %d > MaxDeletes", pass, s.Deleted)
+ }
+ next = s.NextBox
+ }
+ if next != "" {
+ t.Fatal("resume never completed")
+ }
+ mustNotExist(t, st, old...)
+ if got := len(allKeys(t, st)); got != 3 {
+ t.Fatalf("kept keys = %d, want 3", got)
+ }
+}
+
+func TestPruneResumeSkipsEarlierBoxesAndApps(t *testing.T) {
+ st := newPruneStore(t)
+ early := dayAgo(t, "acme", "blog", "b1", 700)
+ earlyBox := dayAgo(t, "acme", "shop", "b1", 700)
+ late := dayAgo(t, "acme", "shop", "b2", 700)
+ for _, k := range []string{early, earlyBox, late} {
+ putKey(t, st, k)
+ }
+ start, _ := BoxPrefix("acme", "shop", "b2")
+ stats, _ := runPrune(t, st, PruneOptions{StartAt: start})
+ mustNotExist(t, st, late)
+ mustExist(t, st, early, earlyBox)
+ if stats.Deleted != 1 || stats.NextBox != "" {
+ t.Fatalf("stats = %+v", stats)
+ }
+}
+
+func TestPruneCancelledBeforeStartDeletesNothing(t *testing.T) {
+ st := newPruneStore(t)
+ k := dayAgo(t, "acme", "shop", "b1", 700)
+ putKey(t, st, k)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ stats, err := Prune(ctx, st, pruneNow, PruneOptions{Logf: func(string, ...any) {}})
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("err = %v, want context.Canceled", err)
+ }
+ if stats.Deleted != 0 || stats.Errors == 0 || st.pageCalls != 0 {
+ t.Fatalf("stats = %+v pageCalls %d", stats, st.pageCalls)
+ }
+ mustExist(t, st, k)
+}
+
+func TestPruneCancelledMidRunStopsBetweenPages(t *testing.T) {
+ st := newPruneStore(t)
+ var old []string
+ for i := 0; i < 6; i++ {
+ k := dayAgo(t, "acme", "shop", "b1", 700+i)
+ putKey(t, st, k)
+ old = append(old, k)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ st.afterPage = func(n int) {
+ if n == 1 {
+ cancel()
+ }
+ }
+ l := &pruneLog{}
+ stats, err := Prune(ctx, st, pruneNow, PruneOptions{PageSize: 2, Logf: l.logf})
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("err = %v, want context.Canceled", err)
+ }
+ if st.pageCalls != 1 {
+ t.Fatalf("ListPage calls after cancel = %d, want 1", st.pageCalls)
+ }
+ if stats.Deleted > 2 {
+ t.Fatalf("deleted %d after cancellation, want at most the first page", stats.Deleted)
+ }
+ if stats.NextBox == "" {
+ t.Fatal("NextBox must be kept so the next pass resumes")
+ }
+ // A later pass finishes the job.
+ runPrune(t, st, PruneOptions{StartAt: stats.NextBox})
+ mustNotExist(t, st, old...)
+}
+
+func TestPruneNeverDeletesKeysOutsideTheDaysPrefix(t *testing.T) {
+ st := newPruneStore(t)
+ days, _ := BoxPrefix("acme", "shop", "b1")
+ foreign := []string{
+ "apps/acme/shop/logs/b1/2020-01-01.json",
+ "apps/acme/shop/analytics/b2/days/2020-01-01.json", // other box
+ "apps/acme/shop/analytics/b1/days/x/2020-01-01.json",
+ "apps/acme/shop/analytics/b1/2020-01-01.json",
+ "apps/other/shop/analytics/b1/days/2020-01-01.json",
+ "config/2020-01-01.json",
+ days + "../2020-01-01.json",
+ days + "2020-01-01.json/",
+ "2020-01-01.json",
+ "",
+ }
+ for _, k := range foreign {
+ if k != "" && !strings.Contains(k, "..") && !strings.HasSuffix(k, "/") {
+ putKey(t, st, k)
+ }
+ }
+ putKey(t, st, days+"2030-01-01.json") // so the box exists
+ st.dirs = func(prefix string) ([]string, error) {
+ switch prefix {
+ case "apps/":
+ return []string{"apps/acme/"}, nil
+ case "apps/acme/":
+ return []string{"apps/acme/shop/"}, nil
+ }
+ return []string{"apps/acme/shop/analytics/b1/"}, nil
+ }
+ st.page = func(_ context.Context, prefix, after string, limit int) ([]string, error) {
+ // A broken adapter ignores the prefix; keys are sorted and bounded.
+ out := slices.Clone(foreign)
+ slices.Sort(out)
+ out = slices.DeleteFunc(out, func(k string) bool { return k <= after || k == "" })
+ return out[:min(len(out), limit)], nil
+ }
+ l := &pruneLog{}
+ stats, err := Prune(context.Background(), st, pruneNow, PruneOptions{PageSize: 1000, Logf: l.logf})
+ if err != nil {
+ t.Fatalf("Prune: %v", err)
+ }
+ if len(st.deletes) != 0 || stats.Deleted != 0 || stats.DeleteCalls != 0 {
+ t.Fatalf("deleted foreign keys: %v stats %+v", st.deletes, stats)
+ }
+ if stats.Malformed == 0 || !l.has("malformed") {
+ t.Fatalf("foreign keys were not reported: %+v", stats)
+ }
+ for _, k := range foreign {
+ if k != "" && !strings.Contains(k, "..") && !strings.HasSuffix(k, "/") {
+ mustExist(t, st, k)
+ }
+ }
+}
+
+func TestPruneRefusesBrokenPages(t *testing.T) {
+ good := "apps/acme/shop/analytics/b1/days/2020-01-01.json"
+ cases := map[string]func(prefix, after string, limit int) []string{
+ "unsorted": func(p, a string, l int) []string { return []string{p + "2020-01-02.json", good} },
+ "duplicate": func(p, a string, l int) []string { return []string{good, good} },
+ "not after": func(p, a string, l int) []string { return []string{p + "2019-01-01.json"}[:0:0] },
+ "over limit": func(p, a string, l int) []string { return []string{good, p + "2020-01-02.json", p + "2020-01-03.json"} },
+ "empty segment": func(p, a string, l int) []string { return []string{""} },
+ }
+ delete(cases, "not after") // an empty page is legal; covered elsewhere
+ for name, fn := range cases {
+ t.Run(name, func(t *testing.T) {
+ st := newPruneStore(t)
+ putKey(t, st, good)
+ putKey(t, st, "apps/acme/shop/analytics/b1/days/2020-01-02.json")
+ st.page = func(_ context.Context, p, a string, l int) ([]string, error) { return fn(p, a, l), nil }
+ stats, err := Prune(context.Background(), st, pruneNow, PruneOptions{PageSize: 2, Logf: func(string, ...any) {}})
+ if err == nil || !strings.Contains(err.Error(), "invalid page") {
+ t.Fatalf("err = %v, want invalid page", err)
+ }
+ if stats.Deleted != 0 || len(st.deletes) != 0 {
+ t.Fatalf("deleted from a broken page: %+v %v", stats, st.deletes)
+ }
+ mustExist(t, st, good)
+ })
+ }
+}
+
+func TestPruneSkipsUnsafeAccountAppAndBoxSegments(t *testing.T) {
+ st := newPruneStore(t)
+ legit := "apps/acme/shop/analytics/b1/days/2020-01-01.json"
+ putKey(t, st, legit)
+ st.dirs = func(prefix string) ([]string, error) {
+ switch prefix {
+ case "apps/":
+ return []string{"apps/BAD/", "apps/ab/", "apps/acme/", "apps/../", "apps/./", "apps/ac me/", "apps/acme/x/"}, nil
+ case "apps/acme/":
+ return []string{"apps/acme/Shop/", "apps/acme/1shop/", "apps/acme/shop/", "apps/acme/../", "apps/acme/sh_op/", "apps/acme/shop/x/"}, nil
+ case "apps/acme/shop/analytics/":
+ return []string{
+ "apps/acme/shop/analytics/b1/", "apps/acme/shop/analytics/../", "apps/acme/shop/analytics/./",
+ "apps/acme/shop/analytics/a\\b/", "apps/acme/shop/analytics/a/b/", "apps/acme/shop/analytics//",
+ "apps/acme/shop/analytics/", "apps/acme/shop/other/b1/",
+ }, nil
+ }
+ return nil, nil // unsafe accounts/apps must not even be listed
+ }
+ var listed []string
+ st.page = func(ctx context.Context, prefix, after string, limit int) ([]string, error) {
+ listed = append(listed, prefix)
+ return st.inner.ListPage(ctx, prefix, after, limit)
+ }
+ stats, _ := runPrune(t, st, PruneOptions{})
+ if want := []string{"apps/acme/shop/analytics/b1/days/"}; !slices.Equal(listed, want) {
+ t.Fatalf("ListPage prefixes = %v, want %v", listed, want)
+ }
+ mustNotExist(t, st, legit)
+ if stats.Boxes != 1 || stats.Apps != 1 || stats.Malformed == 0 {
+ t.Fatalf("stats = %+v", stats)
+ }
+ for _, k := range st.deletes {
+ if k != legit {
+ t.Fatalf("deleted %q", k)
+ }
+ }
+}
+
+func TestPruneBatchPartialFailureCountsSuccesses(t *testing.T) {
+ b := &batchStore{pruneStore: newPruneStore(t), failing: map[string]bool{}}
+ var old []string
+ for i := 0; i < 4; i++ {
+ k := dayAgo(t, "acme", "shop", "b1", 700+i)
+ putKey(t, b, k)
+ old = append(old, k)
+ }
+ b.failing[old[2]] = true
+ l := &pruneLog{}
+ stats, err := Prune(context.Background(), b, pruneNow, PruneOptions{Logf: l.logf})
+ if err == nil || release.FailedKeys(err)[old[2]] == nil {
+ t.Fatalf("err = %v, want the per-key failure", err)
+ }
+ if stats.Deleted != 3 || stats.Errors != 1 || stats.DeleteCalls != 1 {
+ t.Fatalf("stats = %+v", stats)
+ }
+ mustNotExist(t, b, old[0], old[1], old[3])
+ mustExist(t, b, old[2])
+ // The failed key is retried on the next pass.
+ b.failing = map[string]bool{}
+ stats2, err := Prune(context.Background(), b, pruneNow, PruneOptions{Logf: l.logf})
+ if err != nil || stats2.Deleted != 1 {
+ t.Fatalf("retry: %v %+v", err, stats2)
+ }
+ mustNotExist(t, b, old[2])
+}
+
+func TestPruneBatchWholeCallFailureCountsNothing(t *testing.T) {
+ st := newPruneStore(t)
+ k := dayAgo(t, "acme", "shop", "b1", 700)
+ putKey(t, st, k)
+ w := &wholeFail{pruneStore: st}
+ stats, err := Prune(context.Background(), w, pruneNow, PruneOptions{Logf: func(string, ...any) {}})
+ if err == nil || stats.Deleted != 0 || stats.Errors != 1 {
+ t.Fatalf("err %v stats %+v", err, stats)
+ }
+ mustExist(t, st, k)
+}
+
+type wholeFail struct{ *pruneStore }
+
+func (wholeFail) DeleteKeys(context.Context, []string) error { return errors.New("boom") }
+
+func TestPruneListErrorIsCountedAndOtherBoxesContinue(t *testing.T) {
+ st := newPruneStore(t)
+ b1 := dayAgo(t, "acme", "shop", "b1", 700)
+ b2 := dayAgo(t, "acme", "shop", "b2", 700)
+ putKey(t, st, b1)
+ putKey(t, st, b2)
+ bad, _ := BoxPrefix("acme", "shop", "b1")
+ st.page = func(ctx context.Context, prefix, after string, limit int) ([]string, error) {
+ if prefix == bad {
+ return nil, errors.New("list failed")
+ }
+ return st.inner.ListPage(ctx, prefix, after, limit)
+ }
+ stats, err := Prune(context.Background(), st, pruneNow, PruneOptions{Logf: func(string, ...any) {}})
+ if err == nil || stats.Errors != 1 || stats.Deleted != 1 {
+ t.Fatalf("err %v stats %+v", err, stats)
+ }
+ mustExist(t, st, b1)
+ mustNotExist(t, st, b2)
+}
diff --git a/internal/console/analyticsprune.go b/internal/console/analyticsprune.go
new file mode 100644
index 000000000..624d8d0d7
--- /dev/null
+++ b/internal/console/analyticsprune.go
@@ -0,0 +1,72 @@
+package console
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "log"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/analytics"
+)
+
+const analyticsPruneTimeout = 10 * time.Minute
+
+func normalizeAnalyticsPruneMode(raw string) (string, error) {
+ mode := strings.TrimSpace(raw)
+ switch mode {
+ case "", "off":
+ return "off", nil
+ case "dry-run", "on":
+ return mode, nil
+ default:
+ return "", fmt.Errorf("CONSOLE_ANALYTICS_PRUNE must be off, dry-run or on")
+ }
+}
+
+// analyticsPrunePass rides the existing hourly economics worker. Only this
+// local SQL admission runs on the hourly tick: object listings run at most
+// once in 24 hours, including after a crash or console restart. Recording the
+// attempt before I/O deliberately defers a failed or interrupted pass until
+// tomorrow instead of issuing another bucket sweep on each boot.
+func (s *Server) analyticsPrunePass(ctx context.Context, now time.Time) error {
+ mode, err := normalizeAnalyticsPruneMode(s.cfg.AnalyticsPrune)
+ if err != nil {
+ return err
+ }
+ if mode == "off" || s.cfg.Releases == nil {
+ return nil
+ }
+ if s.cfg.HostClaim {
+ return fmt.Errorf("analytics prune: unavailable on a host-claim console")
+ }
+ ctx, cancel := context.WithTimeout(ctx, analyticsPruneTimeout)
+ defer cancel()
+ var cursor string
+ // One conditional UPDATE is the admission even if two callers arrive
+ // together. The singleton exists from migration; no row means no run.
+ err = s.store.db.QueryRowContext(ctx, `UPDATE analytics_prune_state SET last_started = ?
+ WHERE id = 1 AND (last_started IS NULL OR last_started <= ?)
+ RETURNING next_box`, now.Unix(), now.Add(-24*time.Hour).Unix()).Scan(&cursor)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("analytics prune: daily admission: %w", err)
+ }
+ stats, pruneErr := analytics.Prune(ctx, s.cfg.Releases, now, analytics.PruneOptions{
+ DryRun: mode == "dry-run", PageSize: 1000, MaxDeletes: 10000, MaxKeys: 100000, StartAt: cursor,
+ })
+ log.Printf("console: analytics prune: mode=%s apps=%d boxes=%d keys_listed=%d deleted=%d would_delete=%d skipped_malformed=%d errors=%d list_requests=%d delete_requests=%d next_box=%q",
+ mode, stats.Apps, stats.Boxes, stats.Listed, stats.Deleted, stats.WouldDelete, stats.Malformed, stats.Errors, stats.ListCalls, stats.DeleteCalls, stats.NextBox)
+ // A timeout must not prevent saving progress. This final local write has
+ // its own small deadline, independent of the bucket work's deadline.
+ saveCtx, saveCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer saveCancel()
+ if _, err := s.store.db.ExecContext(saveCtx, `UPDATE analytics_prune_state SET next_box = ? WHERE id = 1 AND last_started = ?`, stats.NextBox, now.Unix()); err != nil {
+ return fmt.Errorf("analytics prune: save progress: %w (pass: %v)", err, pruneErr)
+ }
+ return pruneErr
+}
diff --git a/internal/console/analyticsprune_test.go b/internal/console/analyticsprune_test.go
new file mode 100644
index 000000000..6d3b78a33
--- /dev/null
+++ b/internal/console/analyticsprune_test.go
@@ -0,0 +1,144 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/analytics"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestAnalyticsPruneDailyAndRestart(t *testing.T) {
+ ctx := context.Background()
+ now := time.Date(2026, 11, 11, 18, 0, 0, 0, time.UTC)
+ path := filepath.Join(t.TempDir(), "console.db")
+ db, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := release.NewDirStore(t.TempDir())
+ key, _ := analytics.DayKey("bab", "shop", "box-1", now.AddDate(0, 0, -401).Format("2006-01-02"))
+ put := func() {
+ t.Helper()
+ if _, err := st.Put(ctx, key, []byte("{}"), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ exists := func(want bool) {
+ t.Helper()
+ _, _, err := st.Get(ctx, key)
+ if (err == nil) != want || err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("exists=%v: %v", want, err)
+ }
+ }
+ srv := &Server{store: db, cfg: Config{Releases: st, AnalyticsPrune: "on"}}
+ put()
+ if err := srv.analyticsPrunePass(ctx, now); err != nil {
+ t.Fatal(err)
+ }
+ exists(false)
+ put()
+ if err := srv.analyticsPrunePass(ctx, now.Add(23*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ exists(true)
+ if err := db.Close(); err != nil {
+ t.Fatal(err)
+ }
+ db, err = Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ srv.store = db
+ if err := srv.analyticsPrunePass(ctx, now.Add(23*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ exists(true)
+ if err := srv.analyticsPrunePass(ctx, now.Add(24*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ exists(false)
+}
+
+func TestAnalyticsPruneModes(t *testing.T) {
+ for _, mode := range []string{"", "off", "dry-run", "on", "invalid"} {
+ t.Run(mode, func(t *testing.T) {
+ ctx := context.Background()
+ now := time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC)
+ st := release.NewDirStore(t.TempDir())
+ key, _ := analytics.DayKey("bab", "shop", "box-1", "2020-01-01")
+ if _, err := st.Put(ctx, key, []byte("{}"), ""); err != nil {
+ t.Fatal(err)
+ }
+ db := openTestStore(t)
+ srv := &Server{store: db, cfg: Config{Releases: st, AnalyticsPrune: mode}}
+ err := srv.analyticsPrunePass(ctx, now)
+ if (err != nil) != (mode == "invalid") {
+ t.Fatalf("mode %q: %v", mode, err)
+ }
+ _, _, err = st.Get(ctx, key)
+ if mode == "on" {
+ if !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ } else if err != nil {
+ t.Fatal(err)
+ }
+ var stamp *int64
+ if err := db.db.QueryRowContext(ctx, `SELECT last_started FROM analytics_prune_state WHERE id=1`).Scan(&stamp); err != nil {
+ t.Fatal(err)
+ }
+ if (stamp != nil) != (mode == "on" || mode == "dry-run") {
+ t.Fatalf("mode %q stamp=%v", mode, stamp)
+ }
+ })
+ }
+}
+
+// The admission is persisted before I/O even when the store fails. Concurrent
+// attempts and a restart must not turn a failing LIST into repeated paid work.
+func TestAnalyticsPruneFailedAttemptAndConcurrentAdmission(t *testing.T) {
+ db := openTestStore(t)
+ base := release.NewDirStore(t.TempDir())
+ st := &pruneFailListingStore{DirStore: base}
+ srv := &Server{store: db, cfg: Config{Releases: st, AnalyticsPrune: "on"}}
+ now := time.Now()
+ var wg sync.WaitGroup
+ for i := 0; i < 4; i++ {
+ wg.Add(1)
+ go func() { defer wg.Done(); _ = srv.analyticsPrunePass(context.Background(), now) }()
+ }
+ wg.Wait()
+ if st.calls != 1 {
+ t.Fatalf("LISTs=%d, want one", st.calls)
+ }
+ if err := srv.analyticsPrunePass(context.Background(), now.Add(time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if st.calls != 1 {
+ t.Fatalf("second pass listed: %d", st.calls)
+ }
+}
+
+type pruneFailListingStore struct {
+ *release.DirStore
+ calls int
+}
+
+func (s *pruneFailListingStore) ListDirs(context.Context, string) ([]string, error) {
+ s.calls++
+ return nil, errors.New("test LIST failure")
+}
+
+func TestAnalyticsPruneHostClaimRefuses(t *testing.T) {
+ srv := &Server{cfg: Config{HostClaim: true, AnalyticsPrune: "on", Releases: release.NewDirStore(t.TempDir())}}
+ if err := srv.analyticsPrunePass(context.Background(), time.Now()); err == nil {
+ t.Fatal("host-claim mutation was not refused")
+ }
+}
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go
index 0f2699b1f..ad0aa06b2 100644
--- a/internal/console/economicspass.go
+++ b/internal/console/economicspass.go
@@ -57,6 +57,10 @@ func (s *Server) StartEconomicsPass(ctx context.Context) {
// a failed stage logs and the next still runs, because a missing census day
// must not cost the month's statements (spec: error handling).
func (s *Server) economicsPass(ctx context.Context, now time.Time) error {
+ if err := s.analyticsPrunePass(ctx, now); err != nil {
+ log.Printf("console: analytics prune: %v", err)
+ jobFailed(ctx, err)
+ }
date := usage.DayOf(now)
if err := s.censusPass(ctx, date); err != nil {
log.Printf("console: census pass %s: %v", date, err)
diff --git a/internal/console/server.go b/internal/console/server.go
index d8b6f6032..5b0a4980f 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -532,6 +532,9 @@ const (
// Config is everything the server reads its world through.
type Config struct {
+ // AnalyticsPrune selects off (default), dry-run or on for daily analytics retention.
+ AnalyticsPrune string
+
Demo demo.Config
DemoAlerts DemoAlertConfig
Registrar registrar.Registrar
@@ -1825,6 +1828,14 @@ func normalizeDelegationZone(raw string) string {
// NewServer wires a server over an opened Store, loading (or minting) the
// console's Keymail signing key.
func NewServer(cfg Config, st *Store) (*Server, error) {
+ pruneMode, pruneErr := normalizeAnalyticsPruneMode(cfg.AnalyticsPrune)
+ if pruneErr != nil {
+ return nil, pruneErr
+ }
+ if cfg.HostClaim && pruneMode != "off" {
+ return nil, fmt.Errorf("analytics prune: unavailable on a host-claim console")
+ }
+ cfg.AnalyticsPrune = pruneMode
demoAPIOrigin, err := validateDemoAPIOrigin(cfg.DemoAPIOrigin)
if err != nil {
return nil, err
diff --git a/internal/console/store.go b/internal/console/store.go
index d2fa3e94b..d14a28835 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -166,6 +166,12 @@ func (s *Store) Close() error {
// stays idempotent.
func (s *Store) migrate() error {
for _, stmt := range []string{
+ `CREATE TABLE IF NOT EXISTS analytics_prune_state (
+ id INTEGER PRIMARY KEY CHECK(id = 1),
+ last_started INTEGER,
+ next_box TEXT NOT NULL DEFAULT ''
+ );`,
+ `INSERT INTO analytics_prune_state(id) VALUES(1) ON CONFLICT(id) DO NOTHING;`,
`CREATE TABLE IF NOT EXISTS owners (
address TEXT NOT NULL,
app TEXT NOT NULL,
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index 1eaa8ffa1..b55cf4e94 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -295,6 +295,8 @@ var claimSQLTables = map[string]claimSQLTable{
"managed_fleet_delivered_keys": {NonApp: "fleet access key IDs ever delivered to boxes; no app identity"},
+ "analytics_prune_state": {NonApp: "the console retention sweep clock and resume position; no app lifecycle authority"},
+
// The alert engine's tables (alertstore.go). A scope is "fleet" or an
// account; subjects name boxes, services and apps as message text only.
"alert_connectors": {NonApp: "alert destinations, keyed by id and owned by a scope (fleet or an account); names no app"},