host: operator settings for log 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 as before; a refused value is logged and keeps its default. Both are on the host.env allowlist; docs/site/cli.md documents them. The hourly prune no longer LISTs every kept hour every hour (~2,160 LISTs per app per box per hour at 90 days). pruneLedger walks once per process and once a day, learns this box's own writes from the flush, and between walks LISTs only the hours it deletes. Slice 1 of discussion #1024. Astra code review (fixes applied) and census approval (READY, recorded on #280). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from log-retention-knobs into main.
18 files changed,
+688
−91
docs/site/cli.md+2 −0docs/superpowers/notes/census-proposal-log-retention-knobs.md+11 −0docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs-census.md+13 −0docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs.md+11 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-log-retention-knobs-census.md+35 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-log-retention-knobs.md+14 −0internal/host/agent.go+5 −0internal/host/applessroute_test.go+4 −4internal/host/errship.go+5 −3internal/host/errship_test.go+4 −4internal/host/logretention.go+230 −0internal/host/logretention_test.go+323 −0internal/host/logship.go+14 −72internal/host/logship_test.go+6 −6internal/hostenv/hostenv.go+2 −0internal/provision/plan9_b8_census_test.go+4 −2internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-log-retention-knobs.tsv+4 −0
CI passed — run details
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 55b6c4fee..c6d966605 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -1711,6 +1711,8 @@ carlos logs --app hello --since 1h -f |
| an RE2 pattern, `--stream app` drops the platform commentary, and `--host` |
| narrows to one instance. |
| +Logs and errors are kept for 7 days, up to 50 MiB per app on each server, whichever runs out first. On your own servers you can change both in each server's host.env: `CARLOS_LOG_RETENTION_DAYS` takes whole days, and `CARLOS_LOG_RETENTION_MB` takes whole MiB or `off` for no size limit. A value the server can't use is logged, and the default stays. |
| + |
| ### carlos explain |
| `carlos explain <code> --app <a>` reads a reference code from a page the platform's edge protection answered. It says which rule fired and when, and shows the request while a record of it is kept, for 7 days. |
diff --git a/docs/superpowers/notes/census-proposal-log-retention-knobs.md b/docs/superpowers/notes/census-proposal-log-retention-knobs.md| new file mode 100644 |
| index 000000000..1dbbaa322 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-log-retention-knobs.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: log-retention-knobs |
| + |
| +Ruling `census-ruling-log-retention-knobs`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/host`, `internal/hostenv`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Seal: `e8beda8fd31db92f742943be631e8d034bbb4880225e69a680d5a0be893807af` → `e8beda8fd31db92f742943be631e8d034bbb4880225e69a680d5a0be893807af`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-log-retention-knobs.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs-census.md b/docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs-census.md| new file mode 100644 |
| index 000000000..7ba8328af |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs-census.md |
| @@ -0,0 +1,13 @@ |
| +Reviewed `c48e91e5..44da25ab95d84ef57df2d8b9f8686addcc8027dc`, census round 1. |
| + |
| +- **`internal/host`: approve.** Reviewed the new ledger, both shipping loops and flushes, their callees, and the `agent.go` comment. Pruning starts at `FamilyBoxPrefix` and deletes only keys listed beneath its returned hour prefixes. Parsed sizes and timestamps affect eviction decisions, not delete destinations. No new filesystem, execution or root-authority path is introduced. Evidence: [logretention.go:113–229](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/host/logretention.go:113), [chunk.go:80–119](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/applog/chunk.go:80), [store.go:1236–1273](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/release/store.go:1236). The fleet door also rejects traversal segments before authorization: [storedoor.go:569](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/edge/storedoor.go:569). |
| + |
| +- **`internal/hostenv`: approve.** The two optional names change retention policy only. Existing environment rendering checks remain intact. Invalid numeric values log a refusal and independently retain their defaults; ceilings prevent arithmetic overflow. Explicit `MB=off` disables only the byte cap, leaving age retention active. Evidence: [hostenv.go:101](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/hostenv/hostenv.go:101), [hostenv.go:361–403](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/hostenv/hostenv.go:361), [logretention.go:60–78](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/host/logretention.go:60). |
| + |
| +- **9B8 re-digests: approve.** Each flush retains one `Put` call site for a non-record chunk. The added `ledger.wrote` call updates memory only. No record key or additional storage write is introduced. Evidence: [logship.go:120–144](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/host/logship.go:120), [errship.go:75–99](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/host/errship.go:75), [census entries:784–790](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/provision/plan9_b8_census_test.go:784). |
| + |
| +**Findings:** P1: none. P2: none. P3: none. |
| + |
| +`git diff --check` passed. Targeted tests could not start because the read-only sandbox prevented Go from creating its build directory; runtime tests and census digest checks remain unverified here. No files were edited, no subagents spawned, and no full suites run. |
| + |
| +**READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs.md b/docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs.md| new file mode 100644 |
| index 000000000..167898f2c |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs.md |
| @@ -0,0 +1,11 @@ |
| +No material runtime correctness bug found in `fddc42f1`. Two findings: |
| + |
| +1. **P2 risk — repeated writes to an existing hour are untested.** [internal/host/logretention_test.go:166](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/host/logretention_test.go:166). The own-write test flushes once into a new hour. Changing `wrote` from `+=` to `=` would still pass, but repeated flushes would then discard previously counted bytes, allowing the cap to be exceeded until the daily walk. Outage recovery into an already-counted old hour is also untested. **Fix:** flush multiple distinct chunks into an existing hour, including records timestamped before the current hour; assert exact totals and oldest-first deletion. Exercise both shipping families. Invariant: every successful write contributes exactly once. |
| + |
| +2. **P3 nit — “cost no longer grows with retention” overstates the improvement.** [internal/host/logretention.go:8](/home/paulca/amadan.net/carlos/platform-log-retention-knobs/internal/host/logretention.go:8). Ordinary passes make one `ListDirs` call plus one `List` per deleted hour, but those calls paginate. The daily walk also remains proportional to retained hours: 2,160 populated hours require 2,160 sizing calls daily, averaging 90 per hour before pagination and deletions. The counter tests measure interface calls, not storage requests. **Fix:** describe the improvement as eliminating hourly sizing walks; distinguish interface calls from requests and account for the daily walk. |
| + |
| +Static inspection found matching hour-prefix semantics across S3Store, DirStore, PrefixStore and the fleet door. Sorting, default age handling, current-hour eviction and box isolation remain consistent with the previous implementation. |
| + |
| +The requested targeted tests **could not start** because the read-only sandbox prevented Go from creating its build directory. No files were edited. |
| + |
| +**READY AFTER FIXES** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-log-retention-knobs-census.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-log-retention-knobs-census.md| new file mode 100644 |
| index 000000000..262dc760f |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-log-retention-knobs-census.md |
| @@ -0,0 +1,35 @@ |
| +# Review brief: log-retention-knobs census approval, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `log-retention-knobs`, commit 44da25ab95d84ef57df2d8b9f8686addcc8027dc. |
| +Under review: the diff `c48e91e5..44da25ab` (`git diff c48e91e5 44da25ab`), against the census card |
| +`docs/superpowers/notes/census-proposal-log-retention-knobs.md`. |
| +Authorities: AGENTS.md "The census: the reviewer decides"; errors spec |
| +docs/superpowers/specs/2026-09-07-errors-and-analytics-design.md §3.6 (errors follow log retention). |
| + |
| +You are the independent census reviewer (AGENTS.md). Read the card, then every changed function in the |
| +re-pinned envelopes `internal/host` and `internal/hostenv`, and what each reaches. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul no longer rules on census units; you decide (#280, 2026-10-26). |
| +- An earlier code review of fddc42f1 (docs/superpowers/reviews/CODEX-FINDINGS-log-retention-knobs.md) found no runtime bug; its P2 and P3 were fixed in dfc9c8bf. |
| + |
| +## What to check |
| + |
| +1. Envelope `internal/host`: new logretention.go (logRetentionFromEnv, pruneLedger), the edited logshipLoop/logshipFlush, errshipLoop/errshipFlush, and the agent.go comment. Does any of it let root open, run, query or follow anything new from a path or input a tenant, app or box agent can create, write or name? The prune LISTs and DELETEs only under applog.FamilyBoxPrefix(fam, acct, app, box) in the bucket (as chunkPrune did); confirm nothing widens that scope, and that bucket key names (written by this box, but listable in a bucket other boxes and the console also write) cannot steer a delete outside the box's own subtree. |
| +2. Envelope `internal/hostenv`: two names added to Optional. Does admitting CARLOS_LOG_RETENTION_DAYS / _MB through host.env weaken any check root relies on? Can a bad value stop the agent or remove a limit silently (consider MB=off, ceilings, parse paths)? |
| +3. The 9B8 record-write census re-digests of logshipFlush and errshipFlush (internal/provision/plan9_b8_census_test.go): still one Put of a non-record chunk, no record key? |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +A verdict per envelope (`internal/host`, `internal/hostenv`) and for the 9B8 re-digests: approve or reject, citing the lines you read. Then findings ranked P1, P2, P3, each with evidence (file:line), failure scenario, fix and the invariant it breaks. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-log-retention-knobs.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-log-retention-knobs.md| new file mode 100644 |
| index 000000000..58fdd7762 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-log-retention-knobs.md |
| @@ -0,0 +1,14 @@ |
| +Review commit fddc42f1 on branch log-retention-knobs in the carlos/platform repo (your working directory). `git show fddc42f1` is the whole change. Read-only review: do not edit files. Leave GOCACHE unset if you run go; run only targeted tests (go test ./internal/host/ -run 'TestLogRetention|TestPrune|TestLogship|TestErrship' -count=1). |
| + |
| +Context: boxes ship app logs (and errors) as gzipped chunks into the bucket at apps/<sqid>/<app>/{logs,errors}/<box>/<hour>/<seq>-<size>... Each box prunes only its own subtree hourly. Retention was hard-coded 7 days / 50 MiB per app per box. This commit: |
| +1. Adds host.env settings CARLOS_LOG_RETENTION_DAYS and CARLOS_LOG_RETENTION_MB (or off), defaults unchanged, refused values logged and defaulted (internal/host/logretention.go). |
| +2. Replaces chunkPrune (which LISTed every hour dir every pass) with pruneLedger: walks once per process and once per 24 h, adds the flush's own writes via ledger.wrote, LISTs only hours it deletes. |
| + |
| +Look for correctness bugs, specifically: |
| +- Can the ledger under-count so the byte cap is exceeded beyond a day's drift, or over-count so it deletes hours it should keep? Consider: chunks whose hour (HourOf(recs[0].TS)) is an old hour after a bucket outage; a Put that fails but lands; process restarts; the hour dir key derivation in wrote (key[:LastIndexByte('/')+1]) vs what ListDirs returns for S3Store, DirStore, a PrefixStore and the edge store-door store a fleet box uses; ListDirs pagination/ordering. |
| +- Behaviour equivalence with the old chunkPrune at default settings (age floor, byte-cap ordering, current hour, other boxes' subtrees untouched). |
| +- Any path where a refused setting or a bad value could stop the agent or silently change behaviour. |
| +- Whether the tests would catch a broken implementation. |
| +- Request cost: is the steady state really one ListDirs per app per hour plus one List per deleted hour? |
| + |
| +Output: a numbered list of findings, each with severity (P1 bug / P2 risk / P3 nit), file:line, a concrete failure scenario, and a suggested fix. Say plainly if you find nothing material. Keep it under 600 words. |
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..89e3653c5 |
| --- /dev/null |
| +++ b/internal/host/logretention.go |
| @@ -0,0 +1,230 @@ |
| +// 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 no longer sizes every hour every hour. It used to LIST each |
| +// hour it kept on every pass: ~168 LISTs per app per box per hour at 7 |
| +// days, ~2,160 at 90. pruneLedger remembers each hour's size after a walk, |
| +// adds what this box's own flushes write, and between walks LISTs only the |
| +// hours it deletes: one ListDirs per app per hour (paginated, 1,000 hours |
| +// a page on S3) plus one List per deleted hour. The walk itself still |
| +// costs one List per kept hour and runs once per process and once a day, |
| +// to correct drift (an ambiguous Put that landed after reporting |
| +// failure): at 90 days that averages ~90 LISTs per app per box per hour, |
| +// against ~2,160 before. These counts are Store calls; a List over more |
| +// than 1,000 keys pages too. |
| +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..e8647b965 |
| --- /dev/null |
| +++ b/internal/host/logretention_test.go |
| @@ -0,0 +1,323 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "maps" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/apperr" |
| + "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)) |
| + } |
| +} |
| + |
| +// TestPruneLedgerCountsEveryWriteOnce: after a walk, every chunk a flush |
| +// writes adds its size exactly once, including repeated writes into one |
| +// hour and late writes into an older hour (records held through a bucket |
| +// outage). The ledger must then match a fresh walk byte for byte, for both |
| +// shipping families. |
| +func TestPruneLedgerCountsEveryWriteOnce(t *testing.T) { |
| + t.Parallel() |
| + ctx := context.Background() |
| + now := time.Date(2026, 11, 14, 12, 30, 0, 0, time.UTC) |
| + stamps := []time.Time{now, now.Add(time.Minute), now.Add(-3 * time.Hour), now.Add(-3*time.Hour + time.Minute), now} |
| + ret := logRetention{maxAge: 30 * 24 * time.Hour, maxBytes: 1 << 30} |
| + |
| + for _, fam := range []applog.Family{applog.FamilyLogs, applog.FamilyErrors} { |
| + f := newPruneFixture(t) |
| + l := newPruneLedger(fam, "box1", ret) |
| + if fam == applog.FamilyLogs { |
| + f.put("box1", now.Add(-3*time.Hour), 77) // an existing older hour |
| + } else { |
| + key := mustKey(t)(applog.FamilyChunkKey(fam, f.k.Acct, f.k.App, "box1", applog.HourOf(now.Add(-3*time.Hour)), 1, 77)) |
| + if _, err := f.s.Store.Put(ctx, key, make([]byte, 77), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + l.prune(ctx, f.s, f.k, now) // walk |
| + for i, ts := range stamps { |
| + seq := uint64(100 + i) |
| + if fam == applog.FamilyLogs { |
| + logshipFlush(ctx, f.s, map[applog.AppKey][]applog.Record{f.k: {{TS: ts, Box: "box1", Seq: seq, Msg: "line"}}}, l) |
| + } else { |
| + errshipFlush(ctx, f.s, map[applog.AppKey][]apperr.Record{f.k: {{TS: ts, Box: "box1", Seq: seq, Source: "log", Name: "boom", FP: "fp"}}}, l) |
| + } |
| + } |
| + got := maps.Clone(l.apps[f.k].bytes) |
| + |
| + fresh := newPruneLedger(fam, "box1", ret) |
| + fresh.prune(ctx, f.s, f.k, now) |
| + want := fresh.apps[f.k].bytes |
| + if len(want) != 2 || !maps.Equal(got, want) { |
| + t.Fatalf("%s: ledger %v, fresh walk %v (want two hours, equal)", fam, got, want) |
| + } |
| + } |
| +} |
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", |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 24b76f516..9bc78108d 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -781,11 +781,13 @@ var plan9B8CensusInventory = []censusEntry{ |
| {"internal/host/rootexecution_authority.go", "ClaimRootHTTP.executionAuthority", "key-site", "key:RecordKey", "107989f561409fd8c11c2666d0672b8dbeb368842fe00ad6a7b84fece2150438"}, |
| // Re-digested for fix-empty-app-key (census-ruling-fix-empty-app-key, platform-1e 2026-10-16): a chunk key the errors builder refuses (empty or invalid account or app) drops that app's records and logs once; no Put happens for it. Same single Put of the errors chunk; no record key. |
| // Re-digested for agent-start-demo-log-skip (Opus review, 2026-11-05): a tmp-demo- app's pending records are dropped before any Put, as UpsertDay drops demo analytics. One fewer write; same single Put of the errors chunk otherwise; no record key. |
| - {"internal/host/errship.go", "errshipFlush", "nonrecord", "sel:Put", "cbd28ca322e52f3d0ee67e483c04911f635223963fba9e306d5148e54439585c"}, |
| + // Re-digested for log-retention-knobs (Astra review, 2026-11-14): after a successful Put it tells the prune ledger the chunk's key and size (ledger.wrote, in-memory only). Same single Put of the errors chunk; no record key. |
| + {"internal/host/errship.go", "errshipFlush", "nonrecord", "sel:Put", "c4a77f8d81c0b045715d42395ae7fae3adcf901002537eba01df713af1e21f4c"}, |
| {"internal/host/fleetbind.go", "WriteFleetBinding", "nonrecord", "sel:Put", "44ab984c2c9b30abcc938132118f61a6922ccc0cd40ed2b6cb61c7654aa0a1c3"}, |
| // Re-digested for fix-empty-app-key (census-ruling-fix-empty-app-key, platform-1e 2026-10-16): as errshipFlush, for the logs family. Same single Put of the log chunk; no record key. |
| // Re-digested for agent-start-demo-log-skip (Opus review, 2026-11-05): as errshipFlush, for the logs family. Same single Put of the log chunk otherwise; no record key. |
| - {"internal/host/logship.go", "logshipFlush", "nonrecord", "sel:Put", "6458f1225c8f079c5ecab6635f154e53fb5c5d643de9451854d75ab976a840d7"}, |
| + // Re-digested for log-retention-knobs (Astra review, 2026-11-14): as errshipFlush, for the logs family. Same single Put of the log chunk; no record key. |
| + {"internal/host/logship.go", "logshipFlush", "nonrecord", "sel:Put", "8af5df40824469d43813170bd0e152048a676c3db35afbb5fc07dd0796be258a"}, |
| {"internal/host/metrics_loop.go", "putAlertState", "nonrecord", "sel:Put", "d5b6e8b34dc5a731d6bbafeac0b7d0c5c20706d6f413dff38088b3321b35a26c"}, |
| // Clears an aborting record through SetRecordMove (MoveGuardedAbortComplete) once nothing is owed under the op, then ReleaseAbort: record first, ruling M4. |
| {"internal/host/movesabort.go", "movesWorker.abortSource", "record-writer", "key:SetRecordMove", "51bafe02fe16f07c1f1e08cfbc224ba21c8277ec065fff1142349afe0dde675b"}, |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 667bc41bd..8d8ee7232 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -215,3 +215,4 @@ plan14-root-reads-offline-move-pool-target-413.tsv f79b455e32eb0f63e19ba8b5c6712 |
| plan14-root-reads-probe-burst-block.tsv 94ccbabaf19c3a449cec248a0c32fcc8593c82d3f7f433c6a48b6e0fdf068167 |
| plan14-root-reads-g6-pool.tsv 94ccbabaf19c3a449cec248a0c32fcc8593c82d3f7f433c6a48b6e0fdf068167 |
| plan14-root-reads-pdf-host-client-groups.tsv e8beda8fd31db92f742943be631e8d034bbb4880225e69a680d5a0be893807af |
| +plan14-root-reads-log-retention-knobs.tsv e8beda8fd31db92f742943be631e8d034bbb4880225e69a680d5a0be893807af |
diff --git a/internal/provision/testdata/plan14-root-reads-log-retention-knobs.tsv b/internal/provision/testdata/plan14-root-reads-log-retention-knobs.tsv| new file mode 100644 |
| index 000000000..a2d943449 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-log-retention-knobs.tsv |
| @@ -0,0 +1,4 @@ |
| +# Census overlay log-retention-knobs, written by census-propose (#369). census-ruling-log-retention-knobs, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-log-retention-knobs.md. |
| +# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/host 5db3bd1ba62cb0a5fc25e53aa9748319adb53fedbb7c611a972533ed5f421d9d |
| +@coverage internal/hostenv d7eaaec935c96536449b38210eec2d3d8c71c3178f070a00bb97c5506f69db11 |