carlos / platform Public

host: operator log retention; prune cost flat in retention

CARLOS_LOG_RETENTION_DAYS (whole days, default 7) and
CARLOS_LOG_RETENTION_MB (whole MiB per app per box, default 50, or off)
set how much of each app's shipped logs and errors a box keeps. Unset
behaves exactly as before; a refused value is logged and keeps its
default. Both are on the host.env allowlist.

The hourly prune used to LIST every hour it kept, every hour (~2,160
LISTs per app per box per hour at 90 days). pruneLedger now walks once
per process and once a day, learns this box's own writes from the
flush, and LISTs only the hours it deletes: steady state is one
ListDirs per app per hour.

Slice 1 of discussion #1024.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev fddc42f1aa53b41b38ef1b6cbddc3e492bfb0c3e parent c48e91e
9 files changed, +544 −89
  • internal/host/agent.go +5 −0
  • internal/host/applessroute_test.go +4 −4
  • internal/host/errship.go +5 −3
  • internal/host/errship_test.go +4 −4
  • internal/host/logretention.go +226 −0
  • internal/host/logretention_test.go +278 −0
  • internal/host/logship.go +14 −72
  • internal/host/logship_test.go +6 −6
  • internal/hostenv/hostenv.go +2 −0

CI cancelled — superseded by a newer push — run details

diff --git a/internal/host/agent.go b/internal/host/agent.go
index 3e3f3e5b9..30782f1f2 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -101,6 +101,11 @@
// when no layout intent is recorded, nested|flat (default nested;
// isolated-exec design §8.6, "Nested by default"). Nested applies only
// on a box whose isolation is ready; a recorded intent always wins.
+// - CARLOS_LOG_RETENTION_DAYS / CARLOS_LOG_RETENTION_MB — how long and
+// how much of each app's shipped logs and errors this box keeps
+// (logretention.go): whole days, default 7; whole MiB per app per
+// family, default 50, or off for no byte cap. A refused value is
+// logged and keeps its default.
// - STATUS_HOST / STATUS_PUBLIC — NOT read anywhere in this file. They
// gate whether ops/tofu fronts the bucket's published status/ prefix
// with a public hostname; recorded here only so the fleet status
diff --git a/internal/host/applessroute_test.go b/internal/host/applessroute_test.go
index 840851c4b..0e2721b51 100644
--- a/internal/host/applessroute_test.go
+++ b/internal/host/applessroute_test.go
@@ -142,13 +142,13 @@ func TestErrshipAppLessRouteWritesNothing(t *testing.T) {
if _, ok := pending[applog.AppKey{Acct: "bab", App: ""}]; !ok {
t.Fatalf("round %d: the edge did not file the app-less route under (bab, \"\"); pending = %v", round, pending)
}
- errshipFlush(ctx, s, pending)
+ errshipFlush(ctx, s, pending, nil)
if len(pending) != 0 {
t.Fatalf("round %d: pending after flush = %v; a refused key must drop, not hold forever", round, pending)
}
}
for _, k := range errshipKnownApps(pending, sink) {
- chunkPrune(ctx, s, applog.FamilyErrors, "leo-climbing", k, time.Now())
+ newPruneLedger(applog.FamilyErrors, "leo-climbing", defaultLogRetention).prune(ctx, s, k, time.Now())
}
var webPuts int
@@ -177,11 +177,11 @@ func TestLogshipAndAnalyticsDropAppLessRecords(t *testing.T) {
bad := applog.AppKey{Acct: "bab", App: ""}
pending := map[applog.AppKey][]applog.Record{bad: {{TS: time.Now(), Box: "box1", Seq: 1, Msg: "x"}}}
- logshipFlush(ctx, s, pending)
+ logshipFlush(ctx, s, pending, nil)
if len(pending) != 0 {
t.Fatalf("logship pending = %v", pending)
}
- chunkPrune(ctx, s, applog.FamilyLogs, "box1", bad, time.Now())
+ newPruneLedger(applog.FamilyLogs, "box1", defaultLogRetention).prune(ctx, s, bad, time.Now())
now := time.Date(2026, 10, 16, 6, 46, 0, 0, time.UTC)
am := analytics.NewMeter(t.TempDir(), "box1", func() time.Time { return now })
diff --git a/internal/host/errship.go b/internal/host/errship.go
index 2d2aede3d..d5adde012 100644
--- a/internal/host/errship.go
+++ b/internal/host/errship.go
@@ -41,16 +41,17 @@ func errshipLoop(sink *apperr.Sink, box string) {
}
log.Printf("agent: errship loop armed (10s ticks), publishing to %s", target)
+ ledger := newPruneLedger(applog.FamilyErrors, box, logRetentionFromEnv(os.Getenv))
pending := make(map[applog.AppKey][]apperr.Record)
pruned := ""
ticker := time.NewTicker(errshipTick)
defer ticker.Stop()
for range ticker.C {
errshipGather(sink, pending)
- errshipFlush(ctx, s, pending)
+ errshipFlush(ctx, s, pending, ledger)
if hour := applog.HourOf(time.Now()); hour != pruned {
for _, k := range errshipKnownApps(pending, sink) {
- chunkPrune(ctx, s, applog.FamilyErrors, box, k, time.Now())
+ ledger.prune(ctx, s, k, time.Now())
}
pruned = hour
}
@@ -71,7 +72,7 @@ func errshipGather(sink *apperr.Sink, pending map[applog.AppKey][]apperr.Record)
// errshipFlush writes one create-only chunk per pending app and forgets
// what landed; a failed app keeps its records for the next round.
-func errshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKey][]apperr.Record) {
+func errshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKey][]apperr.Record, ledger *pruneLedger) {
for k, recs := range pending {
if len(recs) == 0 || strings.HasPrefix(k.App, demo.AppPrefix) {
delete(pending, k)
@@ -93,6 +94,7 @@ func errshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKe
log.Printf("agent: errship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs))
continue
}
+ ledger.wrote(k, key, len(body))
delete(pending, k)
}
}
diff --git a/internal/host/errship_test.go b/internal/host/errship_test.go
index 3bd6ae8ad..1808b48f4 100644
--- a/internal/host/errship_test.go
+++ b/internal/host/errship_test.go
@@ -22,11 +22,11 @@ func TestErrshipFlushDropsDemoApps(t *testing.T) {
if known := errshipKnownApps(pending, sink); len(known) != 1 || known[0].App != "web" {
t.Fatalf("prune worklist should hold only the ordinary app: %v", known)
}
- errshipFlush(t.Context(), failingStore{}, pending)
+ errshipFlush(t.Context(), failingStore{}, pending, nil)
if len(pending) != 1 || len(pending[applog.AppKey{Acct: "bab", App: "web"}]) != 1 {
t.Fatalf("only ordinary app should remain pending: %v", pending)
}
- errshipFlush(t.Context(), s, pending)
+ errshipFlush(t.Context(), s, pending, nil)
keys, err := s.List(t.Context(), "apps/")
if err != nil || len(keys) != 1 || !strings.HasPrefix(keys[0], "apps/bab/web/errors/") || len(pending) != 0 {
t.Fatalf("flush: keys %v, pending %v, err %v", keys, pending, err)
@@ -41,7 +41,7 @@ func TestErrshipFlushWritesOneChunkPerApp(t *testing.T) {
sink.Add("bab", "web", apperr.Record{Source: apperr.SourceEdge, Kind: apperr.KindHTTP, Name: "500 GET /x", Host: "h1"})
pending := map[applog.AppKey][]apperr.Record{}
errshipGather(sink, pending)
- errshipFlush(context.Background(), s, pending)
+ errshipFlush(context.Background(), s, pending, nil)
if len(pending) != 0 {
t.Fatalf("pending after flush = %d", len(pending))
}
@@ -53,7 +53,7 @@ func TestErrshipFlushWritesOneChunkPerApp(t *testing.T) {
func TestErrshipFlushHoldsOnFailure(t *testing.T) {
pending := map[applog.AppKey][]apperr.Record{{Acct: "bab", App: "web"}: {{TS: time.Now(), Source: apperr.SourceEdge, Name: "x", FP: "f", Box: "box1", Seq: 1}}}
- errshipFlush(context.Background(), failingStore{}, pending)
+ errshipFlush(context.Background(), failingStore{}, pending, nil)
if len(pending) != 1 {
t.Fatal("a failed flush must keep its records for the next round")
}
diff --git a/internal/host/logretention.go b/internal/host/logretention.go
new file mode 100644
index 000000000..5737045cb
--- /dev/null
+++ b/internal/host/logretention.go
@@ -0,0 +1,226 @@
+// Log retention: how long, and how much, one box keeps of one app's shipped
+// chunks (discussion #1024, slice 1). Both chunk families the box prunes,
+// logs and errors, follow it (errors spec §3.6: errors follow log
+// retention). The operator sets it in host.env; the defaults are what the
+// constants were before the settings existed, so an unset box behaves as
+// it always did.
+//
+// The prune's cost no longer grows with retention. It used to LIST every
+// hour it kept, every hour: ~168 LISTs per app per box per hour at 7 days,
+// ~2,160 at 90. pruneLedger remembers each hour's size after one walk,
+// adds what this box's own flushes write, and LISTs only the hours it
+// deletes. Steady state is one ListDirs per app per hour, plus a full
+// re-walk once a day to correct any drift (an ambiguous Put that landed
+// after reporting failure).
+package host
+
+import (
+ "context"
+ "log"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const (
+ logRetentionDaysEnv = "CARLOS_LOG_RETENTION_DAYS"
+ logRetentionMBEnv = "CARLOS_LOG_RETENTION_MB"
+
+ // The ceilings refuse a typo, not a policy: ten years, one TiB per app
+ // per box.
+ logRetentionMaxDays = 3660
+ logRetentionMaxMB = 1 << 20
+
+ // pruneRewalk is how often the ledger forgets its sizes and LISTs every
+ // hour again. Once a day bounds the drift the ledger can carry while
+ // keeping the walk's cost to 1/24 of what every pass used to pay.
+ pruneRewalk = 24 * time.Hour
+)
+
+// logRetention is one box's retention for one app's chunks per family.
+type logRetention struct {
+ maxAge time.Duration
+ maxBytes int64 // 0 = no byte cap ("off")
+}
+
+var defaultLogRetention = logRetention{maxAge: 7 * 24 * time.Hour, maxBytes: 50 << 20}
+
+// logRetentionFromEnv reads the two settings. Each falls back to its default
+// on its own when unset or refused, and a refusal is logged: an operator's
+// typo must never stop the agent, and must never pass silently either
+// (logRejectedAlertOverrides' rule).
+func logRetentionFromEnv(getenv func(string) string) logRetention {
+ r := defaultLogRetention
+ if v := strings.TrimSpace(getenv(logRetentionDaysEnv)); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= logRetentionMaxDays {
+ r.maxAge = time.Duration(n) * 24 * time.Hour
+ } else {
+ log.Printf("agent: %s=%q ignored: want whole days, 1-%d; keeping %d days", logRetentionDaysEnv, v, logRetentionMaxDays, int(defaultLogRetention.maxAge/(24*time.Hour)))
+ }
+ }
+ if v := strings.TrimSpace(getenv(logRetentionMBEnv)); v != "" {
+ if strings.EqualFold(v, "off") {
+ r.maxBytes = 0
+ } else if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= logRetentionMaxMB {
+ r.maxBytes = int64(n) << 20
+ } else {
+ log.Printf("agent: %s=%q ignored: want whole MiB, 1-%d, or off; keeping %d", logRetentionMBEnv, v, logRetentionMaxMB, defaultLogRetention.maxBytes>>20)
+ }
+ }
+ return r
+}
+
+func (r logRetention) String() string {
+ limit := "no byte cap"
+ if r.maxBytes > 0 {
+ limit = strconv.FormatInt(r.maxBytes>>20, 10) + " MiB per app"
+ }
+ return strconv.Itoa(int(r.maxAge/(24*time.Hour))) + " days, " + limit
+}
+
+// pruneLedger enforces retention for one family on THIS box's subtrees only;
+// each box owns what it wrote (logs spec §5). It belongs to one shipping
+// loop's goroutine and is not safe for concurrent use.
+type pruneLedger struct {
+ fam applog.Family
+ box string
+ ret logRetention
+ apps map[applog.AppKey]*hourSizes
+}
+
+// hourSizes is one app's hour directories (full prefixes, "/"-terminated)
+// and their key-embedded byte totals, as of walked plus this box's writes.
+type hourSizes struct {
+ walked time.Time
+ bytes map[string]int64
+}
+
+func newPruneLedger(fam applog.Family, box string, ret logRetention) *pruneLedger {
+ return &pruneLedger{fam: fam, box: box, ret: ret, apps: map[applog.AppKey]*hourSizes{}}
+}
+
+// wrote records a chunk this box's flush has just put. Before the app's
+// first walk there is nothing to add to; the walk will LIST it. A nil
+// ledger (tests that only flush) ignores it.
+func (l *pruneLedger) wrote(k applog.AppKey, key string, size int) {
+ if l == nil {
+ return
+ }
+ h := l.apps[k]
+ if h == nil {
+ return
+ }
+ i := strings.LastIndexByte(key, '/')
+ if i < 0 {
+ return
+ }
+ h.bytes[key[:i+1]] += int64(size)
+}
+
+// prune drops k's hours that are older than the age floor or, oldest first,
+// that keep the subtree over the byte cap. Hour granularity. Errors are
+// logged and left for the next hourly pass; retention is idempotent.
+func (l *pruneLedger) prune(ctx context.Context, s release.Store, k applog.AppKey, now time.Time) {
+ prefix, err := applog.FamilyBoxPrefix(l.fam, k.Acct, k.App, l.box)
+ if err != nil {
+ unshippable(l.fam, k, err)
+ return
+ }
+ dirs, err := s.ListDirs(ctx, prefix)
+ if err != nil {
+ log.Printf("agent: logship prune %s: %v", prefix, err)
+ return
+ }
+ // Hour names are zero-padded UTC, so lexical order is chronological and
+ // dirs[0] is the oldest.
+ slices.Sort(dirs)
+
+ var sizes map[string]int64
+ var total int64
+ if l.ret.maxBytes > 0 {
+ h := l.apps[k]
+ if h == nil || now.Sub(h.walked) >= pruneRewalk {
+ delete(l.apps, k)
+ h = &hourSizes{walked: now, bytes: make(map[string]int64, len(dirs))}
+ for _, dir := range dirs {
+ n, ok := l.sizeOf(ctx, s, dir)
+ if !ok {
+ return // walk again next pass; nothing deleted on a partial view
+ }
+ h.bytes[dir] = n
+ }
+ l.apps[k] = h
+ } else {
+ // Forget hours that are gone (deleted by another pass, such as
+ // the app's deletion sweep); size any hour the ledger has not
+ // seen. After a walk every write goes through wrote, so the
+ // second case is rare.
+ listed := make(map[string]bool, len(dirs))
+ for _, dir := range dirs {
+ listed[dir] = true
+ if _, ok := h.bytes[dir]; !ok {
+ n, ok := l.sizeOf(ctx, s, dir)
+ if !ok {
+ return
+ }
+ h.bytes[dir] = n
+ }
+ }
+ for dir := range h.bytes {
+ if !listed[dir] {
+ delete(h.bytes, dir)
+ }
+ }
+ }
+ sizes = h.bytes
+ for _, dir := range dirs {
+ total += sizes[dir]
+ }
+ }
+
+ cutoff := now.Add(-l.ret.maxAge)
+ for _, dir := range dirs {
+ over := l.ret.maxBytes > 0 && total > l.ret.maxBytes
+ if !applog.HourBefore(applog.HourNameOfDir(dir), cutoff) && !over {
+ break // oldest first: nothing further is droppable
+ }
+ keys, err := s.List(ctx, dir)
+ if err != nil {
+ log.Printf("agent: logship prune %s: %v", dir, err)
+ return
+ }
+ for _, key := range keys {
+ if err := s.Delete(ctx, key); err != nil {
+ log.Printf("agent: logship prune %s: %v", key, err)
+ // The hour is half gone; walk again next pass rather than
+ // trust a size that no longer matches.
+ delete(l.apps, k)
+ return
+ }
+ }
+ if sizes != nil {
+ total -= sizes[dir]
+ delete(sizes, dir)
+ }
+ }
+}
+
+// sizeOf LISTs one hour directory and totals its key-embedded sizes.
+func (l *pruneLedger) sizeOf(ctx context.Context, s release.Store, dir string) (int64, bool) {
+ keys, err := s.List(ctx, dir)
+ if err != nil {
+ log.Printf("agent: logship prune %s: %v", dir, err)
+ return 0, false
+ }
+ var b int64
+ for _, key := range keys {
+ if n, ok := applog.ChunkKeySize(key); ok {
+ b += n
+ }
+ }
+ return b, true
+}
diff --git a/internal/host/logretention_test.go b/internal/host/logretention_test.go
new file mode 100644
index 000000000..c10cbc190
--- /dev/null
+++ b/internal/host/logretention_test.go
@@ -0,0 +1,278 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestLogRetentionFromEnv(t *testing.T) {
+ t.Parallel()
+ day := 24 * time.Hour
+ for _, tc := range []struct {
+ days, mb string
+ want logRetention
+ }{
+ {"", "", defaultLogRetention},
+ {"90", "", logRetention{maxAge: 90 * day, maxBytes: 50 << 20}},
+ {" 30 ", "2048", logRetention{maxAge: 30 * day, maxBytes: 2048 << 20}},
+ {"", "off", logRetention{maxAge: 7 * day, maxBytes: 0}},
+ {"365", "OFF", logRetention{maxAge: 365 * day, maxBytes: 0}},
+ {"3660", "1048576", logRetention{maxAge: 3660 * day, maxBytes: 1 << 40}},
+ // Refusals keep that setting's default and leave the other alone.
+ {"0", "100", logRetention{maxAge: 7 * day, maxBytes: 100 << 20}},
+ {"-1", "", defaultLogRetention},
+ {"7d", "", defaultLogRetention},
+ {"1.5", "", defaultLogRetention},
+ {"3661", "", defaultLogRetention},
+ {"14", "0", logRetention{maxAge: 14 * day, maxBytes: 50 << 20}},
+ {"", "50MB", defaultLogRetention},
+ {"", "1048577", defaultLogRetention},
+ } {
+ env := map[string]string{logRetentionDaysEnv: tc.days, logRetentionMBEnv: tc.mb}
+ if got := logRetentionFromEnv(func(k string) string { return env[k] }); got != tc.want {
+ t.Errorf("days=%q mb=%q: got %+v, want %+v", tc.days, tc.mb, got, tc.want)
+ }
+ }
+}
+
+// pruneCountStore counts the requests the prune pays for.
+type pruneCountStore struct {
+ release.Store
+ lists, listDirs, deletes int
+ failDelete bool
+}
+
+func (c *pruneCountStore) List(ctx context.Context, prefix string) ([]string, error) {
+ c.lists++
+ return c.Store.List(ctx, prefix)
+}
+
+// ListDirs answers as S3 does: a prefix with no keys left under it is not
+// a directory. DirStore keeps the emptied directory; its LISTs are local
+// reads, so the cost this file tests is S3's.
+func (c *pruneCountStore) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ c.listDirs++
+ dirs, err := c.Store.ListDirs(ctx, prefix)
+ if err != nil {
+ return nil, err
+ }
+ var out []string
+ for _, d := range dirs {
+ if keys, err := c.Store.List(ctx, d); err != nil || len(keys) > 0 {
+ out = append(out, d)
+ }
+ }
+ return out, nil
+}
+
+func (c *pruneCountStore) Delete(ctx context.Context, key string) error {
+ c.deletes++
+ if c.failDelete {
+ return errors.New("delete refused")
+ }
+ return c.Store.Delete(ctx, key)
+}
+
+func (c *pruneCountStore) reset() { c.lists, c.listDirs, c.deletes = 0, 0, 0 }
+
+type pruneFixture struct {
+ t *testing.T
+ s *pruneCountStore
+ k applog.AppKey
+ seq uint64
+}
+
+func newPruneFixture(t *testing.T) *pruneFixture {
+ return &pruneFixture{t: t, s: &pruneCountStore{Store: release.NewDirStore(t.TempDir())}, k: applog.AppKey{Acct: "bde", App: "shop"}}
+}
+
+// put writes a chunk straight into the store, behind the ledger's back.
+func (f *pruneFixture) put(box string, at time.Time, size int) string {
+ f.t.Helper()
+ f.seq++
+ key := mustKey(f.t)(applog.ChunkKey(f.k.Acct, f.k.App, box, applog.HourOf(at), f.seq, size))
+ if _, err := f.s.Store.Put(context.Background(), key, make([]byte, size), ""); err != nil {
+ f.t.Fatal(err)
+ }
+ return key
+}
+
+func (f *pruneFixture) exists(key string) bool {
+ _, _, err := f.s.Store.Get(context.Background(), key)
+ return err == nil
+}
+
+// TestPruneCostFlatInRetention: the first pass walks every hour once; after
+// that a pass LISTs only the hour it deletes, where the old prune LISTed
+// every hour it kept, every hour (2,160 at 90 days). 14 days keeps the
+// fixture quick; the counts do not depend on the length.
+func TestPruneCostFlatInRetention(t *testing.T) {
+ t.Parallel()
+ f := newPruneFixture(t)
+ ctx := context.Background()
+ now := time.Date(2026, 11, 14, 12, 30, 0, 0, time.UTC)
+ const hours = 14 * 24
+ keys := make([]string, hours)
+ for i := range hours { // i = 0 is the oldest, 14 days back
+ keys[i] = f.put("box1", now.Add(-time.Duration(hours-1-i)*time.Hour), 100)
+ }
+ l := newPruneLedger(applog.FamilyLogs, "box1", logRetention{maxAge: 14 * 24 * time.Hour, maxBytes: 1 << 30})
+
+ l.prune(ctx, f.s, f.k, now)
+ if f.s.listDirs != 1 || f.s.lists != hours || f.s.deletes != 0 {
+ t.Fatalf("first pass: listDirs=%d lists=%d deletes=%d, want 1, %d, 0", f.s.listDirs, f.s.lists, f.s.deletes, hours)
+ }
+
+ f.s.reset()
+ // Two hours on, the oldest hour has ended before the cutoff; the next
+ // has not.
+ l.prune(ctx, f.s, f.k, now.Add(2*time.Hour))
+ if f.s.listDirs != 1 || f.s.lists != 1 || f.s.deletes != 1 {
+ t.Fatalf("steady pass: listDirs=%d lists=%d deletes=%d, want 1, 1, 1", f.s.listDirs, f.s.lists, f.s.deletes)
+ }
+ if f.exists(keys[0]) || !f.exists(keys[1]) {
+ t.Fatalf("age floor: oldest survived=%v, next survived=%v; want false, true", f.exists(keys[0]), f.exists(keys[1]))
+ }
+
+ f.s.reset()
+ l.prune(ctx, f.s, f.k, now.Add(2*time.Hour)) // nothing more due
+ if f.s.listDirs != 1 || f.s.lists != 0 || f.s.deletes != 0 {
+ t.Fatalf("idle pass: listDirs=%d lists=%d deletes=%d, want 1, 0, 0", f.s.listDirs, f.s.lists, f.s.deletes)
+ }
+}
+
+// TestPruneByteCapCountsOwnWrites: the ledger learns this box's own writes
+// from the flush, so the byte cap holds without re-LISTing hours it already
+// knows.
+func TestPruneByteCapCountsOwnWrites(t *testing.T) {
+ t.Parallel()
+ f := newPruneFixture(t)
+ ctx := context.Background()
+ now := time.Date(2026, 11, 14, 12, 30, 0, 0, time.UTC)
+ oldest := f.put("box1", now.Add(-3*time.Hour), 400)
+ middle := f.put("box1", now.Add(-2*time.Hour), 400)
+ other := f.put("box2", now.Add(-3*time.Hour), 400) // not ours
+ l := newPruneLedger(applog.FamilyLogs, "box1", logRetention{maxAge: 30 * 24 * time.Hour, maxBytes: 801})
+ l.prune(ctx, f.s, f.k, now) // walk: 800 of 801
+ if !f.exists(oldest) || !f.exists(middle) {
+ t.Fatal("under the cap, something went")
+ }
+
+ // The flush writes a chunk into the current hour, through the ledger.
+ pending := map[applog.AppKey][]applog.Record{f.k: {{TS: now, Box: "box1", Seq: 99, Msg: "hello"}}}
+ logshipFlush(ctx, f.s, pending, l)
+ if len(pending) != 0 {
+ t.Fatalf("flush held records: %v", pending)
+ }
+
+ f.s.reset()
+ l.prune(ctx, f.s, f.k, now)
+ if f.exists(oldest) || !f.exists(middle) || !f.exists(other) {
+ t.Fatalf("over the cap: oldest=%v middle=%v other box=%v; want false, true, true", f.exists(oldest), f.exists(middle), f.exists(other))
+ }
+ // One hour dropped: one LIST for it, none to size anything.
+ if f.s.lists != 1 {
+ t.Fatalf("lists = %d, want 1 (the dropped hour only)", f.s.lists)
+ }
+}
+
+// TestPruneRewalkCorrectsDrift: a chunk the ledger never heard of (a Put that
+// landed after reporting failure) is invisible to the cap until the daily
+// re-walk, and counted after it.
+func TestPruneRewalkCorrectsDrift(t *testing.T) {
+ t.Parallel()
+ f := newPruneFixture(t)
+ ctx := context.Background()
+ now := time.Date(2026, 11, 14, 12, 30, 0, 0, time.UTC)
+ old := f.put("box1", now.Add(-5*time.Hour), 400)
+ l := newPruneLedger(applog.FamilyLogs, "box1", logRetention{maxAge: 30 * 24 * time.Hour, maxBytes: 1000})
+ l.prune(ctx, f.s, f.k, now)
+
+ f.put("box1", now.Add(-5*time.Hour), 800) // same, known hour; ledger unaware
+ l.prune(ctx, f.s, f.k, now.Add(time.Hour))
+ if !f.exists(old) {
+ t.Fatal("dropped before the re-walk could have seen the drift")
+ }
+ l.prune(ctx, f.s, f.k, now.Add(pruneRewalk))
+ if f.exists(old) {
+ t.Fatal("the re-walk did not count the unrecorded chunk")
+ }
+}
+
+// TestPruneNoByteCap: MB=off keeps everything inside the age floor however
+// large, and never sizes an hour.
+func TestPruneNoByteCap(t *testing.T) {
+ t.Parallel()
+ f := newPruneFixture(t)
+ ctx := context.Background()
+ now := time.Date(2026, 11, 14, 12, 30, 0, 0, time.UTC)
+ aged := f.put("box1", now.Add(-8*24*time.Hour), 10)
+ var big []string
+ for i := 1; i <= 3; i++ {
+ big = append(big, f.put("box1", now.Add(-time.Duration(i)*time.Hour), 60<<20))
+ }
+ l := newPruneLedger(applog.FamilyLogs, "box1", logRetention{maxAge: 7 * 24 * time.Hour})
+ l.prune(ctx, f.s, f.k, now)
+ if f.exists(aged) {
+ t.Fatal("past the age floor, survived")
+ }
+ for _, k := range big {
+ if !f.exists(k) {
+ t.Fatalf("%s went with no byte cap", k)
+ }
+ }
+ if f.s.lists != 1 {
+ t.Fatalf("lists = %d, want 1 (the aged hour only)", f.s.lists)
+ }
+}
+
+// TestPruneDeleteFailureForgetsSizes: a half-deleted hour makes the ledger
+// walk again rather than trust sizes that no longer match.
+func TestPruneDeleteFailureForgetsSizes(t *testing.T) {
+ t.Parallel()
+ f := newPruneFixture(t)
+ ctx := context.Background()
+ now := time.Date(2026, 11, 14, 12, 30, 0, 0, time.UTC)
+ for i := range 3 {
+ f.put("box1", now.Add(-time.Duration(i)*time.Hour), 600)
+ }
+ l := newPruneLedger(applog.FamilyLogs, "box1", logRetention{maxAge: 30 * 24 * time.Hour, maxBytes: 1000})
+ f.s.failDelete = true
+ l.prune(ctx, f.s, f.k, now)
+ if _, ok := l.apps[f.k]; ok {
+ t.Fatal("ledger kept its sizes after a failed delete")
+ }
+ f.s.failDelete = false
+ f.s.reset()
+ l.prune(ctx, f.s, f.k, now)
+ if f.s.lists != 3+2 { // walk all three, then LIST the two it drops
+ t.Fatalf("lists = %d, want 5 (re-walk plus two drops)", f.s.lists)
+ }
+ left, err := f.s.Store.List(ctx, mustKey(t)(applog.FamilyBoxPrefix(applog.FamilyLogs, f.k.Acct, f.k.App, "box1")))
+ if err != nil || len(left) != 1 {
+ t.Fatalf("chunks left = %v (%v), want 1", left, err)
+ }
+}
+
+// TestPruneLedgersArePerFamily: the errors loop's ledger never sees the logs
+// loop's writes, and each prunes only its own family.
+func TestPruneLedgersArePerFamily(t *testing.T) {
+ t.Parallel()
+ f := newPruneFixture(t)
+ ctx := context.Background()
+ now := time.Date(2026, 11, 14, 12, 30, 0, 0, time.UTC)
+ logKey := f.put("box1", now.Add(-8*24*time.Hour), 10)
+ errKey := mustKey(t)(applog.FamilyChunkKey(applog.FamilyErrors, f.k.Acct, f.k.App, "box1", applog.HourOf(now.Add(-8*24*time.Hour)), 1, 10))
+ if _, err := f.s.Store.Put(ctx, errKey, make([]byte, 10), ""); err != nil {
+ t.Fatal(err)
+ }
+ newPruneLedger(applog.FamilyErrors, "box1", defaultLogRetention).prune(ctx, f.s, f.k, now)
+ if f.exists(errKey) || !f.exists(logKey) {
+ t.Fatalf("errors prune: errors chunk survived=%v, logs chunk survived=%v; want false, true", f.exists(errKey), f.exists(logKey))
+ }
+}
diff --git a/internal/host/logship.go b/internal/host/logship.go
index 7fa53a2df..4023cac68 100644
--- a/internal/host/logship.go
+++ b/internal/host/logship.go
@@ -6,7 +6,8 @@
// immutable gzipped chunk per app into the deployment bucket. On each hour
// boundary it prunes ITS OWN box subtree per app: hours beyond the age
// floor, then oldest-first beyond the byte cap (sizes ride in the chunk
-// keys — applog.ChunkKeySize — so no Store interface change). The
+// keys — applog.ChunkKeySize — so no Store interface change). Both limits
+// are the operator's, from host.env (logretention.go). The
// sampler/flush split mirrors metricsLoop for the same reason: the loop
// shares a process with the box's traffic, so it recovers panics and
// disables itself without a bucket rather than taking the box down.
@@ -29,8 +30,6 @@ import (
const (
logshipTick = 10 * time.Second
logshipDebounce = 2 * time.Second // event-poke settle: batch a wake's burst into one PUT
- logshipMaxAge = 7 * 24 * time.Hour
- logshipMaxBytes = 50 << 20 // per app per box
// logshipMaxPending caps records held across failed flushes, per app.
// The bucket being unwritable must not grow the agent's heap forever
// (samplerMaxBuf's reasoning); oldest go first, silently — a box-wide
@@ -71,8 +70,10 @@ func logshipLoop(sink *applog.Sink, box string) {
}
return
}
- log.Printf("agent: logship loop armed (10s ticks, event fast-flush), publishing to %s", target)
+ ret := logRetentionFromEnv(os.Getenv)
+ log.Printf("agent: logship loop armed (10s ticks, event fast-flush), publishing to %s, keeping %s", target, ret)
+ ledger := newPruneLedger(applog.FamilyLogs, box, ret)
pending := make(map[applog.AppKey][]applog.Record)
pruned := "" // last hour a prune ran for, "" = not yet
ticker := time.NewTicker(logshipTick)
@@ -84,15 +85,15 @@ func logshipLoop(sink *applog.Sink, box string) {
time.Sleep(logshipDebounce) // let the event's burst finish
}
logshipGather(sink, pending)
- logshipFlush(ctx, s, pending)
+ logshipFlush(ctx, s, pending, ledger)
if hour := applog.HourOf(time.Now()); hour != pruned {
// Prune covers every app this box is CURRENTLY holding or has
// just flushed; an app that stops logging entirely ages out via
- // other boxes' passes or the app's own deletion sweep. Sub-cap
- // apps pay one ListDirs each per hour.
+ // other boxes' passes or the app's own deletion sweep. An app
+ // with nothing to drop pays one ListDirs per hour.
for _, k := range logshipKnownApps(pending, sink) {
- chunkPrune(ctx, s, applog.FamilyLogs, box, k, time.Now())
+ ledger.prune(ctx, s, k, time.Now())
}
pruned = hour
}
@@ -113,9 +114,10 @@ func logshipGather(sink *applog.Sink, pending map[applog.AppKey][]applog.Record)
// logshipFlush writes one chunk per pending app — create-only, keyed by the
// batch's first seq, so a retried batch can never overwrite a delivered one
-// — and forgets what landed. A failed app keeps its records for the next
-// round; other apps' flushes proceed regardless.
-func logshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKey][]applog.Record) {
+// — and forgets what landed, telling ledger what it wrote. A failed app
+// keeps its records for the next round; other apps' flushes proceed
+// regardless.
+func logshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKey][]applog.Record, ledger *pruneLedger) {
for k, recs := range pending {
if len(recs) == 0 || strings.HasPrefix(k.App, demo.AppPrefix) {
delete(pending, k)
@@ -137,6 +139,7 @@ func logshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKe
log.Printf("agent: logship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs))
continue
}
+ ledger.wrote(k, key, len(body))
delete(pending, k)
}
}
@@ -162,67 +165,6 @@ func logshipKnownApps(pending map[applog.AppKey][]applog.Record, sink *applog.Si
return out
}
-// chunkPrune enforces retention for ONE app's ONE family on THIS box's
-// subtree only — each box owns what it wrote (spec §5). Hour granularity: an
-// hour goes when it is older than the age floor, or (oldest first) while the
-// subtree's key-embedded sizes total over the byte cap. Errors are logged
-// and left for the next hourly pass — retention is idempotent.
-func chunkPrune(ctx context.Context, s release.Store, fam applog.Family, box string, k applog.AppKey, now time.Time) {
- prefix, err := applog.FamilyBoxPrefix(fam, k.Acct, k.App, box)
- if err != nil {
- unshippable(fam, k, err)
- return
- }
- hourDirs, err := s.ListDirs(ctx, prefix)
- if err != nil {
- log.Printf("agent: logship prune %s: %v", prefix, err)
- return
- }
- // ListDirs returns full prefixes ending in "/", sorted is not promised —
- // the hour names sort chronologically, so order them ourselves via the
- // keys' lexical shape. Collect per-hour keys+sizes as we go.
- type hourEnt struct {
- dir string
- keys []string
- bytes int64
- }
- var hours []hourEnt
- var total int64
- for _, dir := range hourDirs {
- keys, err := s.List(ctx, dir)
- if err != nil {
- log.Printf("agent: logship prune %s: %v", dir, err)
- return
- }
- var b int64
- for _, key := range keys {
- if n, ok := applog.ChunkKeySize(key); ok {
- b += n
- }
- }
- hours = append(hours, hourEnt{dir: dir, keys: keys, bytes: b})
- total += b
- }
- // hourDirs from both implementations come lexically sorted (S3 lists in
- // key order; DirStore sorts), and hour names are zero-padded UTC — so
- // hours[0] is oldest.
- cutoff := now.Add(-logshipMaxAge)
- for _, h := range hours {
- hourName := applog.HourNameOfDir(h.dir)
- drop := applog.HourBefore(hourName, cutoff) || total > logshipMaxBytes
- if !drop {
- break // hours are oldest-first; nothing further is droppable
- }
- for _, key := range h.keys {
- if err := s.Delete(ctx, key); err != nil {
- log.Printf("agent: logship prune %s: %v", key, err)
- return
- }
- }
- total -= h.bytes
- }
-}
-
// unshippableSeen remembers which (family, app) pairs unshippable has
// already reported, so a route that can never ship says so once per
// process rather than every tick. Bounded by the routes a box serves.
diff --git a/internal/host/logship_test.go b/internal/host/logship_test.go
index 9f47e7889..2450259e4 100644
--- a/internal/host/logship_test.go
+++ b/internal/host/logship_test.go
@@ -27,11 +27,11 @@ func TestLogshipFlushDropsDemoApps(t *testing.T) {
if known := logshipKnownApps(pending, sink); len(known) != 1 || known[0].App != "web" {
t.Fatalf("prune worklist should hold only the ordinary app: %v", known)
}
- logshipFlush(t.Context(), failingStore{}, pending)
+ logshipFlush(t.Context(), failingStore{}, pending, nil)
if len(pending) != 1 || len(pending[applog.AppKey{Acct: "bab", App: "web"}]) != 1 {
t.Fatalf("only ordinary app should remain pending: %v", pending)
}
- logshipFlush(t.Context(), s, pending)
+ logshipFlush(t.Context(), s, pending, nil)
keys, err := s.List(t.Context(), "apps/")
if err != nil || len(keys) != 1 || !strings.HasPrefix(keys[0], "apps/bab/web/logs/") || len(pending) != 0 {
t.Fatalf("flush: keys %v, pending %v, err %v", keys, pending, err)
@@ -47,7 +47,7 @@ func TestLogshipFlushWritesOneChunkPerApp(t *testing.T) {
pending := make(map[applog.AppKey][]applog.Record)
logshipGather(sink, pending)
- logshipFlush(context.Background(), s, pending)
+ logshipFlush(context.Background(), s, pending, nil)
if len(pending) != 0 {
t.Fatalf("flushed apps still pending: %v", pending)
}
@@ -80,7 +80,7 @@ func TestLogshipFlushKeepsRecordsWhenTheBucketRefuses(t *testing.T) {
sink.App("bde", "ledgerpay", "h", "precious")
pending := make(map[applog.AppKey][]applog.Record)
logshipGather(sink, pending)
- logshipFlush(context.Background(), failingStore{}, pending)
+ logshipFlush(context.Background(), failingStore{}, pending, nil)
k := applog.AppKey{Acct: "bde", App: "ledgerpay"}
if len(pending[k]) != 1 || pending[k][0].Msg != "precious" {
t.Fatalf("records lost on failed flush: %v", pending)
@@ -120,7 +120,7 @@ func TestLogshipPrune(t *testing.T) {
liveKey := put("box1", "2026-08-10-11", 3, 10)
otherBox := put("box2", "2026-08-01-10", 4, 10) // NOT ours to prune
- chunkPrune(ctx, s, applog.FamilyLogs, "box1", k, now)
+ newPruneLedger(applog.FamilyLogs, "box1", defaultLogRetention).prune(ctx, s, k, now)
for key, want := range map[string]bool{oldKey: false, bigKey: false, liveKey: true, otherBox: true} {
_, _, err := s.Get(ctx, key)
@@ -147,7 +147,7 @@ func TestLogshipPruneKeepsRecentUnderCap(t *testing.T) {
if _, err := s.Put(ctx, key, make([]byte, 10), ""); err != nil {
t.Fatal(err)
}
- chunkPrune(ctx, s, applog.FamilyLogs, "box1", k, now)
+ newPruneLedger(applog.FamilyLogs, "box1", defaultLogRetention).prune(ctx, s, k, now)
if _, _, err := s.Get(ctx, key); err != nil {
t.Fatalf("live chunk pruned: %v", err)
}
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go
index 195d23e9c..e1ee3b98c 100644
--- a/internal/hostenv/hostenv.go
+++ b/internal/hostenv/hostenv.go
@@ -98,6 +98,8 @@ var Optional = []string{
"CARLOS_INGRESS_PROXY_SOURCES",
"CARLOS_INGRESS_TARGET_GROUPS",
"CARLOS_LAYOUT_DEFAULT",
+ "CARLOS_LOG_RETENTION_DAYS",
+ "CARLOS_LOG_RETENTION_MB",
"CARLOS_MOVES_PHASE1",
"CARLOS_MOVE_READY_DELTA_BYTES",
"CARLOS_PLAN_LIMITS",