carlos / platform Public

litestream: size the memory cap from the database count; restart alerts (#284)

carlos ops litestream writes carlos-litestream.service.d/50-memory.conf:
MemoryMax = 256M + 8M per database (floor 512M), GOMEMLIMIT at 3/4,
retried via a .reload-pending marker. Unit default 512M with restart
backoff. A per-unit restarts@<unit> rule (more than 3 restarts in 10
min) on the fleet alerts engine, at incident level. A root-run agent
keeps its restart watch in memory only. Copy by Luna on Paul's
instruction; census-ruling-ls284 (#280); Astra merge review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from litestream-oom-284 into main.
claude agent, operated by paul@keymail.dev 87ef93edf85367e05239d755b0965047d4b69cf1 parent 74757d1
35 files changed, +2,135 −46
  • docs/superpowers/notes/LUNA-COPY-BRIEF-litestream-284.md +43 −0
  • docs/superpowers/notes/census-proposal-ls284.md +29 −0
  • docs/superpowers/notes/copy-litestream-284.md +111 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-census-ls284-R2.md +34 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-census-ls284.md +96 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-litestream-284-merge.md +91 −0
  • docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284-R2.md +34 −0
  • docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284.md +50 −0
  • docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-litestream-284-merge.md +20 −0
  • internal/alerting/ruletext.go +6 −0
  • internal/console/alertcopy_test.go +3 −2
  • internal/console/alertdetail_test.go +130 −0
  • internal/console/alertengine_pass.go +11 −6
  • internal/console/alertnotify.go +20 −4
  • internal/console/alertpages.go +12 −2
  • internal/console/alertsignals.go +13 −2
  • internal/console/metricsview.go +7 −1
  • internal/console/templates/metrics.html +1 −1
  • internal/host/alertsink.go +30 −8
  • internal/host/alertsink_test.go +20 −3
  • internal/host/enginebeat_linux_test.go +1 −1
  • internal/host/metrics_loop.go +45 −5
  • internal/host/metrics_loop_test.go +9 −9
  • internal/host/restartwatch.go +306 −0
  • internal/host/restartwatch_test.go +321 −0
  • internal/host/units/carlos-litestream.service +15 −1
  • internal/metrics/alert.go +82 −1
  • internal/metrics/alert_test.go +107 −0
  • internal/ops/flock_unix.go +15 −0
  • internal/ops/flock_windows.go +18 −0
  • internal/ops/litestream_memory.go +155 −0
  • internal/ops/ops.go +42 −0
  • internal/ops/ops_test.go +235 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-ls284.tsv +22 −0

CI passed — run details

landed from litestream-oom-284

diff --git a/docs/superpowers/notes/LUNA-COPY-BRIEF-litestream-284.md b/docs/superpowers/notes/LUNA-COPY-BRIEF-litestream-284.md
new file mode 100644
index 000000000..a1adbf76e
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-BRIEF-litestream-284.md
@@ -0,0 +1,43 @@
+# Copy pass: litestream memory cap and restart alert (#284 slice A)
+
+You are reviewing copy for CARLOS, a hosting platform. This change stops the
+backup replicator on a box from being killed for lack of memory, and alerts
+operators when any platform service on a box restarts in a loop. In the
+incident behind it, the replicator restarted over 900 times in two hours
+and nothing said so.
+
+Readers are platform operators: technical people running the fleet, reading
+an alert on a phone or a line in a terminal.
+
+The deck is `docs/superpowers/notes/copy-litestream-284.md`, at this brief's
+commit. Read all of it, including "What the feature does": the copy must
+match those facts. You may read the code it names to check a fact. Change
+nothing on disk.
+
+## House rules (Paul's)
+
+- Plain, direct voice. Say what happened, then what to do. No marketing
+ tone, no exclamation marks, no "simply", no throat-clearing.
+- No em or en dashes used as dashes. Use a full stop and a new sentence,
+ starting in lower case where the original sentence continued.
+- Human text only. Leave error fragments, diagnostics, log lines and JSON
+ keys alone. The deck already leaves them out; don't add them back.
+- No tenant or customer names. Examples use neutral names (box-a, shop,
+ example.com).
+- Keep every placeholder (`%s`, `%d`, `%v`) in the same order. If you must
+ reorder, say so in "why".
+- Box-side text (group A, B) may go to Slack or email, so never name a
+ channel ("you will get another email").
+- Group A is lower case by convention, like every box alert. Its subject
+ stays ASCII and under 100 characters.
+- Operator-facing, so technical words (systemd, drop-in, journal, unit) are
+ fine. Undefined jargon is not.
+
+## What to return
+
+1. A table `key | new | why`, with only the rows you change. Rows you leave
+ alone are approved as they are.
+2. A `## Flags` section with only what needs a person: a fact in the copy
+ that conflicts with "What the feature does" or the code, a placeholder
+ you can't make work, or a string that needs splitting. Keep it short.
+ Write "none" if there are none.
diff --git a/docs/superpowers/notes/census-proposal-ls284.md b/docs/superpowers/notes/census-proposal-ls284.md
new file mode 100644
index 000000000..75541b8e1
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-ls284.md
@@ -0,0 +1,29 @@
+# Census approval: ls284
+
+Ruling `census-ruling-ls284`. The independent reviewer approves or rejects every change below, 5 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/units/carlos-litestream.service` `external` | body | unchanged (1) | MemoryMax 256M -> 512M, adds Environment=GOMEMLIMIT=384MiB and RestartSteps=5/RestartMaxDelaySec=60 backoff; ExecStart, user, sandboxing and the config path it reads are unchanged; no new read |
+| `internal/ops/ops.go` `runLitestream` | body | unchanged (3) | after writing the config, writes the memory drop-in (default /etc/systemd/system/carlos-litestream.service.d/50-memory.conf only when --out is the default config path; --memory-dropin overrides, "none" skips) and calls systemctl daemon-reload; reads only the config it just wrote, via configDBCount; no tenant input reaches the path |
+
+Envelopes re-pinned: `internal/alerting`, `internal/host`, `internal/host/units`, `internal/metrics`, `internal/ops`.
+
+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.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/units/carlos-litestream.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/ops/ops.go` `runLitestream`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/host/restartwatch.go:loadRestartWatch`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+- new `internal/host/restartwatch.go:platformUnitRestarts`: reads +file:CommandContext; written legacy, accepted-legacy, frozen
+- new `internal/ops/litestream_memory.go:configDBCount`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+- new `internal/ops/litestream_memory.go:writeMemoryDropIn`: reads +file:Lstat, +file:Open, +file:ReadFile; written legacy, accepted-legacy, frozen
+- new `internal/ops/ops.go:systemdDaemonReload`: reads +file:CommandContext; written legacy, accepted-legacy, frozen
+
+Seal: `7fb932b118e67e23b33a374c6a4020b38976667c7ec4cfb855c0f8b598b1756b` → `744b16d970f22476b79982e57c326157ca5137fa96ccaee4a7ae10c25248d124`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-ls284.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/copy-litestream-284.md b/docs/superpowers/notes/copy-litestream-284.md
new file mode 100644
index 000000000..ea0568338
--- /dev/null
+++ b/docs/superpowers/notes/copy-litestream-284.md
@@ -0,0 +1,111 @@
+# Litestream memory cap and restart alert (#284 slice A): copy deck
+
+Every human-facing string slice A adds, as the code has it after the merge
+of main on 2026-11-03. The October deck (10 strings) was written before main
+replaced the console's alert watcher with the fleet alerts engine. Its mail
+strings are gone, and the engine needed the new rows in groups B and C.
+
+Status: APPROVED by delegation (Luna, 2026-11-03, on Paul's instruction).
+Every row is approved as below: the `current` column is the draft Luna read,
+and "Luna's changes" at the end gives the final text of the rows she
+changed. Rows she left alone are approved as drafted.
+
+How to read it: `current` is the text in the code. `%s` and `%d` are Go
+format verbs; the notes say what each one holds. Keep every verb, in order.
+
+## What the feature does (the facts the copy must match)
+
+- The box agent asks systemd once a minute for each `carlos-*.service`
+ unit's restart counter. A unit that restarts **more than 3 times in 10
+ minutes** fires its own alert, one per unit. It clears only after a whole
+ 10 minutes with no restart **and** the unit is not failed or between
+ restarts. A unit that stopped restarting because systemd gave up has not
+ recovered, so the alert stays up. A unit that is no longer loaded clears.
+- The rule's ID on the wire is `restarts@<unit>`, e.g.
+ `restarts@carlos-litestream.service`. Its kind is `restarts`.
+- The incident that started it (#284): `carlos-litestream.service`, the
+ backup replicator, was killed for running out of memory four seconds into
+ every start, restarted over 900 times in two hours, and nothing reported
+ it. While it loops, the box's databases are not being copied off the box.
+- `carlos ops litestream` now writes a systemd drop-in sizing the
+ replicator's memory cap from the number of databases: 256M + 8M per
+ database, never under 512M. It runs on a box, as root, by an operator or
+ a timer.
+
+## Group A. The box's own alert (SNS email, or Slack when the box's webhook is a Slack URL)
+
+`internal/host/alertsink.go`. Lower case, like every box alert. The fire
+sentence is also the subject, after `carlos alert: `; the clear sentence
+after `carlos alert cleared: `. The body adds a full stop. Subject must stay
+ASCII and under 100 characters.
+
+| key | current | notes |
+|---|---|---|
+| A1 box.fire | `%s restarted %d times in %d minutes on %s` | unit, count, window (10), box. e.g. "carlos-litestream.service restarted 12 times in 10 minutes on box-a" |
+| A2 box.clear | `%s has stopped restarting on %s` | unit, box |
+| A3 box.level | `more than %d restarts in %d minutes` | 3, 10. Shown as "the alert level is %s." (that frame is main's, not in scope) |
+| A4 box.footer | `rule: Restart loop (%s)` | the footer names the rule by B1 with the unit in brackets. Only the brackets are new; "rule:" is main's |
+
+## Group B. Shared rule text (`alerting.BoxRuleText["restarts"]`)
+
+Used by the box's alert (A) under "How long you have" / "What to do", and by
+the console's messages (C), so both say the same.
+
+| key | current | notes |
+|---|---|---|
+| B1 rule.restarts.title | `Restart loop` | the display name. The console shows it as "Restart loop (carlos-litestream.service)" |
+| B2 rule.restarts.how_long | `What the service does is down or unreliable until it stays up.` | for litestream: backups stop |
+| B3 rule.restarts.what_to_do | `Read the service's journal on that box to see why it keeps stopping.` | |
+
+## Group C. The console (alert messages and the `/fleet/alerts` and metrics pages)
+
+`internal/console`. Messages go to email, Slack or a webhook. The headline is
+main's frame `%[1]s on %[2]s` with B1 and the unit as `%[1]s`, e.g. "Restart
+loop (carlos-litestream.service) on box-a". The `what` takes only the box.
+
+| key | current | notes |
+|---|---|---|
+| C1 rule.restarts.what | `A platform service on %s keeps restarting.` | box. The unit is in the headline, not here |
+| C2 rule.restarts.what.none | `A platform service keeps restarting.` | every box snoozed, none to name |
+| C3 value.restarts | `%d restarts in 10 minutes` | count. Follows C1 as "Reading: %s." and fills the value column of the metrics page's alert table |
+| C4 rules.when.restarts | `A platform service on a box restarts more than 3 times in 10 minutes. Each service is its own alert.` | the Rules section of `/fleet/alerts`, under the rule's title |
+
+## Group D. `carlos ops litestream` (operator CLI on a box)
+
+`internal/ops`. Lines go to stderr. Leading `litestream: ` is the verb's
+existing prefix on every line.
+
+| key | current | notes |
+|---|---|---|
+| D1 flag.memory-dropin | `systemd drop-in receiving the replicator's memory cap, sized from the database count (default %s when --out is %s; "none" to leave the unit's cap alone)` | `--help` text. %s are the default drop-in path and default config path |
+| D2 warn.cap | `litestream: WARNING: could not set the memory cap in %s: %v` then on the next line, indented, `The replicator keeps its current cap. The next run will try again.` | drop-in path, error. Not fatal: the config is written |
+| D3 info.cap | `litestream: memory cap %dM for %d databases (%s)` | MiB, count, drop-in path |
+| D4 dropin.header | `# GENERATED by `carlos ops litestream` — do not hand-edit; it is rewritten when` / `# the number of replicated databases changes. To override it, add a drop-in` / `# that sorts after this one.` | the comment at the top of the generated drop-in, read with `systemctl cat`. Note the em dash |
+
+## Not in the deck
+
+Error fragments (`systemd did not reload: %w`, `systemctl daemon-reload:
+...`, `ops verbs lock box-side (linux) only`), journal log lines
+(`agent: restart watch: save ...`), JSON keys, and code comments, including
+those in `carlos-litestream.service`.
+
+## Luna's changes (gpt-5.6-luna, high effort, 2026-11-03)
+
+Brief: `LUNA-COPY-BRIEF-litestream-284.md`. Luna raised no flags.
+
+| key | new | why (Luna) | applied |
+|---|---|---|---|
+| A4 | `rule: restart loop (%s)` | Box alerts use lower case. | **No.** Main's footer names every rule by its capitalised display name ("rule: Disk nearly full"), by the fleet alerts ruling R-31. Lower-casing only this rule would make it the odd one out. Left for Paul. |
+| B2 | `The service may be down or unreliable after repeated restarts.` | Avoids implying recovery while the alert remains active. | yes |
+| B3 | `Read the service's journal on that box to find out why it restarted repeatedly.` | Matches the observed condition. | yes |
+| C1 | `A platform service on %s has restarted repeatedly.` | Remains accurate if systemd has stopped retrying. | yes |
+| C2 | `A platform service has restarted repeatedly.` | Same accuracy fix without a box name. | yes |
+| D1 | `systemd drop-in that sets the replicator's memory cap from the database count (default %s when --out is %s; "none" leaves the unit's cap alone)` | "Sets" is clearer than "receiving." | yes |
+| D2 | `litestream: WARNING: could not apply the memory cap from %s: %v` / ` The replicator keeps its current cap. The next run will try again.` | Covers both write and reload failures. | yes |
+| D4 | `# GENERATED by `carlos ops litestream`. Do not hand-edit. It is rewritten when` / (rest unchanged) | Removes the prohibited em dash and improves sentence boundaries. | yes, with the house rule's lower case where the sentence continued: `# GENERATED by `carlos ops litestream`. do not hand-edit. it is rewritten when` |
+
+## Added after the Luna pass
+
+| key | text | why |
+|---|---|---|
+| C5 rules.th.restarts | `Fixed at more than 3 restarts in 10 minutes. Not configurable.` | Astra's merge review (P2): the Rules row said "No threshold." Worded on main's pattern for fixed thresholds (`rules.th.lag`, `rules.th.engine_silent`); not seen by Luna. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-census-ls284-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-census-ls284-R2.md
new file mode 100644
index 000000000..620427abf
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-census-ls284-R2.md
@@ -0,0 +1,34 @@
+# Review brief: census ruling ls284 (litestream-oom-284), round 2 of 3
+
+Repo carlos/platform, branch `litestream-oom-284`, commit
+7120ca1555ad7e1f4ae1ff48bc6cf4b2ab49a36e (the fix and the re-proposed
+overlay; this brief is the commit after it and changes nothing in scope).
+Under review: the census card
+`docs/superpowers/notes/census-proposal-ls284.md` at that commit and the
+diff `origin/main...7120ca15` for the files round 1 named, plus
+`internal/host/restartwatch_test.go`. `origin` is amadan.net.
+
+Everything else, "Fixed: do not re-argue", "What to check", "Severity" and
+"Output", is as in round 1's brief,
+`docs/superpowers/reviews/CODEX-REVIEW-BRIEF-census-ls284.md`. Read it.
+
+## Round 2
+
+Earlier rounds: round 1, `docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284.md`
+(one P1: a root-run agent follows agent-writable restart-state paths;
+`loadRestartWatch` and the `internal/host` envelope rejected; everything
+else approved). The round number counts every earlier review of this
+change, under any file name or reviewer.
+
+First give one line for round 1's P1: resolved, partly, or not. The fix is
+`restartWatchFile` / `newRestartWatchFile` in `internal/host/restartwatch.go`
+and its use in `metricsLoop` (`internal/host/metrics_loop.go`), with the
+guard test `TestRestartWatchFileRootNeverTouchesThePath`. Carry it forward
+if unresolved, then add new findings. Units approved in round 1 whose code
+did not change since 67042203 keep their verdict unless you find new
+evidence; say "unchanged, approved in round 1" for them in the table.
+
+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-census-ls284.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-census-ls284.md
new file mode 100644
index 000000000..d11b0210d
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-census-ls284.md
@@ -0,0 +1,96 @@
+# Review brief: census ruling ls284 (litestream-oom-284), round 1 of 3
+
+Repo carlos/platform, branch `litestream-oom-284`, commit
+67042203fb9f30c71fbe0682058c56f35d70eef9 (the census proposal; this brief is
+the commit after it and changes nothing in scope).
+Under review: the census card
+`docs/superpowers/notes/census-proposal-ls284.md` and the diff
+`origin/main...67042203` for the files it names:
+
+- `internal/host/units/carlos-litestream.service`
+- `internal/ops/ops.go`, `internal/ops/litestream_memory.go`,
+ `internal/ops/flock_unix.go`, `internal/ops/flock_windows.go`
+- `internal/host/restartwatch.go`, `internal/host/metrics_loop.go`,
+ `internal/host/alertsink.go`
+- `internal/metrics/alert.go`
+- `internal/alerting/ruletext.go`
+
+`origin` is amadan.net. Run `git diff origin/main...67042203 -- <file>`.
+
+Authorities, merged on main: AGENTS.md, "The census: the reviewer decides"
+(read all of it), and the census card itself. This is a census ruling, not a
+code review: the question is only what root reads, runs or follows.
+
+You are an independent reviewer from the other model family. Paul does not
+rule on census units (#280, 2026-10-26); your verdict is the approval.
+
+## Fixed: do not re-argue
+
+- The feature (discussion #284): `carlos ops litestream` writes a systemd
+ drop-in sizing the replicator's MemoryMax from the database count, and
+ the box agent alerts on platform units that restart in a loop. Whether the
+ feature is wanted is not in question.
+- The sizing numbers (256M + 8M per database, floor 512M, GOMEMLIMIT three
+ quarters) are not a census matter.
+
+## What to check
+
+For every unit and every re-pinned envelope on the card, give approve or
+reject, citing the lines you read.
+
+1. `writeMemoryDropIn` and `runLitestream`: what decides the drop-in path
+ and the `.reload-pending` marker path? Can a tenant, an app or a box
+ agent create, write or name either path, or the directory locked with
+ `os.Open`, so that root's `MkdirAll`, `Lstat`, `Open`, `ReadFile` or the
+ safefile write follows something it did not before? Note the default path
+ is used only when `--out` is the default config path.
+2. `configDBCount`: it reads the config at `--out` after this run wrote it.
+ Is that file anything other than root's own output? What does its count
+ decide (only the size of the cap)?
+3. `systemdDaemonReload` and `platformUnitRestarts`: are the argv fixed, with
+ no caller input? Is the `carlos-*.service` pattern passed to systemctl as
+ an argument (no shell)?
+4. `loadRestartWatch`: it reads `<dataDir>/monitor/restarts.json`. Who can
+ write that path on a box? What does the parsed content decide? The claim
+ is: only the restarts alert's count, and a malformed file is an empty
+ watch.
+5. `carlos-litestream.service`: MemoryMax 256M to 512M, GOMEMLIMIT, and
+ RestartSteps/RestartMaxDelaySec. Confirm ExecStart, User, sandboxing and
+ the files the unit reads are unchanged, and nothing weakens a check the
+ recorded basis (`accepted-legacy;rev3=J4;basis=root-input`) relies on.
+6. Envelopes `internal/alerting`, `internal/host`, `internal/host/units`,
+ `internal/metrics`, `internal/ops`: read every changed function and what
+ it reaches. The alerting, metrics and alertsink changes are text and
+ alert evaluation; say if any of them reads or runs anything.
+7. New dispositions (`legacy`, `accepted-legacy`, frozen) for the five new
+ units: right for their reads?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge. For the census, a rejected unit is a P1.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a 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
+
+First a table: `unit or envelope | verdict (approve/reject) | lines read`.
+Then findings ranked P1, P2, P3. Each gives the unit, the problem, the
+evidence (file:line, verified), the failure scenario, a concrete fix and
+the invariant or trust boundary it breaks (that is its fault family). End
+with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+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-litestream-284-merge.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-litestream-284-merge.md
new file mode 100644
index 000000000..3f334f0fc
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-litestream-284-merge.md
@@ -0,0 +1,91 @@
+# Review brief: litestream-oom-284 merge of main, round 1 of 1
+
+Repo carlos/platform, branch `litestream-oom-284`, tip
+bfb7367bf74a865ae581f4e80213b6a10896d191 (this brief is the commit after it).
+Under review: **only what changed since fa63c1ea**, the tip that passed five
+Astra rounds and was MERGE-READY on 2026-10-14. Since then the branch merged
+main twice (7560a5de against 16b2a0ce, 709e6d5a against 56940c87) and added
+copy and census commits. `origin` is amadan.net.
+
+Do not re-review the slice as a whole. Compare the branch's net change then
+and now:
+
+ git diff d2f58fd3...fa63c1ea -- internal/ # reviewed, against its old base
+ git diff origin/main...bfb7367b -- internal/ # now, against today's main
+ git log --oneline fa63c1ea..bfb7367b
+
+and review the difference between them, plus how the branch's code meets
+what main added.
+
+Authorities on main: AGENTS.md ("Stopping rules", "The census"), and main's
+fleet alerts engine as built (`internal/console/alertengine*.go`,
+`alertsignals.go`, `alertnotify.go`, `alertpages.go`, `internal/alerting`).
+
+## Fixed: do not re-argue
+
+- The slice's design and everything in it that is unchanged since
+ fa63c1ea (five rounds; findings in the branch history).
+- The census: ruling ls284 approved by Astra in round 2 at 7120ca15
+ (`docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284-R2.md`).
+- The copy: approved by delegation, Luna pass
+ (`docs/superpowers/notes/copy-litestream-284.md`). Words are not in scope;
+ a string that states something false is.
+
+## What to check
+
+1. **The console port.** Main replaced the alert watcher (whose mail the
+ branch had extended) with the alert engine. The branch now keeps a box's
+ `restarts@<unit>` rule as its own engine incident per unit, with boxes as
+ members, and resolves level, copy, value text, settings
+ (`alertEmitRows`) and the Rules-page noise count by kind
+ (`alertRuleKind`). Does any engine path still key by the raw rule where
+ it needs the kind, or by the kind where it needs the raw rule (snooze
+ keys, history, `withGone`, cutover, `feedAlertsNow`, the rule-save
+ handler)? Can a restarts incident fail to clear or close?
+2. **`internal/metrics/alert.go` Evaluate.** main's `disk_eta` and
+ `engine_silent` sit beside the per-unit restarts block. Note that main's
+ engine_silent deletes its key on disarm while restarts keeps a quiet key;
+ is that a problem for the engine (which reads box objects, not the old
+ watcher's alert_seen)?
+3. **`internal/host/metrics_loop.go`.** `alertTick` now takes both the
+ restart readings and main's disk trend and engine beat. The startup tick
+ passes `beat` and a nil trend. Check it cannot clear a restored
+ `engine_silent` fire or add a bogus forecast point.
+4. **`internal/host/alertsink.go`.** Box rule text is looked up by kind
+ (`alertRuleKind`), and `alertRuleName` names a per-unit rule as
+ "Restart loop (<unit>)". Check the SNS subject stays ASCII and under 100
+ characters for a long unit name, or that main's existing truncation
+ covers it.
+5. **The root gate** (`restartWatchFile`, from census round 1). Does it
+ change alert behaviour for a non-root agent?
+6. Anything the merge dropped from either side.
+
+## 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. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a 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. This review has one round, with
+at most one fix round after it.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section, the problem, the
+evidence (file:line, verified), the failure scenario, a concrete fix and
+the invariant or trust boundary it breaks (that is its fault family). End
+with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+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-FINDINGS-census-ls284-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284-R2.md
new file mode 100644
index 000000000..18f34aecf
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284-R2.md
@@ -0,0 +1,34 @@
+# Census ls284, round 2 findings (gpt-6-astra, high, read-only)
+
+Proposal 7120ca15, brief 86f6278c. Verbatim reviewer output.
+
+Round 1’s P1: **resolved** — root-run agents now bypass restart-history path construction, loading and saving.
+
+| Unit or envelope | Verdict | Lines read |
+|---|---|---|
+| `carlos-litestream.service:external` | approve — unchanged, approved in round 1 | `internal/host/units/carlos-litestream.service:15–50` |
+| `ops.go:runLitestream` | approve — unchanged, approved in round 1 | `internal/ops/ops.go:93–201` |
+| `restartwatch.go:loadRestartWatch` | approve | `internal/host/restartwatch.go:145–249`; `internal/host/metrics_loop.go:899–951`; `internal/host/restartwatch_test.go:281–321` |
+| `restartwatch.go:platformUnitRestarts` | approve — unchanged, approved in round 1 | `internal/host/restartwatch.go:252–306` |
+| `litestream_memory.go:configDBCount` | approve — unchanged, approved in round 1 | `internal/ops/litestream_memory.go:149–155`; `internal/ops/litestream.go:165–175,596–607` |
+| `litestream_memory.go:writeMemoryDropIn` | approve — unchanged, approved in round 1 | `internal/ops/litestream_memory.go:26–145`; `internal/safefile/file_linux.go:15–42,120–198` |
+| `ops.go:systemdDaemonReload` | approve — unchanged, approved in round 1 | `internal/ops/ops.go:203–218` |
+| Envelope `internal/alerting` | approve — unchanged, approved in round 1 | `internal/alerting/ruletext.go:59–70` |
+| Envelope `internal/host` | approve | `restartwatch.go:1–306`; `metrics_loop.go:526–645,689–710,849–961`; `alertsink.go:355–490`; `restartwatch_test.go:281–321` |
+| Envelope `internal/host/units` | approve — unchanged, approved in round 1 | `internal/host/units/carlos-litestream.service:1–50` |
+| Envelope `internal/metrics` | approve — unchanged, approved in round 1 | `internal/metrics/alert.go:14–75,110–158,227–253,421–461` |
+| Envelope `internal/ops` | approve — unchanged, approved in round 1 | `ops.go:93–218`; `litestream_memory.go:1–155`; `flock_unix.go:1–15`; `flock_windows.go:1–18` |
+
+**P1:** None.
+**P2:** None.
+**P3:** None.
+
+The prior failure’s trust boundary is now enforced before filesystem access. At `restartwatch.go:163–183`, effective UID zero produces an empty `restartWatchFile`; its methods return without calling either persistence function. The production caller supplies `os.Geteuid()` at `metrics_loop.go:899,921`. Both the startup load and subsequent saves use that guarded object. No other production caller bypasses it.
+
+The guard test at `restartwatch_test.go:284–321` checks that root never requests the path, gets an empty watch, and leaves a planted symlink’s target unchanged when saving. It also checks that non-root persistence round-trips. I inspected this test; I did not execute it.
+
+All five new `legacy`, `accepted-legacy`, frozen dispositions are approved. The revised `loadRestartWatch` basis correctly states the non-root restriction. The other four retain their round-1 approvals: operator-selected configuration and drop-in paths, count-only configuration parsing, and fixed systemctl arguments without a shell. Service execution, user, sandboxing and input paths remain unchanged. Alert formatting and evaluation introduce no filesystem reads or command execution.
+
+Reviewed proposal `7120ca1555ad7e1f4ae1ff48bc6cf4b2ab49a36e` under brief commit `86f6278c503572fc9f86de53ce83f98aa354a67c`, round 2 of 3. The requested diff used local `origin/main` at `56940c872a21ed9814b79b1a0f9ec84966cfd20a`. Remote verification and recording on #280 remain blocked by DNS failure for amadan.net. No files were edited, no subagents were spawned, and no tests were run. This round has no P1, so review stops here.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284.md b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284.md
new file mode 100644
index 000000000..f72d3a9f3
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-census-ls284.md
@@ -0,0 +1,50 @@
+# Census ls284, round 1 findings (gpt-6-astra, high, read-only)
+
+Proposal 67042203, brief e75eaa5a. Verbatim reviewer output.
+
+| Unit or envelope | Verdict | Lines read |
+|---|---|---|
+| `carlos-litestream.service:external` | approve | [carlos-litestream.service](internal/host/units/carlos-litestream.service:15), 15–50 |
+| `ops.go:runLitestream` | approve | [ops.go](internal/ops/ops.go:93), 93–201 |
+| `restartwatch.go:loadRestartWatch` | **reject** | [restartwatch.go](internal/host/restartwatch.go:147), 147–212 |
+| `restartwatch.go:platformUnitRestarts` | approve | `internal/host/restartwatch.go`, 215–269 |
+| `litestream_memory.go:configDBCount` | approve | [litestream_memory.go](internal/ops/litestream_memory.go:149), 149–155; `internal/ops/litestream.go`, 165–175, 596–607 |
+| `litestream_memory.go:writeMemoryDropIn` | approve | `internal/ops/litestream_memory.go`, 26–145; `internal/safefile/file_linux.go`, 15–42, 120–198 |
+| `ops.go:systemdDaemonReload` | approve | `internal/ops/ops.go`, 203–218 |
+| Envelope `internal/alerting` | approve | [ruletext.go](internal/alerting/ruletext.go:28), 28–70 |
+| Envelope `internal/host` | **reject** | `restartwatch.go`, 1–269; [metrics_loop.go](internal/host/metrics_loop.go:526), 526–709, 849–957; [alertsink.go](internal/host/alertsink.go:355), 355–511 |
+| Envelope `internal/host/units` | approve | `carlos-litestream.service`, 1–50 |
+| Envelope `internal/metrics` | approve | [alert.go](internal/metrics/alert.go:14), 14–158, 170–461 |
+| Envelope `internal/ops` | approve | `ops.go`, 93–218; `litestream_memory.go`, 1–155; [flock_unix.go](internal/ops/flock_unix.go:1), 1–15; [flock_windows.go](internal/ops/flock_windows.go:1), 1–18 |
+
+**P1 — Root-run agents follow agent-controlled restart-state paths.**
+
+Unit: `loadRestartWatch`; also rejects the `internal/host` envelope through `metricsLoop` and `saveRestartWatch`.
+
+Evidence:
+
+- Bootstrap assigns `/data` to `carlos` at [bootstrap.go:676](internal/host/bootstrap.go:676).
+- `metricsLoop` unconditionally loads and saves the watch at [metrics_loop.go:920–924](internal/host/metrics_loop.go:920), including when its effective UID is zero.
+- `loadRestartWatch` follows the path with `os.ReadFile` at [restartwatch.go:158](internal/host/restartwatch.go:158). Validation happens afterward.
+- `saveRestartWatch` writes through the predictable `restarts.json.tmp` path with `os.WriteFile` at [restartwatch.go:208–209](internal/host/restartwatch.go:208).
+
+Failure scenario: an actor with the box agent’s filesystem permissions plants a symlink at `restarts.json`, or at `restarts.json.tmp`. When an agent runs as root with monitoring enabled, it reads the selected target; the save can also truncate a root-owned target through the temporary-file symlink. The normal service’s `User=carlos` does not exclude root-run agents, which the existing code explicitly accommodates.
+
+Concrete fix: gate restart-history persistence on nonzero effective UID **before any filesystem access**. A root-run agent can retain an in-memory watch. Add a guard test proving root invokes neither loading nor saving. The existing refusal at [enginebeat.go:76–83](internal/host/enginebeat.go:76) establishes the same boundary.
+
+Fault family: **root must not follow paths writable or nameable by the box agent**. Parsing only alert data does not protect the preceding filesystem operation. The proposed frozen `accepted-legacy` disposition for `loadRestartWatch` therefore cannot be approved.
+
+**P2:** None.
+**P3:** None.
+
+The remaining approvals rest on these checks:
+
+- Drop-in selection comes from operator arguments or the fixed `/etc/systemd/system` default; the default applies only with the default `--out`. The marker is derived from that path. No tenant or registry value selects either path.
+- `configDBCount` rereads the generated configuration and uses only the entry count for sizing; it does not open the database paths it parses.
+- Both systemctl calls have fixed arguments and no shell. The service pattern is passed literally.
+- Litestream’s execution, user, sandboxing, configuration path and credentials path remain unchanged.
+- Alert text and metrics evaluation add no filesystem reads or command execution. Restart-history contents affect alert state, not command arguments or operational paths.
+
+Reviewed proposal `67042203fb9f30c71fbe0682058c56f35d70eef9` under the brief at `e75eaa5aa81e96f1be4b66ac9815944783e1c76b`, round 1 of 3. No files were edited, no subagents were spawned, and no tests were run. Recording on #280 was blocked by sandbox network restrictions.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-litestream-284-merge.md b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-litestream-284-merge.md
new file mode 100644
index 000000000..7b6f34a20
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-litestream-284-merge.md
@@ -0,0 +1,20 @@
+# litestream-oom-284 merge-diff review findings (gpt-6-astra, high, read-only)
+
+Tip bfb7367b, brief d06b5ad9. Verbatim reviewer output.
+
+P1: None found.
+
+P2 — Section 1, console port: the restart rule incorrectly displays “No threshold.”
+
+- **Evidence:** `rules.th.restarts` is missing, so [alertpages.go:437](internal/console/alertpages.go:437) falls back to “No threshold.” The evaluator actually fires above `RestartCount`, fixed at 3 ([alert.go:437](internal/metrics/alert.go:437)).
+- **Failure scenario:** An operator viewing Rules sees “more than 3 times in 10 minutes” beside a contradictory threshold description.
+- **Fix:** Add `rules.th.restarts` describing the fixed threshold; verify the rendered restart row.
+- **Fault family:** Operator-facing rule descriptions must match the evaluator’s behavior.
+
+P3: None.
+
+The incident identity, clear/close paths, startup beat handling and non-root persistence checks revealed no additional findings. SNS formatting has no truncation for long unit names, but that behavior predates this review’s baseline; restart events now bypass box sinks.
+
+Targeted tests could not start because the read-only sandbox prevented Go from creating its work directory. No files were edited, no subagents were spawned, and no full suites ran. Fix the P2 without reopening review.
+
+READY AFTER FIXES
\ No newline at end of file
diff --git a/internal/alerting/ruletext.go b/internal/alerting/ruletext.go
index 0e6eed593..58a838dd6 100644
--- a/internal/alerting/ruletext.go
+++ b/internal/alerting/ruletext.go
@@ -61,4 +61,10 @@ var BoxRuleText = map[string]RuleText{
HowLong: "Until it runs again, the console sends no alerts. Each box still sends its own.",
WhatToDo: "Check the console service on that box and restart it if it is stuck.",
},
+ // restarts is per unit: a box reports it as "restarts@<unit>".
+ "restarts": {
+ Title: "Restart loop",
+ HowLong: "The service may be down or unreliable after repeated restarts.",
+ WhatToDo: "Read the service's journal on that box to find out why it restarted repeatedly.",
+ },
}
diff --git a/internal/console/alertcopy_test.go b/internal/console/alertcopy_test.go
index a7f9d777a..019137ffb 100644
--- a/internal/console/alertcopy_test.go
+++ b/internal/console/alertcopy_test.go
@@ -9,9 +9,10 @@ import (
"time"
)
-// Every rule the console knows, and one it does not (a newer box's).
+// Every rule the console knows, one per-subject rule as a box reports it,
+// and one rule it does not know (a newer box's).
func alertCopyRules() []string {
- return append(slices.Sorted(maps.Keys(alertRuleLevels)), "rule_from_a_newer_box")
+ return append(slices.Sorted(maps.Keys(alertRuleLevels)), "restarts@carlos-litestream.service", "rule_from_a_newer_box")
}
// noFormatDebris fails on what a mismatched Sprintf leaves in text a person
diff --git a/internal/console/alertdetail_test.go b/internal/console/alertdetail_test.go
new file mode 100644
index 000000000..c2f4f4a2f
--- /dev/null
+++ b/internal/console/alertdetail_test.go
@@ -0,0 +1,130 @@
+package console
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/metrics"
+)
+
+// TestAlertTextForRestarts: the restarts rule says what its value means,
+// reported per unit or not, and an unknown rule still prints a bare number.
+func TestAlertTextForRestarts(t *testing.T) {
+ for _, c := range []struct {
+ rule string
+ value float64
+ want string
+ }{
+ {"restarts", 5, "5 restarts in 10 minutes"},
+ {"restarts@carlos-litestream.service", 5, "5 restarts in 10 minutes"},
+ {"somefuturerule", 3, "3"},
+ } {
+ if got := alertValueText(c.rule, c.value); got != c.want {
+ t.Errorf("alertValueText(%q, %v) = %q, want %q", c.rule, c.value, got, c.want)
+ }
+ }
+}
+
+// TestAlertRestartsNamesTheUnit: a per-unit rule is its own incident with
+// the boxes as members. It takes its kind's level and words, and its title
+// names the unit, so the headline and the clear say which unit it was.
+func TestAlertRestartsNamesTheUnit(t *testing.T) {
+ const rule = "restarts@carlos-litestream.service"
+ now := alertT0
+ if got := alertRuleTitle(rule); got != "Restart loop (carlos-litestream.service)" {
+ t.Errorf("title = %q", got)
+ }
+ if got := alertRuleTitle("somefuturerule@thing"); got != "somefuturerule@thing" {
+ t.Errorf("an unknown per-subject rule keeps its ID: %q", got)
+ }
+ if alertRuleLevel(rule) != alertRuleLevels["restarts"] {
+ t.Errorf("level = %q, want the kind's %q", alertRuleLevel(rule), alertRuleLevels["restarts"])
+ }
+ // An incident, not a warning (Paul, 2026-11-03): a platform service in
+ // a restart loop is one whose work stops, and for the replicator that
+ // means the box's databases stop reaching the bucket.
+ if alertRuleLevel(rule) != alerting.LevelIncident {
+ t.Errorf("level = %q, want %q", alertRuleLevel(rule), alerting.LevelIncident)
+ }
+
+ sig := newAlertSignals()
+ sig.add(alertSignal{Key: alertKey{alertScopeFleet, rule, "box-a"}, Level: alertRuleLevel(rule), Firing: true, Value: 5, At: now})
+ in := alertIncident{Scope: alertScopeFleet, Rule: rule, Level: alertRuleLevel(rule), Members: []string{"box-a"}, OpenedAt: now}
+ n := alertEmitNote(alertEmit{Incident: in, Kind: alertKindFire}, sig, now)
+ if h := alertHeadline(n); h != "Restart loop (carlos-litestream.service) on box-a" {
+ t.Errorf("fire headline = %q", h)
+ }
+ if n.What != "A platform service on box-a has restarted repeatedly. Reading: 5 restarts in 10 minutes." {
+ t.Errorf("fire what = %q", n.What)
+ }
+ if n.HowLong != alerting.BoxRuleText["restarts"].HowLong || n.WhatToDo != alerting.BoxRuleText["restarts"].WhatToDo {
+ t.Errorf("fire lines = %q / %q", n.HowLong, n.WhatToDo)
+ }
+
+ in.CloseReason = alertCloseCleared
+ n = alertEmitNote(alertEmit{Incident: in, Kind: alertKindClear}, sig, now)
+ if n.What != "Restart loop (carlos-litestream.service) has cleared on box-a." {
+ t.Errorf("clear what = %q", n.What)
+ }
+}
+
+// TestAlertRestartsSettingsAreTheKinds: the Rules section has one restarts
+// rule, and what an operator sets there (here, turning it off) holds for
+// every unit's incident.
+func TestAlertRestartsSettingsAreTheKinds(t *testing.T) {
+ now := alertT0
+ in := alertIncident{ID: 7, Scope: alertScopeFleet, Rule: "restarts@carlos-relay.service", Level: alertRuleLevel("restarts"),
+ Members: []string{"box-a"}, OpenedAt: now}
+ conns := []alertConnector{{ID: 1, Kind: alertConnectorEmail, Name: "me", Confirmed: true}}
+ emits := []alertEmit{{Incident: in, Kind: alertKindFire}}
+ if rows := alertEmitRows(context.Background(), emits, nil, conns, newAlertSignals(), now); len(rows) != 1 {
+ t.Fatalf("with no setting the fire goes to every connector: %d rows", len(rows))
+ }
+ off := map[string]alertRuleSetting{"restarts": {Enabled: false}}
+ if rows := alertEmitRows(context.Background(), emits, off, conns, newAlertSignals(), now); len(rows) != 0 {
+ t.Fatalf("restarts turned off still queued %d rows", len(rows))
+ }
+}
+
+// TestSweepAlertsSplitsPerUnitRules: the dashboard's row shows a per-unit
+// rule as its kind with the unit beside it.
+func TestSweepAlertsSplitsPerUnitRules(t *testing.T) {
+ srv, rel := newMetricsFixture(t)
+ writeAlertState(t, rel, metrics.AlertState{
+ V: 1, Box: "box-a", UpdatedAt: time.Now(),
+ Rules: map[string]metrics.RuleState{
+ "restarts@carlos-litestream.service": {Firing: true, Value: 4, FiredAt: time.Now()},
+ "restarts@carlos-relay.service": {},
+ "disk": {Firing: true, Value: 0.9, FiredAt: time.Now()},
+ },
+ })
+ rows, err := srv.sweepAlerts(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := map[string]string{}
+ for _, r := range rows {
+ got[r.Rule] = r.Detail
+ }
+ if len(rows) != 2 || got["restarts"] != "carlos-litestream.service" || got["disk"] != "" {
+ t.Fatalf("rows = %+v", rows)
+ }
+ if !strings.Contains(alertValueText(rows[1].Rule, rows[1].Value), "restarts in 10 minutes") {
+ t.Fatalf("row value = %q", alertValueText(rows[1].Rule, rows[1].Value))
+ }
+}
+
+// TestAlertRestartsRuleRowStatesItsThreshold: the Rules section shows the
+// fixed threshold the box evaluates, not "No threshold".
+func TestAlertRestartsRuleRowStatesItsThreshold(t *testing.T) {
+ v := alertRuleRow("restarts", nil, nil, alertNoise{})
+ if v.Threshold != alertPageCopy["rules.th.restarts"] || !strings.Contains(v.Threshold, "3 restarts in 10 minutes") {
+ t.Fatalf("restarts threshold = %q", v.Threshold)
+ }
+ if !strings.Contains(v.When, "more than 3 times in 10 minutes") {
+ t.Fatalf("restarts when = %q", v.When)
+ }
+}
diff --git a/internal/console/alertengine_pass.go b/internal/console/alertengine_pass.go
index 8831689d5..f45cc8071 100644
--- a/internal/console/alertengine_pass.go
+++ b/internal/console/alertengine_pass.go
@@ -340,7 +340,7 @@ func alertEmitRows(ctx context.Context, emits []alertEmit, settings map[string]a
if in.Scope != alertScopeFleet {
continue // account connectors are a later plan
}
- st, set := settings[in.Rule]
+ st, set := settings[alertRuleKind(in.Rule)]
if set && !st.Enabled {
continue
}
@@ -377,6 +377,7 @@ func alertRuleConnectors(st alertRuleSetting, conns []alertConnector) []int64 {
// alertValued are the rules whose value means something in a message.
var alertValued = map[string]bool{
"disk": true, "mem": true, "cpu": true, "lag": true, "geoip": true, "disk_eta": true, "box_silent": true, "cert_expiring": true,
+ "restarts": true,
}
// alertEmitNote is what one emit says, stored without links (ruling R-2).
@@ -425,7 +426,7 @@ func alertEmitNote(em alertEmit, sig *alertSignals, now time.Time) alertNote {
} else {
n.What = alertRuleCopy(in.Rule, "what.none")
}
- if v, ok := sig.value(alertKey{in.Scope, in.Rule, n.Subject}); ok && alertValued[in.Rule] && named {
+ if v, ok := sig.value(alertKey{in.Scope, in.Rule, n.Subject}); ok && alertValued[alertRuleKind(in.Rule)] && named {
n.What += " " + fmt.Sprintf(alertCopy["what.value"], alertValueText(in.Rule, v))
}
switch {
@@ -466,9 +467,10 @@ func alertUnits(n int, unit string) string {
return strconv.Itoa(n) + " " + unit + "s"
}
-// alertRuleCopy is rule's line part, or the default rule's.
+// alertRuleCopy is rule's line part (its kind's, for a per-subject rule),
+// or the default rule's.
func alertRuleCopy(rule, part string) string {
- if s, ok := alertCopy["rule."+rule+"."+part]; ok {
+ if s, ok := alertCopy["rule."+alertRuleKind(rule)+"."+part]; ok {
return s
}
return alertCopy["rule.default."+part]
@@ -727,9 +729,10 @@ func writeAlertBeatFile(path string, now time.Time) error {
//
// An unknown rule name (a future rule this console has not been taught) is
// rendered as a bare number rather than being given someone else's unit: a
-// unitless figure is honest, a wrong unit is not.
+// unitless figure is honest, a wrong unit is not. A per-subject rule
+// ("restarts@<unit>") has its kind's unit.
func alertValueText(rule string, value float64) string {
- switch rule {
+ switch alertRuleKind(rule) {
case "disk", "mem", "cpu":
return fmt.Sprintf("%.0f%%", value*100)
case "lag":
@@ -743,6 +746,8 @@ func alertValueText(rule string, value float64) string {
return fmt.Sprintf("%.0f minutes since its last report", value)
case "cert_expiring":
return fmt.Sprintf("%.0f days left", value)
+ case "restarts":
+ return fmt.Sprintf("%d restarts in 10 minutes", int(value))
default:
return strconv.FormatFloat(value, 'g', -1, 64)
}
diff --git a/internal/console/alertnotify.go b/internal/console/alertnotify.go
index 41b8f6d98..850a1ec9d 100644
--- a/internal/console/alertnotify.go
+++ b/internal/console/alertnotify.go
@@ -37,6 +37,7 @@ import (
"unicode/utf8"
"github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/metrics"
)
const (
@@ -193,6 +194,14 @@ var alertCopy = map[string]string{
"rule.engine_silent.how_long": alerting.BoxRuleText["engine_silent"].HowLong,
"rule.engine_silent.what_to_do": alerting.BoxRuleText["engine_silent"].WhatToDo,
+ // restarts is per unit ("restarts@<unit>"): the title names the unit
+ // (alertRuleTitle), so the what names only the box.
+ "rule.restarts.title": alerting.BoxRuleText["restarts"].Title,
+ "rule.restarts.what": "A platform service on %s has restarted repeatedly.",
+ "rule.restarts.what.none": "A platform service has restarted repeatedly.",
+ "rule.restarts.how_long": alerting.BoxRuleText["restarts"].HowLong,
+ "rule.restarts.what_to_do": alerting.BoxRuleText["restarts"].WhatToDo,
+
"rule.box_silent.title": "Box silent",
"rule.box_silent.what": "%s has stopped reporting.",
"rule.box_silent.what.none": "A box has stopped reporting.",
@@ -258,12 +267,19 @@ var alertCopy = map[string]string{
}
// alertRuleTitle is rule's display name. A rule this console has no name for
-// (a newer box's) keeps its ID, which is honest and never empty.
+// (a newer box's) keeps its ID, which is honest and never empty. A
+// per-subject rule ("restarts@<unit>") is its kind's name with the subject
+// after it, so every line that names the rule names the unit too.
func alertRuleTitle(rule string) string {
- if t, ok := alertCopy["rule."+rule+".title"]; ok {
- return t
+ kind, subject := metrics.SplitRule(rule)
+ t, ok := alertCopy["rule."+kind+".title"]
+ switch {
+ case !ok:
+ return rule
+ case subject != "":
+ return t + " (" + subject + ")"
}
- return rule
+ return t
}
// alertHeadline is n's one line. A message with no member to name uses the
diff --git a/internal/console/alertpages.go b/internal/console/alertpages.go
index 604e0685c..47652e092 100644
--- a/internal/console/alertpages.go
+++ b/internal/console/alertpages.go
@@ -102,6 +102,7 @@ var alertPageCopy = map[string]string{
"rules.when.lag": "A box's mail relay is behind by more than the threshold.",
"rules.when.geoip": "A box's location database is old, expiring, not loading or failing to update.",
"rules.when.engine_silent": "The alert engine has not run for 10 minutes. Only the console box reports this.",
+ "rules.when.restarts": "A platform service on a box restarts more than 3 times in 10 minutes. Each service is its own alert.",
"rules.when.box_silent": "A box has not reported for longer than the threshold.",
"rules.when.service_down": "A platform service is reported down.",
"rules.when.cert_expiring": "A served host's certificate expires within the threshold.",
@@ -114,6 +115,7 @@ var alertPageCopy = map[string]string{
"rules.th.lag": "Fixed at 900 seconds. Not configurable.",
"rules.th.geoip": "Fixed. Not configurable.",
"rules.th.engine_silent": "Fixed at 10 minutes. Not configurable.",
+ "rules.th.restarts": "Fixed at more than 3 restarts in 10 minutes. Not configurable.",
"rules.th.readonly": "Set on each box, not here.",
"rules.th.none": "No threshold.",
"rules.th.box_silent": "Silent after (minutes)",
@@ -210,7 +212,7 @@ const (
// alertRuleOrder is the Rules section, top to bottom: the box rules, then
// the console's. It names every rule in alertRuleLevels
// (TestAlertRuleOrderCoversEveryRule).
-var alertRuleOrder = []string{"disk_eta", "disk", "mem", "cpu", "lag", "geoip", "engine_silent",
+var alertRuleOrder = []string{"disk_eta", "disk", "mem", "cpu", "lag", "geoip", "engine_silent", "restarts",
"box_silent", "service_down", "cert_expiring", "alert_delivery_broken", "seal_key"}
// alertThresholdBounds are the editable thresholds' whole-number bounds:
@@ -386,8 +388,16 @@ func (s *Server) alertsView() (*alertsView, error) {
v.Kinds = append(v.Kinds, alertKindForm{Kind: k.kind, Heading: alertPageCopy["kind."+k.kind],
Label: alertPageCopy["conn.add."+k.kind], Help: alertPageCopy["conn.add."+k.kind+".help"], InputType: k.input})
}
+ // A per-subject rule's incidents ("restarts@<unit>") count towards its
+ // kind's row: the kind is what an operator sets.
+ byKind := map[string]alertNoise{}
+ for rule, n := range noise {
+ k := byKind[alertRuleKind(rule)]
+ k.Fired, k.QuickClears = k.Fired+n.Fired, k.QuickClears+n.QuickClears
+ byKind[alertRuleKind(rule)] = k
+ }
for _, rule := range alertRuleOrder {
- v.Rules = append(v.Rules, alertRuleRow(rule, settings, conns, noise[rule]))
+ v.Rules = append(v.Rules, alertRuleRow(rule, settings, conns, byKind[rule]))
}
return v, nil
}
diff --git a/internal/console/alertsignals.go b/internal/console/alertsignals.go
index e63936fc7..891270980 100644
--- a/internal/console/alertsignals.go
+++ b/internal/console/alertsignals.go
@@ -451,6 +451,7 @@ var alertRuleLevels = map[string]string{
"lag": alerting.LevelWarning,
"geoip": alerting.LevelWarning,
"engine_silent": alerting.LevelIncident,
+ "restarts": alerting.LevelIncident,
"box_silent": alerting.LevelIncident,
"service_down": alerting.LevelIncident,
"cert_expiring": alerting.LevelWarning,
@@ -458,6 +459,16 @@ var alertRuleLevels = map[string]string{
"seal_key": alerting.LevelIncident,
}
+// alertRuleKind is a rule's kind: the rule itself, or for a per-subject
+// box rule ("restarts@<unit>") its name without the subject. A per-subject
+// rule is its own incident, one per subject, with the boxes as members,
+// so one unit's loop never hides another's. Its level, words and settings
+// are its kind's.
+func alertRuleKind(rule string) string {
+ kind, _ := metrics.SplitRule(rule)
+ return kind
+}
+
// alertConsoleRules are the rules the console evaluates. Every other fleet
// rule is a box rule, read from the box's alert object.
var alertConsoleRules = map[string]bool{
@@ -465,9 +476,9 @@ var alertConsoleRules = map[string]bool{
}
// alertRuleLevel is rule's level; a rule this console has not been taught
-// is a warning.
+// is a warning. A per-subject rule ("restarts@<unit>") has its kind's.
func alertRuleLevel(rule string) string {
- if l, ok := alertRuleLevels[rule]; ok {
+ if l, ok := alertRuleLevels[alertRuleKind(rule)]; ok {
return l
}
return alerting.LevelWarning
diff --git a/internal/console/metricsview.go b/internal/console/metricsview.go
index 5ffa61f7c..90c3a77b9 100644
--- a/internal/console/metricsview.go
+++ b/internal/console/metricsview.go
@@ -102,6 +102,9 @@ type AlertRow struct {
Box, Rule string
Value float64
FiredAt time.Time
+ // Detail is what a per-subject rule is about: the unit, for restarts.
+ // Empty for a rule with no subject.
+ Detail string
}
// metricsCacheTTL is how soon after a successful sweep LoadMetrics considers
@@ -1029,7 +1032,10 @@ func (s *Server) sweepAlerts(ctx context.Context) ([]AlertRow, error) {
if !rs.Firing {
continue
}
- rows = append(rows, AlertRow{Box: box, Rule: name, Value: rs.Value, FiredAt: rs.FiredAt})
+ // A per-subject rule ("restarts@<unit>") shows as its kind with
+ // the subject beside it.
+ kind, about := metrics.SplitRule(name)
+ rows = append(rows, AlertRow{Box: box, Rule: kind, Value: rs.Value, FiredAt: rs.FiredAt, Detail: about})
}
}
return rows, nil
diff --git a/internal/console/templates/metrics.html b/internal/console/templates/metrics.html
index 4a3399886..0639237ee 100644
--- a/internal/console/templates/metrics.html
+++ b/internal/console/templates/metrics.html
@@ -14,7 +14,7 @@
{{range .MetricAlerts}}
<tr>
<td>{{.Box}}</td>
- <td>{{.Rule}}</td>
+ <td>{{.Rule}}{{if .Detail}} ({{.Detail}}){{end}}</td>
<td co-neg>{{alertVal .Rule .Value}}</td>
<td co-m-hide>{{fmtTime .FiredAt}}</td>
</tr>
diff --git a/internal/host/alertsink.go b/internal/host/alertsink.go
index 60752708e..d07e3d421 100644
--- a/internal/host/alertsink.go
+++ b/internal/host/alertsink.go
@@ -375,7 +375,7 @@ func formatAlert(rules metrics.Rules, at time.Time, ev metrics.Event) (subject,
}
fmt.Fprintf(&b, "this was reported at %s.\n", at.UTC().Format("2006-01-02 15:04 MST"))
if ev.Firing {
- if t, ok := alerting.BoxRuleText[ev.Rule]; ok {
+ if t, ok := alerting.BoxRuleText[alertRuleKind(ev.Rule)]; ok {
fmt.Fprintf(&b, "%s: %s\n%s: %s\n", alerting.LabelHowLong, t.HowLong, alerting.LabelWhatToDo, t.WhatToDo)
}
b.WriteString("it will be reported again when it clears.\n")
@@ -385,12 +385,25 @@ func formatAlert(rules metrics.Rules, at time.Time, ev metrics.Event) (subject,
}
// alertRuleName is a rule's display name, or its ID for a rule this agent
-// has no name for.
+// has no name for. A per-subject rule ("restarts@<unit>") is named by its
+// kind, with the subject after it.
func alertRuleName(rule string) string {
- if t, ok := alerting.BoxRuleText[rule]; ok {
- return t.Title
+ kind, subject := metrics.SplitRule(rule)
+ t, ok := alerting.BoxRuleText[kind]
+ switch {
+ case !ok:
+ return rule
+ case subject != "":
+ return t.Title + " (" + subject + ")"
}
- return rule
+ return t.Title
+}
+
+// alertRuleKind is a rule's kind: the rule itself, or a per-subject rule's
+// name without its subject.
+func alertRuleKind(rule string) string {
+ kind, _ := metrics.SplitRule(rule)
+ return kind
}
func alertSubject(ev metrics.Event) string {
@@ -403,7 +416,8 @@ func alertSubject(ev metrics.Event) string {
// alertSentence is the lower-case "what is wrong" clause, shared by the
// subject and the body.
func alertSentence(ev metrics.Event) string {
- switch ev.Rule {
+ name, subject := metrics.SplitRule(ev.Rule)
+ switch name {
case "disk":
return fmt.Sprintf("disk is %s full on %s", pct(ev.Value), ev.Box)
case "mem":
@@ -414,6 +428,8 @@ func alertSentence(ev metrics.Event) string {
return fmt.Sprintf("mail relay lag is %d seconds on %s", int64(ev.Value), ev.Box)
case "geoip":
return geoipAlertSentence(ev)
+ case "restarts":
+ return fmt.Sprintf("%s restarted %d times in %d minutes on %s", subject, int64(ev.Value), int(restartWindow.Minutes()), ev.Box)
case "disk_eta":
return fmt.Sprintf("the disk on %s is filling up", ev.Box)
case "engine_silent":
@@ -424,7 +440,8 @@ func alertSentence(ev metrics.Event) string {
}
func alertClearSentence(ev metrics.Event) string {
- switch ev.Rule {
+ name, subject := metrics.SplitRule(ev.Rule)
+ switch name {
case "disk":
return fmt.Sprintf("disk is back to %s full on %s", pct(ev.Value), ev.Box)
case "mem":
@@ -439,13 +456,16 @@ func alertClearSentence(ev metrics.Event) string {
return fmt.Sprintf("the disk on %s is no longer filling up", ev.Box)
case "engine_silent":
return fmt.Sprintf("the alert engine on %s is running again", ev.Box)
+ case "restarts":
+ return fmt.Sprintf("%s has stopped restarting on %s", subject, ev.Box)
default:
return fmt.Sprintf("%s has cleared on %s", alertRuleName(ev.Rule), ev.Box)
}
}
func alertLevel(r metrics.Rules, rule string) (string, bool) {
- switch rule {
+ name, _ := metrics.SplitRule(rule)
+ switch name {
case "disk":
return pct(r.DiskFrac), true
case "mem":
@@ -454,6 +474,8 @@ func alertLevel(r metrics.Rules, rule string) (string, bool) {
return pct(r.CPUFrac), true
case "lag":
return fmt.Sprintf("%d seconds", r.LagSecs), true
+ case "restarts":
+ return fmt.Sprintf("more than %d restarts in %d minutes", int64(r.RestartCount), int(restartWindow.Minutes())), true
}
return "", false
}
diff --git a/internal/host/alertsink_test.go b/internal/host/alertsink_test.go
index 1a14b47da..6f5571422 100644
--- a/internal/host/alertsink_test.go
+++ b/internal/host/alertsink_test.go
@@ -15,6 +15,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/sns"
+ "github.com/carlosframework/platform/internal/alerting"
"github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/release"
)
@@ -60,6 +61,22 @@ func TestFormatAlertFireAndClear(t *testing.T) {
subjectHas: []string{"carlos alert cleared", "disk", "30%", "ada-stargazing"},
bodyHas: []string{"back", "30%", "ada-stargazing"},
},
+ {
+ name: "restarts fires and names the unit",
+ ev: metrics.Event{Rule: "restarts@carlos-litestream.service", Firing: true, Value: 6, Box: "box-a"},
+ subjectHas: []string{"carlos alert", "carlos-litestream.service", "restarted 6 times", "10 minutes", "box-a"},
+ bodyHas: []string{"carlos-litestream.service", "more than 3 restarts in 10 minutes", "clears",
+ // The rule's own lines, looked up by its kind, and the footer
+ // naming the unit beside the rule's display name.
+ alerting.BoxRuleText["restarts"].HowLong, alerting.BoxRuleText["restarts"].WhatToDo,
+ "rule: Restart loop (carlos-litestream.service)\n"},
+ },
+ {
+ name: "restarts clears",
+ ev: metrics.Event{Rule: "restarts@carlos-litestream.service", Firing: false, Value: 0, Box: "box-a"},
+ subjectHas: []string{"carlos alert cleared", "carlos-litestream.service", "stopped restarting", "box-a"},
+ bodyHas: []string{"carlos-litestream.service", "stopped restarting"},
+ },
{
name: "mem fires with its sustain window",
ev: metrics.Event{Rule: "mem", Firing: true, Value: 0.94, Box: "box-a"},
@@ -245,10 +262,10 @@ func TestAlertTickDeliversThroughSinks(t *testing.T) {
disk := 0.95
latest := metrics.Sample{At: sinkTestAt, Host: metrics.HostSample{DiskFrac: &disk}}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks, nil, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, alertReadings{}, statePath, sinks, nil, nil); err != nil {
t.Fatal(err)
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks, nil, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, alertReadings{}, statePath, sinks, nil, nil); err != nil {
t.Fatal(err)
}
if len(pub.in) != 1 {
@@ -261,7 +278,7 @@ func TestAlertTickDeliversThroughSinks(t *testing.T) {
// Clearing is a transition too.
low := 0.30
cleared := metrics.Sample{At: sinkTestAt.Add(time.Minute), Host: metrics.HostSample{DiskFrac: &low}}
- if err := alertTick(ctx, store, box, rules, st, cleared, statePath, sinks, nil, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, cleared, alertReadings{}, statePath, sinks, nil, nil); err != nil {
t.Fatal(err)
}
if len(pub.in) != 2 || !strings.Contains(deref(pub.in[1].Subject), "cleared") {
diff --git a/internal/host/enginebeat_linux_test.go b/internal/host/enginebeat_linux_test.go
index e528461fe..30a18c18b 100644
--- a/internal/host/enginebeat_linux_test.go
+++ b/internal/host/enginebeat_linux_test.go
@@ -75,7 +75,7 @@ func (r *beatRig) tick(at time.Time, beat *engineBeatWatch) []metrics.Event {
r.t.Helper()
before := len(r.posted)
if err := alertTick(context.Background(), r.store, "box-a", metrics.DefaultRules(), r.st,
- metrics.Sample{At: at}, r.statePath, r.sinks, nil, beat); err != nil {
+ metrics.Sample{At: at}, alertReadings{}, r.statePath, r.sinks, nil, beat); err != nil {
r.t.Fatal(err)
}
return r.posted[before:]
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go
index 1a22737f5..04dd7eb02 100644
--- a/internal/host/metrics_loop.go
+++ b/internal/host/metrics_loop.go
@@ -40,7 +40,10 @@ type sampleProbes struct {
// (metricsOwners), read before and after units so a reading is tagged
// only when nothing changed during it. nil tags nothing.
owners func() map[string]metrics.Vouch
- now func() time.Time
+ // restarts is each platform unit's systemd restart counter (see
+ // restartWatch). A nil func, or a nil map from it, is "could not ask".
+ restarts func() map[string]unitRestartState
+ now func() time.Time
}
// samplerMaxBuf hard-caps sm.buf at ~2h of 60s ticks. metricsFlush only
@@ -521,7 +524,7 @@ func pruneStaleRaw(ctx context.Context, s release.Store, box string, now time.Ti
// rules (disk, lag; sustain 0) retry the same way, just starting from
// their very first over-threshold tick instead of a sustain deadline.
func alertTick(ctx context.Context, s release.Store, box string, rules metrics.Rules,
- st *metrics.AlertState, latest metrics.Sample, statePath string,
+ st *metrics.AlertState, latest metrics.Sample, extra alertReadings, statePath string,
sinks *alertSinks, trend *diskTrend, beat *engineBeatWatch) error {
obs := metrics.Observation{
@@ -531,6 +534,7 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R
DiskFrac: latest.Host.DiskFrac,
LagSecs: nil, // v1: no lag reading feeds the agent loop yet
GeoIP: geoIPAlertReading(latest.At),
+ Restarts: extra.restarts,
}
if trend != nil {
v, eta := trend.verdict(latest.At)
@@ -584,6 +588,14 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R
return publishErr
}
+// alertReadings are the readings alertTick takes that are not part of a
+// metrics.Sample: they describe the box's units rather than its resources,
+// and are not stored in the raw chunks. The zero value is "no reading", which
+// leaves every rule they feed exactly as it was.
+type alertReadings struct {
+ restarts map[string]metrics.UnitRestarts // see restartWatch.tick
+}
+
// persistAlertState writes st to path as indented JSON via the repo's
// standard temp+rename idiom (internal/appconfig/sync.go's renderEnv,
// internal/release/store.go's DirStore.Put): a crashed write must never
@@ -691,8 +703,9 @@ func realSampleProbes(execRoot string, src unitSources, owners func() map[string
}
return mergeNested(realUnitReadings(execRoot, stamped), nestedUnitReadings(src.nestedRoot, nested, src.nestedAtStart))
},
- owners: owners,
- now: time.Now,
+ owners: owners,
+ restarts: platformUnitRestarts,
+ now: time.Now,
}
}
@@ -898,6 +911,33 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr
// alerted is what keeps a standing refusal from paging every minute.
// dataDir() is the bake dir the agent hands release.BakeDir.
var refusals refusalWatch
+
+ // The restart watch is the one reading taken before the first sleep. It
+ // is loaded from the last run and sampled at once, so an agent that is
+ // itself restarting every minute or so still adds each restart to the
+ // count and gets a chance to say so. An agent that dies within seconds of
+ // starting cannot report on itself from the inside at all. A root-run
+ // agent keeps the watch in memory only (restartWatchFile).
+ watchFile := newRestartWatchFile(euid, restartWatchPath)
+ if watchFile.path == "" {
+ log.Printf("agent: restart watch: agent runs as root, so the watch is kept in memory only")
+ }
+ restarts := watchFile.load()
+ restartTick := func(at time.Time) alertReadings {
+ extra := alertReadings{restarts: restarts.tick(at, probes.restarts())}
+ if err := watchFile.save(restarts); err != nil {
+ log.Printf("agent: restart watch: save %s: %v", watchFile.path, err)
+ }
+ return extra
+ }
+ // A sample with no host readings: every rule but restarts sees nil and
+ // is left exactly as it was. No forecast point either. The engine beat
+ // goes in all the same: inside its grace it holds engine_silent's state,
+ // where nil would read as unarmed and clear a fire restored from disk.
+ started := time.Now()
+ if err := alertTick(ctx, s, box, rules, &st, metrics.Sample{At: started}, restartTick(started), statePath, sinks, nil, beat); err != nil {
+ log.Printf("agent: alert tick: %v", err)
+ }
for {
time.Sleep(60 * time.Second)
tick++
@@ -908,7 +948,7 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr
sm.tick(probes)
latest := sm.buf[len(sm.buf)-1]
recordDiskPoint(&processDiskTrend, probes.diskBytes, latest.At)
- if err := alertTick(ctx, s, box, rules, &st, latest, statePath, sinks, &processDiskTrend, beat); err != nil {
+ if err := alertTick(ctx, s, box, rules, &st, latest, restartTick(latest.At), statePath, sinks, &processDiskTrend, beat); err != nil {
log.Printf("agent: alert tick: %v", err)
}
diff --git a/internal/host/metrics_loop_test.go b/internal/host/metrics_loop_test.go
index f27e45356..66ec8f166 100644
--- a/internal/host/metrics_loop_test.go
+++ b/internal/host/metrics_loop_test.go
@@ -143,7 +143,7 @@ func TestMetricsLoopStoreHonorsFleetPrefix(t *testing.T) {
firing := 0.95
latest := metrics.Sample{At: at, Host: metrics.HostSample{DiskFrac: &firing}}
statePath := filepath.Join(t.TempDir(), "monitor", "alerts.json")
- if err := alertTick(ctx, s, box, rules, st, latest, statePath, nil, nil, nil); err != nil {
+ if err := alertTick(ctx, s, box, rules, st, latest, alertReadings{}, statePath, nil, nil, nil); err != nil {
t.Fatal(err)
}
if _, _, err := under.Get(ctx, "fleets/pi/"+metrics.AlertKey(box)); err != nil {
@@ -222,7 +222,7 @@ func TestAlertTickPersistsPublishesAndPosts(t *testing.T) {
return nil
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, alertReadings{}, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatal(err)
}
@@ -248,7 +248,7 @@ func TestAlertTickPersistsPublishesAndPosts(t *testing.T) {
}
// Second, identical tick: already firing, no new transition -> no post.
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, alertReadings{}, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatal(err)
}
if len(posts) != 1 {
@@ -274,7 +274,7 @@ func TestAlertTickWebhookFailureDoesNotBlock(t *testing.T) {
}
post := func(url string, body []byte) error { return errors.New("webhook unreachable") }
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, alertReadings{}, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatalf("alertTick must not fail on a webhook error: %v", err)
}
if _, err := os.Stat(statePath); err != nil {
@@ -316,7 +316,7 @@ func TestAlertTickPersistFailureDoesNotSuppressPublish(t *testing.T) {
return nil
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, alertReadings{}, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatalf("alertTick must not fail just because the local state write failed: %v", err)
}
if !posted {
@@ -550,7 +550,7 @@ func TestAlertTickRetriesTransitionAfterPublishFailure(t *testing.T) {
}
failStore := &failingPutStore{Store: release.NewDirStore(t.TempDir())}
- if err := alertTick(ctx, failStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err == nil {
+ if err := alertTick(ctx, failStore, box, rules, st, latest, alertReadings{}, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err == nil {
t.Fatal("expected alertTick to return the publish error against a Put-always-fails store")
}
if st.Rules["disk"].Firing {
@@ -563,7 +563,7 @@ func TestAlertTickRetriesTransitionAfterPublishFailure(t *testing.T) {
// Retry with the SAME observation against a working store: the pending
// transition must reproduce, publish, and post again.
workingStore := release.NewDirStore(t.TempDir())
- if err := alertTick(ctx, workingStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
+ if err := alertTick(ctx, workingStore, box, rules, st, latest, alertReadings{}, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatalf("retry against a working store: %v", err)
}
if !st.Rules["disk"].Firing {
@@ -963,7 +963,7 @@ func (r *forecastRig) tick(used uint64) (fired, cleared bool) {
r.trend.add(metrics.DiskPoint{At: r.at, UsedBytes: used, TotalBytes: 100 * gib})
was := r.st.Rules["disk_eta"].Firing
latest := metrics.Sample{At: r.at}
- if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, r.statePath, r.sinks, r.trend, nil); err != nil {
+ if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, alertReadings{}, r.statePath, r.sinks, r.trend, nil); err != nil {
r.t.Fatal(err)
}
now := r.st.Rules["disk_eta"].Firing
@@ -1006,7 +1006,7 @@ func TestAlertTickSinksIncidentOnly(t *testing.T) {
r.at = r.at.Add(time.Minute)
full := 0.95
latest := metrics.Sample{At: r.at, Host: metrics.HostSample{DiskFrac: &full}}
- if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, r.statePath, r.sinks, r.trend, nil); err != nil {
+ if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, alertReadings{}, r.statePath, r.sinks, r.trend, nil); err != nil {
t.Fatal(err)
}
if len(posted) != 1 || posted[0].Rule != "disk" || !posted[0].Firing {
diff --git a/internal/host/restartwatch.go b/internal/host/restartwatch.go
new file mode 100644
index 000000000..66e6be32b
--- /dev/null
+++ b/internal/host/restartwatch.go
@@ -0,0 +1,306 @@
+package host
+
+// A unit that cannot stay up looks healthy from every other angle the agent
+// has. systemd restarts it, the sampler finds its cgroup on most ticks, and
+// its memory and CPU read as modest because it never lives long enough to use
+// either. Discussion #284 is that case: carlos-litestream was OOM-killed four
+// seconds into every start for two hours, restarted over 900 times, and the
+// only thing that noticed was a person asking whether backups were running.
+//
+// systemd counts those restarts itself (NRestarts), so the agent asks it once
+// a tick and alerts, per unit, on how fast the number is moving.
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+)
+
+// restartWindow is how far back a unit's restarts are counted. A unit's
+// restarts rule fires on a count inside it (metrics.Rules.RestartCount) and
+// can clear only after the whole of it passes with none.
+const restartWindow = 10 * time.Minute
+
+// restartProbeTimeout bounds the one systemctl call a tick makes. The call
+// shares a goroutine with every other alert rule, so a systemd that does not
+// answer must cost a reading, not the disk alert.
+const restartProbeTimeout = 5 * time.Second
+
+// unitRestartState is one unit as systemd reports it.
+type unitRestartState struct {
+ restarts int64 // NRestarts
+ down bool // ActiveState is failed, or activating between restarts
+}
+
+// restartWatch remembers each watched unit's restarts over restartWindow. It
+// is saved after every tick (saveRestartWatch) and loaded at agent start, so
+// the agent's own restarts are counted: carlos-edge.service is one of the
+// units, and a watch held only in memory would die with each of them.
+type restartWatch struct {
+ // V is the saved shape's version; loadRestartWatch takes no other.
+ V int `json:"v"`
+ // At is the last tick that got an answer from systemd.
+ At time.Time `json:"at"`
+ Units map[string]*unitRestartHistory `json:"units"`
+}
+
+// restartWatchVersion is the only saved shape this build reads.
+const restartWatchVersion = 1
+
+type unitRestartHistory struct {
+ // Last is the counter at the last tick.
+ Last int64 `json:"last"`
+ // Bumps are the counter's rises inside the window, each dated by the
+ // tick that saw it.
+ Bumps []restartBump `json:"bumps,omitempty"`
+ // QuietSince is when the watch first met this unit, or last saw it
+ // restart or have its counter reset, whichever is later.
+ QuietSince time.Time `json:"quiet_since"`
+}
+
+type restartBump struct {
+ At time.Time `json:"at"`
+ N int64 `json:"n"`
+}
+
+// tick records units as of now and returns each unit's reading. nil units
+// means systemd could not be asked: the reading is nil and the history is
+// kept.
+//
+// A first sighting is a baseline, not a restart: a unit that had restarted
+// 900 times before the watch met it has not restarted "now".
+//
+// systemd zeroes NRestarts when a unit is started by hand. Restarts already
+// counted stay counted, and whatever the counter shows after the reset is
+// added to them, so an operator's restart in the middle of a loop neither
+// hides the loop nor reads as a negative number.
+//
+// A gap longer than the window between two answers leaves nothing to count:
+// the watch knows how far each counter moved and not when, so it starts
+// again from the present rather than date old restarts to this tick. A clock
+// that has gone backwards is the same: what was saved is dated in a future
+// the watch can no longer measure against.
+func (w *restartWatch) tick(now time.Time, units map[string]unitRestartState) map[string]metrics.UnitRestarts {
+ if units == nil {
+ return nil
+ }
+ // Wall time only. A time from time.Now carries a monotonic reading that
+ // a saved-and-loaded one does not, and comparing the two kinds measures a
+ // clock step differently depending on which side of a restart each time
+ // came from. Every time this watch holds is one it could have loaded.
+ now = now.Round(0)
+ if w.Units == nil || now.Before(w.At) || (!w.At.IsZero() && now.Sub(w.At) > restartWindow) {
+ w.Units = map[string]*unitRestartHistory{}
+ }
+ w.V = restartWatchVersion
+ for name := range w.Units {
+ if _, ok := units[name]; !ok {
+ delete(w.Units, name) // unloaded: nothing left to watch
+ }
+ }
+ out := make(map[string]metrics.UnitRestarts, len(units))
+ for name, u := range units {
+ h := w.Units[name]
+ if h == nil {
+ h = &unitRestartHistory{Last: u.restarts, QuietSince: now}
+ w.Units[name] = h
+ }
+ rose := u.restarts - h.Last
+ if u.restarts < h.Last {
+ rose = u.restarts // reset by a manual start; these came after it
+ h.QuietSince = now
+ }
+ if rose > 0 {
+ h.Bumps = append(h.Bumps, restartBump{At: now, N: rose})
+ h.QuietSince = now
+ }
+ h.Last = u.restarts
+
+ var count int64
+ kept := h.Bumps[:0]
+ for _, b := range h.Bumps {
+ if now.Sub(b.At) < restartWindow {
+ kept = append(kept, b)
+ count += b.N
+ }
+ }
+ h.Bumps = kept
+ out[name] = metrics.UnitRestarts{
+ Count: float64(count),
+ Settled: now.Sub(h.QuietSince) >= restartWindow,
+ Down: u.down,
+ }
+ }
+ w.At = now
+ return out
+}
+
+// restartWatchPath is where the watch is kept between agent runs, beside the
+// alert state it feeds.
+func restartWatchPath() string { return filepath.Join(dataDir(), "monitor", "restarts.json") }
+
+// restartWatchFile is the saved watch an agent loads and saves, or none.
+//
+// The data directory belongs to the carlos user, so anything able to act as
+// the agent can put a symlink where the file or its temp file goes. An agent
+// running as carlos follows it with no more than its own rights. A root-run
+// agent would read or truncate whatever it points at. So a root-run agent
+// keeps its watch in memory and never touches the file: the decision is
+// made before the path is even worked out (census ruling ls284, #280), as
+// engineBeatArmed does for the beat. The cost is that such an agent does
+// not count its own restarts across a restart of itself.
+type restartWatchFile struct{ path string }
+
+// newRestartWatchFile is the file for an agent running as euid. path is
+// called only for a non-root agent.
+func newRestartWatchFile(euid int, path func() string) restartWatchFile {
+ if euid == 0 {
+ return restartWatchFile{}
+ }
+ return restartWatchFile{path: path()}
+}
+
+// load is the saved watch, or an empty one with no file.
+func (f restartWatchFile) load() restartWatch {
+ if f.path == "" {
+ return restartWatch{}
+ }
+ return loadRestartWatch(f.path)
+}
+
+// save saves w, or does nothing with no file.
+func (f restartWatchFile) save(w restartWatch) error {
+ if f.path == "" {
+ return nil
+ }
+ return saveRestartWatch(f.path, w)
+}
+
+// loadRestartWatch reads a saved watch. Anything unreadable, of another
+// version, or not exactly the shape tick leaves behind is an empty watch,
+// which is always a safe place to start from: it can delay an alert by a few
+// ticks and can never invent one. The file sits in the data directory, so it
+// is checked as input, not trusted as this program's own output: a unit
+// history with no baseline would read a healthy unit's lifetime counter as
+// that many restarts just now.
+func loadRestartWatch(path string) restartWatch {
+ var w restartWatch
+ b, err := os.ReadFile(path)
+ if err != nil || json.Unmarshal(b, &w) != nil || !w.wellFormed() {
+ return restartWatch{}
+ }
+ // A missing or null "last" decodes as 0, which is a real counter value,
+ // so presence is checked on its own.
+ var present struct {
+ Units map[string]struct {
+ Last *int64 `json:"last"`
+ } `json:"units"`
+ }
+ if json.Unmarshal(b, &present) != nil {
+ return restartWatch{}
+ }
+ for name := range w.Units {
+ if present.Units[name].Last == nil {
+ return restartWatch{}
+ }
+ }
+ return w
+}
+
+func (w restartWatch) wellFormed() bool {
+ if w.V != restartWatchVersion || w.At.IsZero() {
+ return false
+ }
+ for _, h := range w.Units {
+ if h == nil || h.Last < 0 || h.QuietSince.IsZero() || h.QuietSince.After(w.At) {
+ return false
+ }
+ for _, b := range h.Bumps {
+ if b.N <= 0 || b.At.IsZero() || b.At.After(w.At) {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// saveRestartWatch writes the watch by temp file and rename, like
+// persistAlertState. Best effort: a failed save costs history across the
+// next agent restart, nothing more.
+func saveRestartWatch(path string, w restartWatch) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ b, err := json.Marshal(w)
+ if err != nil {
+ return err
+ }
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, b, 0o644); err != nil {
+ return err
+ }
+ return os.Rename(tmp, path)
+}
+
+// platformUnitRestarts asks systemd for the restart counter and state of
+// every loaded platform service. nil when systemd cannot be asked in time.
+//
+// Template instances (carlos-app@<host>, carlos-instance@<id>) are left out:
+// those are tenants' processes, and a tenant's crash loop is not the fleet
+// operator's page.
+func platformUnitRestarts() map[string]unitRestartState {
+ ctx, cancel := context.WithTimeout(context.Background(), restartProbeTimeout)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "systemctl", "show",
+ "--property=Id", "--property=NRestarts", "--property=ActiveState", "carlos-*.service").Output()
+ if err != nil {
+ return nil
+ }
+ return parseUnitRestarts(string(out))
+}
+
+// parseUnitRestarts reads `systemctl show --property=Id --property=NRestarts
+// --property=ActiveState` output: one blank-line-separated block per unit,
+// the properties in whatever order systemd prints them. A block with no Id
+// or no counter is skipped. Never nil: no loaded units is an answer, an
+// empty one.
+func parseUnitRestarts(out string) map[string]unitRestartState {
+ units := map[string]unitRestartState{}
+ for _, block := range strings.Split(out, "\n\n") {
+ var (
+ id string
+ u unitRestartState
+ haveN bool
+ )
+ for _, line := range strings.Split(block, "\n") {
+ k, v, ok := strings.Cut(strings.TrimSpace(line), "=")
+ if !ok {
+ continue
+ }
+ switch k {
+ case "Id":
+ id = v
+ case "NRestarts":
+ if n, err := strconv.ParseInt(v, 10, 64); err == nil {
+ u.restarts, haveN = n, true
+ }
+ case "ActiveState":
+ // "inactive" is a oneshot between runs or a unit an operator
+ // stopped: not running, and not in trouble either.
+ u.down = v == "failed" || v == "activating" || v == "deactivating"
+ }
+ }
+ if id == "" || !haveN || strings.Contains(id, "@") {
+ continue
+ }
+ units[id] = u
+ }
+ return units
+}
diff --git a/internal/host/restartwatch_test.go b/internal/host/restartwatch_test.go
new file mode 100644
index 000000000..26d30fa4e
--- /dev/null
+++ b/internal/host/restartwatch_test.go
@@ -0,0 +1,321 @@
+package host
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+)
+
+const lsUnit = "carlos-litestream.service"
+
+func restartsAt(t0 time.Time, m int) time.Time { return t0.Add(time.Duration(m) * time.Minute) }
+
+func oneUnit(n int64) map[string]unitRestartState {
+ return map[string]unitRestartState{lsUnit: {restarts: n}}
+}
+
+// The #284 shape: one unit restarting every few seconds among quiet ones.
+// Each unit gets its own count, and a count of zero is only "settled" after a
+// whole window with no restart.
+func TestRestartWatchCountsEachUnitInsideTheWindow(t *testing.T) {
+ var w restartWatch
+ t0 := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ units := func(ls, relay int64) map[string]unitRestartState {
+ return map[string]unitRestartState{lsUnit: {restarts: ls}, "carlos-relay.service": {restarts: relay}, "carlos-edge.service": {}}
+ }
+
+ // First sight of a counter is a baseline, not a restart: a unit that has
+ // restarted 900 times before the agent looked has not restarted "now".
+ got := w.tick(t0, units(900, 2))
+ if got[lsUnit].Count != 0 || got[lsUnit].Settled {
+ t.Fatalf("first tick: %+v, want no restarts and not settled", got[lsUnit])
+ }
+ got = w.tick(restartsAt(t0, 1), units(909, 2))
+ if got[lsUnit].Count != 9 || got["carlos-relay.service"].Count != 0 {
+ t.Fatalf("after one minute: %+v", got)
+ }
+ got = w.tick(restartsAt(t0, 2), units(912, 3))
+ if got[lsUnit].Count != 12 || got["carlos-relay.service"].Count != 1 {
+ t.Fatalf("after two minutes: %+v", got)
+ }
+
+ // The loop stops. Restarts age out of the window by the tick that saw
+ // them, and the unit settles only when the whole window has been quiet.
+ for m := 3; m <= 10; m++ {
+ got = w.tick(restartsAt(t0, m), units(912, 3))
+ if got[lsUnit].Count == 0 || got[lsUnit].Settled {
+ t.Fatalf("minute %d: %+v, but minute 1's restarts are still inside the window", m, got[lsUnit])
+ }
+ }
+ if got = w.tick(restartsAt(t0, 11), units(912, 3)); got[lsUnit].Count != 3 || got[lsUnit].Settled {
+ t.Fatalf("minute 11: %+v, want only minute 2's three restarts left", got[lsUnit])
+ }
+ if got = w.tick(restartsAt(t0, 12), units(912, 3)); got[lsUnit].Count != 0 || !got[lsUnit].Settled {
+ t.Fatalf("minute 12: %+v, want settled at zero", got[lsUnit])
+ }
+}
+
+// systemd zeroes NRestarts when a unit is started by hand. Restarts already
+// seen stay counted and the ones after the reset are added: an operator's
+// restart in the middle of a loop must not hide the loop (100, 103, then 2 is
+// five restarts, not two and not minus 101).
+func TestRestartWatchCountsThroughACounterReset(t *testing.T) {
+ var w restartWatch
+ t0 := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ w.tick(t0, oneUnit(100))
+ if got := w.tick(restartsAt(t0, 1), oneUnit(103)); got[lsUnit].Count != 3 {
+ t.Fatalf("before the reset: %+v, want 3", got[lsUnit])
+ }
+ got := w.tick(restartsAt(t0, 2), oneUnit(2))
+ if got[lsUnit].Count != 5 || got[lsUnit].Settled {
+ t.Fatalf("after the reset: %+v, want 5 and not settled", got[lsUnit])
+ }
+ // A reset to zero with nothing after it adds nothing, and still is not
+ // proof of quiet.
+ got = w.tick(restartsAt(t0, 3), oneUnit(0))
+ if got[lsUnit].Count != 5 || got[lsUnit].Settled {
+ t.Fatalf("a second manual start: %+v, want 5 and not settled", got[lsUnit])
+ }
+}
+
+// When systemd cannot be asked there is no reading, and a short gap keeps
+// what the watch knew. A gap longer than the window does not: the counter
+// moved, but nothing says it moved recently.
+func TestRestartWatchAcrossGapsInSampling(t *testing.T) {
+ var w restartWatch
+ t0 := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ w.tick(t0, oneUnit(1))
+ if got := w.tick(restartsAt(t0, 1), nil); got != nil {
+ t.Fatalf("reading %+v with no answer from systemd", got)
+ }
+ if got := w.tick(restartsAt(t0, 2), oneUnit(7)); got[lsUnit].Count != 6 {
+ t.Fatalf("after a two-minute gap: %+v, want 6 against the baseline from before it", got[lsUnit])
+ }
+
+ // Four more restarts, then no answer for eighteen minutes.
+ got := w.tick(restartsAt(t0, 20), oneUnit(11))
+ if got[lsUnit].Count != 0 || got[lsUnit].Settled {
+ t.Fatalf("after an eighteen-minute gap: %+v, want no dated restarts and not settled", got[lsUnit])
+ }
+ if got = w.tick(restartsAt(t0, 21), oneUnit(12)); got[lsUnit].Count != 1 {
+ t.Fatalf("the watch did not start again from the present: %+v", got[lsUnit])
+ }
+}
+
+// A unit that goes away is forgotten, and one that comes back is met afresh.
+func TestRestartWatchForgetsAnUnloadedUnit(t *testing.T) {
+ var w restartWatch
+ t0 := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ w.tick(t0, oneUnit(5))
+ if got := w.tick(restartsAt(t0, 1), map[string]unitRestartState{}); len(got) != 0 {
+ t.Fatalf("an unloaded unit still has a reading: %+v", got)
+ }
+ if got := w.tick(restartsAt(t0, 2), oneUnit(50)); got[lsUnit].Count != 0 {
+ t.Fatalf("a reloaded unit was counted against its old baseline: %+v", got[lsUnit])
+ }
+}
+
+// The watch survives the agent: the agent's own unit is one of those it
+// watches, so its restarts are only countable from what the last run saved.
+func TestRestartWatchSavedAcrossAnAgentRestart(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "monitor", "restarts.json")
+ t0 := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ edge := func(n int64) map[string]unitRestartState {
+ return map[string]unitRestartState{"carlos-edge.service": {restarts: n}}
+ }
+
+ // An agent that lives about ninety seconds: each run loads, samples at
+ // start, and saves.
+ var last map[string]metrics.UnitRestarts
+ for run := 0; run < 5; run++ {
+ w := loadRestartWatch(path)
+ last = w.tick(t0.Add(time.Duration(run)*90*time.Second), edge(int64(run)))
+ if err := saveRestartWatch(path, w); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if got := last["carlos-edge.service"].Count; got != 4 {
+ t.Fatalf("after five runs: %v restarts counted, want 4", got)
+ }
+
+ // A saved watch older than the window is not history any more.
+ w := loadRestartWatch(path)
+ if got := w.tick(t0.Add(2*time.Hour), edge(40)); got["carlos-edge.service"].Count != 0 {
+ t.Fatalf("a two-hour-old watch dated its restarts to now: %+v", got)
+ }
+
+ // An unreadable file is an empty watch.
+ if w := loadRestartWatch(filepath.Join(t.TempDir(), "absent.json")); w.Units != nil || !w.At.IsZero() {
+ t.Fatalf("absent file loaded as %+v", w)
+ }
+}
+
+// The saved watch is a file in the data directory, so it is read as input. A
+// history that decodes but is not what tick writes must not become a
+// baseline: a unit with no recorded counter would turn a healthy unit's
+// lifetime 900 into 900 restarts at startup.
+func TestRestartWatchDiscardsASavedWatchItDidNotWrite(t *testing.T) {
+ t0 := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ at := t0.Format(time.RFC3339)
+ for name, body := range map[string]string{
+ "not json": `{`,
+ "no version": `{"at":"` + at + `","units":{"carlos-litestream.service":{"last":5,"quiet_since":"` + at + `"}}}`,
+ "another version": `{"v":2,"at":"` + at + `","units":{}}`,
+ "no time": `{"v":1,"units":{"carlos-litestream.service":{"last":5,"quiet_since":"` + at + `"}}}`,
+ "empty unit history": `{"v":1,"at":"` + at + `","units":{"carlos-litestream.service":{}}}`,
+ "no counter": `{"v":1,"at":"` + at + `","units":{"carlos-litestream.service":{"quiet_since":"` + at + `"}}}`,
+ "null counter": `{"v":1,"at":"` + at + `","units":{"carlos-litestream.service":{"last":null,"quiet_since":"` + at + `"}}}`,
+ "null unit history": `{"v":1,"at":"` + at + `","units":{"carlos-litestream.service":null}}`,
+ "negative counter": `{"v":1,"at":"` + at + `","units":{"carlos-litestream.service":{"last":-3,"quiet_since":"` + at + `"}}}`,
+ "negative rise": `{"v":1,"at":"` + at + `","units":{"carlos-litestream.service":{"last":5,"quiet_since":"` + at + `","bumps":[{"at":"` + at + `","n":-900}]}}}`,
+ "rise from the future": `{"v":1,"at":"` + at + `","units":{"carlos-litestream.service":{"last":5,"quiet_since":"` + at + `","bumps":[{"at":"2030-01-01T00:00:00Z","n":4}]}}}`,
+ } {
+ path := filepath.Join(t.TempDir(), "restarts.json")
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ w := loadRestartWatch(path)
+ if w.Units != nil || !w.At.IsZero() {
+ t.Errorf("%s: loaded as %+v, want an empty watch", name, w)
+ continue
+ }
+ if got := w.tick(t0.Add(time.Minute), oneUnit(900)); got[lsUnit].Count != 0 || got[lsUnit].Settled {
+ t.Errorf("%s: a healthy unit at 900 read as %+v, want a fresh baseline", name, got[lsUnit])
+ }
+ }
+}
+
+// A clock stepped backwards leaves the saved rises dated in the future. They
+// are dropped with the rest of the history, not kept "inside the window"
+// until the clock catches up with them.
+func TestRestartWatchRebaselinesWhenTheClockGoesBackwards(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "restarts.json")
+ noon := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ var w restartWatch
+ w.tick(noon, oneUnit(10))
+ if got := w.tick(noon.Add(time.Minute), oneUnit(14)); got[lsUnit].Count != 4 {
+ t.Fatalf("before the step: %+v, want 4", got[lsUnit])
+ }
+ if err := saveRestartWatch(path, w); err != nil {
+ t.Fatal(err)
+ }
+ // The clock is corrected back an hour and the agent restarts.
+ w = loadRestartWatch(path)
+ got := w.tick(noon.Add(-time.Hour), oneUnit(14))
+ if got[lsUnit].Count != 0 || got[lsUnit].Settled {
+ t.Fatalf("after the step: %+v, want no dated restarts and not settled", got[lsUnit])
+ }
+ if got = w.tick(noon.Add(-time.Hour).Add(restartWindow), oneUnit(14)); got[lsUnit].Count != 0 || !got[lsUnit].Settled {
+ t.Fatalf("a window later: %+v, want settled at zero", got[lsUnit])
+ }
+}
+
+func TestParseUnitRestarts(t *testing.T) {
+ // The shape systemd 257 prints: properties in its own order, a blank line
+ // between units.
+ out := "NRestarts=0\nId=carlos-edge.service\nActiveState=active\n\n" +
+ "NRestarts=912\nId=carlos-litestream.service\nActiveState=activating\n\n" +
+ "NRestarts=5\nId=carlos-relay.service\nActiveState=failed\n\n" +
+ "NRestarts=0\nId=carlos-stage.service\nActiveState=inactive\n\n" +
+ "NRestarts=3\nId=carlos-app@shop.example.com.service\nActiveState=active\n\n" +
+ "Id=carlos-adopt.service\nActiveState=inactive\n\n" +
+ "NRestarts=x\nId=carlos-restart.service\n"
+ got := parseUnitRestarts(out)
+ want := map[string]unitRestartState{
+ "carlos-edge.service": {},
+ "carlos-litestream.service": {restarts: 912, down: true},
+ "carlos-relay.service": {restarts: 5, down: true},
+ "carlos-stage.service": {},
+ }
+ if len(got) != len(want) {
+ t.Fatalf("got %v, want %v (a tenant's unit, a block with no counter and one with a bad counter are all skipped)", got, want)
+ }
+ for k, v := range want {
+ if got[k] != v {
+ t.Errorf("%s = %+v, want %+v", k, got[k], v)
+ }
+ }
+ if got := parseUnitRestarts(""); got == nil || len(got) != 0 {
+ t.Fatalf("no loaded units = %v, want an empty map, not nil", got)
+ }
+}
+
+// The loop hands tick times from time.Now, which carry a monotonic reading;
+// what it loads back does not. The watch keeps wall time only, so a watch it
+// wrote is one it will accept, and a clock step is measured the same way on
+// both sides of an agent restart.
+func TestRestartWatchKeepsWallTimeOnly(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "restarts.json")
+ var w restartWatch
+ start := time.Now()
+ w.tick(start, oneUnit(3))
+ w.tick(start.Add(time.Minute), oneUnit(7))
+ if err := saveRestartWatch(path, w); err != nil {
+ t.Fatal(err)
+ }
+ loaded := loadRestartWatch(path)
+ if loaded.Units == nil {
+ t.Fatal("a watch ticked with time.Now was discarded on load")
+ }
+ if got := loaded.tick(start.Add(2*time.Minute), oneUnit(7)); got[lsUnit].Count != 4 {
+ t.Fatalf("after load: %+v, want the 4 restarts it saved", got[lsUnit])
+ }
+ for _, h := range w.Units {
+ if h.QuietSince != h.QuietSince.Round(0) || w.At != w.At.Round(0) {
+ t.Fatalf("the watch kept a monotonic reading: at=%v quiet_since=%v", w.At, h.QuietSince)
+ }
+ }
+
+ // A backward step with nothing loaded: still a rebaseline.
+ var live restartWatch
+ live.tick(start, oneUnit(10))
+ live.tick(start.Add(time.Minute), oneUnit(14))
+ if got := live.tick(start.Add(-time.Hour), oneUnit(14)); got[lsUnit].Count != 0 || got[lsUnit].Settled {
+ t.Fatalf("a live backward step kept %+v", got[lsUnit])
+ }
+}
+
+// A root-run agent never works out the watch's path, so it cannot follow a
+// symlink planted there: load is empty and save writes nothing (census
+// ruling ls284, #280). Any other agent loads and saves the file.
+func TestRestartWatchFileRootNeverTouchesThePath(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "root-owned")
+ if err := os.WriteFile(target, []byte("keep"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ planted := filepath.Join(dir, "restarts.json")
+ for _, p := range []string{planted, planted + ".tmp"} {
+ if err := os.Symlink(target, p); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ root := newRestartWatchFile(0, func() string {
+ t.Fatal("a root-run agent asked for the watch's path")
+ return planted
+ })
+ w := root.load()
+ if w.Units != nil || !w.At.IsZero() {
+ t.Fatalf("root load = %+v, want an empty watch", w)
+ }
+ w.tick(time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC), oneUnit(5))
+ if err := root.save(w); err != nil {
+ t.Fatal(err)
+ }
+ if b, err := os.ReadFile(target); err != nil || string(b) != "keep" {
+ t.Fatalf("the symlink's target changed: %q, %v", b, err)
+ }
+
+ own := filepath.Join(t.TempDir(), "monitor", "restarts.json")
+ agent := newRestartWatchFile(1000, func() string { return own })
+ if err := agent.save(w); err != nil {
+ t.Fatal(err)
+ }
+ if got := agent.load(); got.Units[lsUnit] == nil {
+ t.Fatalf("a non-root agent did not round-trip the watch: %+v", got)
+ }
+}
diff --git a/internal/host/units/carlos-litestream.service b/internal/host/units/carlos-litestream.service
index edb17ddf5..89472b450 100644
--- a/internal/host/units/carlos-litestream.service
+++ b/internal/host/units/carlos-litestream.service
@@ -27,10 +27,24 @@ PrivateTmp=yes
PrivateDevices=yes
RestrictAddressFamilies=AF_INET AF_INET6
MemoryDenyWriteExecute=yes
-MemoryMax=256M
+# The default for a box whose config is not generated. `carlos ops litestream`
+# sizes both lines from the number of databases it writes and states them in a
+# drop-in (carlos-litestream.service.d/50-memory.conf), because litestream's
+# memory grows with that number: 256M held ten databases and killed the unit
+# on every start at a hundred (discussion #284). GOMEMLIMIT is three quarters
+# of the cap; Go does not read the cgroup's limit by itself.
+MemoryMax=512M
+Environment=GOMEMLIMIT=384MiB
CPUWeight=50
+# Restart always, but back off: 2s, rising over five restarts to a minute. A
+# replicator that cannot stay up restarted every 2s for hours in #284, and its
+# two startup lines per database pushed everything else out of the journal,
+# the start of the incident included. A minute is the ceiling because every
+# second this unit is down is a second of writes with no copy off the box.
Restart=always
RestartSec=2
+RestartSteps=5
+RestartMaxDelaySec=60
[Install]
WantedBy=multi-user.target
diff --git a/internal/metrics/alert.go b/internal/metrics/alert.go
index 2d4cabab0..6bef2d875 100644
--- a/internal/metrics/alert.go
+++ b/internal/metrics/alert.go
@@ -2,7 +2,9 @@ package metrics
import (
"math"
+ "sort"
"strconv"
+ "strings"
"time"
)
@@ -27,6 +29,10 @@ type Rules struct {
// DiskETAHold is how long the projection must stay under DiskETAHours
// before the rule fires.
DiskETAHold time.Duration // default 2 * time.Hour
+ // RestartCount is how many restarts one unit may make inside the
+ // reporter's window before that unit's restarts rule fires. It is a
+ // count, not a fraction; see UnitRestarts for what clears it.
+ RestartCount float64 // fire >, default 3
}
// DefaultRules are the thresholds shipped with the platform.
@@ -44,6 +50,7 @@ func DefaultRules() Rules {
// Disk forecast: fleet alerts spec §7.2.
DiskETAHours: 72,
DiskETAHold: 2 * time.Hour,
+ RestartCount: 3,
}
}
@@ -113,6 +120,41 @@ type Observation struct {
// agent has already applied the 10 minute grace and staleness, so the
// rule has no sustain here.
EngineSilent *bool
+ // Restarts is every watched unit's reading, keyed by unit name. nil is
+ // "the reporter could not ask this tick" and leaves every restarts rule
+ // as it was. A unit missing from a non-nil map is no longer loaded.
+ Restarts map[string]UnitRestarts
+}
+
+// UnitRestarts is one unit's restart reading.
+type UnitRestarts struct {
+ // Count is how many times the unit restarted inside the reporter's
+ // window.
+ Count float64
+ // Settled says the reporter has watched this unit for a whole window in
+ // which it neither restarted nor was restarted by hand. Only then is a
+ // Count of 0 evidence that a loop is over.
+ Settled bool
+ // Down says systemd reports the unit failed, or between restarts. A unit
+ // that stopped restarting because it gave up has not recovered. A unit
+ // that is merely not running (a oneshot between runs, one an operator
+ // stopped) is not down.
+ Down bool
+}
+
+// restartsRule is the per-unit rule name: one unit's loop must not hide
+// another's, so each watched unit fires and clears by itself.
+const restartsRule = "restarts"
+
+// RuleFor is the rule name for one subject of a per-subject rule, e.g.
+// RuleFor("restarts", "carlos-relay.service").
+func RuleFor(name, subject string) string { return name + "@" + subject }
+
+// SplitRule undoes RuleFor: the rule's kind and what it is about. A rule
+// with no subject ("disk") comes back with an empty one.
+func SplitRule(rule string) (name, subject string) {
+ name, subject, _ = strings.Cut(rule, "@")
+ return name, subject
}
// RuleState is one rule's sustain/hysteresis bookkeeping. Since and FiredAt
@@ -139,7 +181,7 @@ type AlertState struct {
V int `json:"v"` // 1
Box string `json:"box"`
UpdatedAt time.Time `json:"updated_at"`
- Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta","engine_silent"
+ Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta","engine_silent", and "restarts@<unit>" per unit
}
// Event is emitted on a firing or clearing transition — never on every
@@ -376,5 +418,44 @@ func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event) {
emit("engine_silent", *obs.EngineSilent, out.Rules["engine_silent"].Value)
}
+ // restarts, one rule per unit: a count inside a window the reporter
+ // keeps, so there is no sustain here. A unit fires above RestartCount. It
+ // clears when the reporter has seen it quiet for a whole window and it is
+ // not down, or when it is no longer loaded: a unit that has merely slowed
+ // down (systemd backs its restarts off), or stopped because it gave up,
+ // has not recovered.
+ if obs.Restarts != nil {
+ // A cleared rule stays in the map as a quiet RuleState rather than
+ // being deleted: the console learns of a clear by reading firing
+ // false, and a key that vanished would leave it believing the alert
+ // is still up. The set of platform units is small and fixed.
+ var changed []Event
+ for unit, u := range obs.Restarts {
+ rule := RuleFor(restartsRule, unit)
+ cur := out.Rules[rule]
+ switch {
+ case !cur.Firing && u.Count > r.RestartCount:
+ out.Rules[rule] = RuleState{Firing: true, Since: obs.At, FiredAt: obs.At, Value: u.Count}
+ changed = append(changed, Event{Rule: rule, Firing: true, Value: u.Count, Box: st.Box})
+ case cur.Firing && u.Count == 0 && u.Settled && !u.Down:
+ out.Rules[rule] = RuleState{}
+ changed = append(changed, Event{Rule: rule, Firing: false, Box: st.Box})
+ }
+ }
+ for rule, cur := range out.Rules {
+ name, unit := SplitRule(rule)
+ if name != restartsRule || unit == "" || !cur.Firing {
+ continue
+ }
+ if _, loaded := obs.Restarts[unit]; !loaded {
+ out.Rules[rule] = RuleState{}
+ changed = append(changed, Event{Rule: rule, Firing: false, Box: st.Box})
+ }
+ }
+ // Map order is random; the events of one tick are not.
+ sort.Slice(changed, func(i, j int) bool { return changed[i].Rule < changed[j].Rule })
+ events = append(events, changed...)
+ }
+
return out, events
}
diff --git a/internal/metrics/alert_test.go b/internal/metrics/alert_test.go
index 48d8b3a4c..9b8d17947 100644
--- a/internal/metrics/alert_test.go
+++ b/internal/metrics/alert_test.go
@@ -248,6 +248,113 @@ func TestGeoIPReasonChangeWhileFiring(t *testing.T) {
}
}
+// One unit's restarts rule fires above the count, holds while the unit is
+// still restarting (however slowly) or is not running, and clears only once
+// it has been quiet for a settled window and is not down. A nil reading
+// changes nothing.
+func TestRestartsRuleFiresAboveTheCountAndClearsOnlyWhenSettledAndUp(t *testing.T) {
+ r := DefaultRules()
+ t0 := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ const ls = "carlos-litestream.service"
+ rule := RuleFor("restarts", ls)
+ one := func(u UnitRestarts) map[string]UnitRestarts { return map[string]UnitRestarts{ls: u} }
+ st := AlertState{V: 1, Box: "b"}
+
+ st, ev := Evaluate(r, st, Observation{At: t0, Restarts: one(UnitRestarts{Count: 3})})
+ if len(ev) != 0 || st.Rules[rule].Firing {
+ t.Fatalf("fired at the count, not above it: %v", ev)
+ }
+ st, ev = Evaluate(r, st, Observation{At: t0.Add(time.Minute), Restarts: one(UnitRestarts{Count: 4})})
+ if len(ev) != 1 || !ev[0].Firing || ev[0].Rule != rule || ev[0].Value != 4 {
+ t.Fatalf("above the count: %+v", ev)
+ }
+ if rs := st.Rules[rule]; !rs.Firing || !rs.FiredAt.Equal(t0.Add(time.Minute)) {
+ t.Fatalf("state after firing: %+v", rs)
+ }
+ for i, u := range []UnitRestarts{
+ {Count: 1}, // still restarting, now once a minute
+ {Count: 0}, // quiet, but not yet for a whole window
+ {Count: 0, Settled: true, Down: true}, // quiet because it gave up
+ } {
+ st, ev = Evaluate(r, st, Observation{At: t0.Add(time.Duration(2+i) * time.Minute), Restarts: one(u)})
+ if len(ev) != 0 || !st.Rules[rule].Firing {
+ t.Fatalf("reading %+v cleared the alert: %v", u, ev)
+ }
+ }
+ st, ev = Evaluate(r, st, Observation{At: t0.Add(6 * time.Minute)})
+ if len(ev) != 0 || !st.Rules[rule].Firing {
+ t.Fatalf("a nil reading changed the rule: %v", ev)
+ }
+ st, ev = Evaluate(r, st, Observation{At: t0.Add(16 * time.Minute), Restarts: one(UnitRestarts{Count: 0, Settled: true})})
+ if len(ev) != 1 || ev[0].Firing || ev[0].Rule != rule {
+ t.Fatalf("settled, up and quiet must clear: %+v", ev)
+ }
+ // The key stays, quiet: that is how the console reads the clear.
+ if rs, kept := st.Rules[rule]; !kept || rs.Firing || !rs.FiredAt.IsZero() {
+ t.Fatalf("state after clearing: %+v (kept %v)", rs, kept)
+ }
+ if _, ev = Evaluate(r, st, Observation{At: t0.Add(17 * time.Minute), Restarts: one(UnitRestarts{Count: 0, Settled: true})}); len(ev) != 0 {
+ t.Fatalf("a quiet rule emitted: %v", ev)
+ }
+}
+
+// Each unit has its own rule: a second unit that starts looping while the
+// first alert is up is its own page, and the first recovering does not clear
+// the second.
+func TestRestartsRuleIsPerUnit(t *testing.T) {
+ r := DefaultRules()
+ t0 := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
+ relay, ls := RuleFor("restarts", "carlos-relay.service"), RuleFor("restarts", "carlos-litestream.service")
+ st := AlertState{V: 1, Box: "b"}
+
+ st, ev := Evaluate(r, st, Observation{At: t0, Restarts: map[string]UnitRestarts{
+ "carlos-relay.service": {Count: 5},
+ "carlos-litestream.service": {Count: 0, Settled: true},
+ }})
+ if len(ev) != 1 || ev[0].Rule != relay || !ev[0].Firing {
+ t.Fatalf("relay looping: %+v", ev)
+ }
+ st, ev = Evaluate(r, st, Observation{At: t0.Add(time.Minute), Restarts: map[string]UnitRestarts{
+ "carlos-relay.service": {Count: 6},
+ "carlos-litestream.service": {Count: 9},
+ }})
+ if len(ev) != 1 || ev[0].Rule != ls || !ev[0].Firing || ev[0].Value != 9 {
+ t.Fatalf("a second unit looping must fire its own rule: %+v", ev)
+ }
+ st, ev = Evaluate(r, st, Observation{At: t0.Add(20 * time.Minute), Restarts: map[string]UnitRestarts{
+ "carlos-relay.service": {Count: 0, Settled: true},
+ "carlos-litestream.service": {Count: 2},
+ }})
+ if len(ev) != 1 || ev[0].Rule != relay || ev[0].Firing {
+ t.Fatalf("relay recovering must clear only relay: %+v", ev)
+ }
+ if !st.Rules[ls].Firing {
+ t.Fatalf("litestream's alert went with relay's: %+v", st.Rules)
+ }
+ // The unit is unloaded (an operator removed it): nothing left to watch.
+ _, ev = Evaluate(r, st, Observation{At: t0.Add(21 * time.Minute), Restarts: map[string]UnitRestarts{
+ "carlos-relay.service": {Count: 0, Settled: true},
+ }})
+ if len(ev) != 1 || ev[0].Rule != ls || ev[0].Firing {
+ t.Fatalf("an unloaded unit's alert must clear: %+v", ev)
+ }
+}
+
+func TestSplitRule(t *testing.T) {
+ for rule, want := range map[string][2]string{
+ "disk": {"disk", ""},
+ "restarts@carlos-litestream.service": {"restarts", "carlos-litestream.service"},
+ "restarts@carlos-app@shop.service": {"restarts", "carlos-app@shop.service"},
+ } {
+ if n, s := SplitRule(rule); n != want[0] || s != want[1] {
+ t.Errorf("SplitRule(%q) = %q, %q; want %q, %q", rule, n, s, want[0], want[1])
+ }
+ }
+ if got := RuleFor("restarts", "carlos-relay.service"); got != "restarts@carlos-relay.service" {
+ t.Errorf("RuleFor = %q", got)
+ }
+}
+
// etaObs is one disk_eta tick: a verdict and, for TrendGrowing, an ETA.
func etaObs(at time.Time, v TrendVerdict, eta float64) Observation {
return Observation{At: at, DiskTrend: &v, DiskETAHours: eta}
diff --git a/internal/ops/flock_unix.go b/internal/ops/flock_unix.go
new file mode 100644
index 000000000..29c48345a
--- /dev/null
+++ b/internal/ops/flock_unix.go
@@ -0,0 +1,15 @@
+//go:build !windows
+
+package ops
+
+import (
+ "os"
+ "syscall"
+)
+
+// lockDir takes an exclusive advisory lock on an open directory, and
+// unlockDir drops it. syscall.Flock is on both linux and darwin, which
+// covers every platform that runs an ops verb.
+func lockDir(d *os.File) error { return syscall.Flock(int(d.Fd()), syscall.LOCK_EX) }
+
+func unlockDir(d *os.File) { syscall.Flock(int(d.Fd()), syscall.LOCK_UN) } //nolint:errcheck
diff --git a/internal/ops/flock_windows.go b/internal/ops/flock_windows.go
new file mode 100644
index 000000000..7889789b7
--- /dev/null
+++ b/internal/ops/flock_windows.go
@@ -0,0 +1,18 @@
+//go:build windows
+
+package ops
+
+import (
+ "errors"
+ "os"
+)
+
+// lockDir refuses on Windows rather than pretending to lock. The ops verbs
+// run on a Linux box; the Windows build exists only so the carlos CLI
+// compiles for workstation use. Refusing is the safe failure: the caller
+// writes nothing when the lock cannot be taken.
+func lockDir(d *os.File) error {
+ return errors.New("ops verbs lock box-side (linux) only")
+}
+
+func unlockDir(d *os.File) {}
diff --git a/internal/ops/litestream_memory.go b/internal/ops/litestream_memory.go
new file mode 100644
index 000000000..e60678c4c
--- /dev/null
+++ b/internal/ops/litestream_memory.go
@@ -0,0 +1,155 @@
+package ops
+
+// The replicator's memory cap follows the number of databases it replicates.
+//
+// carlos-litestream.service used to carry one fixed MemoryMax. `litestream
+// replicate` holds memory per database, so a cap that fits a box at ten
+// databases stops fitting it at a hundred, and the way it stops fitting is the
+// worst available: the kernel kills the process a few seconds into every
+// start, systemd restarts it, and the databases too large to ship in those few
+// seconds stop being replicated at all while the unit still looks busy
+// (discussion #284: 100 databases, a 256M cap, five databases up to two hours
+// behind before a person noticed).
+//
+// The generator is the one place that knows the count, so it states the cap,
+// in a systemd drop-in beside the unit. A box whose config is not generated by
+// this verb keeps the unit's own default.
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/carlosframework/platform/internal/safefile"
+)
+
+const (
+ // litestreamMemoryFloor is the unit file's own MemoryMax, and so the
+ // least this verb ever states: the drop-in only raises the cap.
+ litestreamMemoryFloor = 512 << 20
+ // litestreamMemoryBase and litestreamMemoryPerDB are fitted to the one
+ // measurement there is (#284): 100 databases held steady at 229-247 MB of
+ // anonymous memory and ran without a kill under a 1G cap, where 256M
+ // killed them every start. 256M + 8M a database puts 100 databases at
+ // 1056M. The headroom over the steady figure is deliberate: the peak
+ // during startup was never measured, only that 1G survives it.
+ litestreamMemoryBase = 256 << 20
+ litestreamMemoryPerDB = 8 << 20
+
+ // defaultMemoryDropIn is where the cap goes on a box. systemd reads
+ // drop-ins in name order, so an operator's own later-sorting file in the
+ // same directory still wins.
+ defaultMemoryDropIn = "/etc/systemd/system/carlos-litestream.service.d/50-memory.conf"
+)
+
+// LitestreamMemoryMax is the replicator's memory cap, in bytes, for a config
+// naming n databases.
+func LitestreamMemoryMax(n int) int64 {
+ if n < 0 {
+ n = 0
+ }
+ want := int64(litestreamMemoryBase) + int64(n)*litestreamMemoryPerDB
+ if want < litestreamMemoryFloor {
+ return litestreamMemoryFloor
+ }
+ return want
+}
+
+// litestreamGoMemLimit is the soft limit handed to litestream's Go runtime:
+// three quarters of the cap. The runtime does not read the cgroup's limit, so
+// without this it lets the heap double before collecting and is killed at a
+// cap the live data would have fitted under. The quarter left over is for
+// what the runtime does not count: the page cache charged to the unit and
+// SQLite's own allocations.
+func litestreamGoMemLimit(max int64) int64 { return max / 4 * 3 }
+
+// LitestreamMemoryDropIn renders the drop-in for a config naming n databases.
+// Same count, same bytes: the verb's changed/unchanged report depends on it.
+func LitestreamMemoryDropIn(n int) string {
+ max := LitestreamMemoryMax(n)
+ return "# GENERATED by `carlos ops litestream`. do not hand-edit. it is rewritten when\n" +
+ "# the number of replicated databases changes. To override it, add a drop-in\n" +
+ "# that sorts after this one.\n" +
+ "[Service]\n" +
+ fmt.Sprintf("MemoryMax=%dM\n", max>>20) +
+ fmt.Sprintf("Environment=GOMEMLIMIT=%dMiB\n", litestreamGoMemLimit(max)>>20)
+}
+
+// writeMemoryDropIn makes the drop-in at path state the cap for n databases
+// and has systemd re-read its units through reload. It reports whether the
+// cap systemd holds changed.
+//
+// The file is replaced whole (safefile: staged beside it, synced, renamed),
+// because systemd may re-read the directory at any moment, on a self-update's
+// reload for one, and a half-written drop-in falls back to the unit's smaller
+// default under a replicator that is already using more.
+//
+// A reload is owed from the moment the file is about to change until systemd
+// has taken it, and that debt is a marker file beside the drop-in, not a
+// comparison of bytes: once the new file is on disk a later run finds nothing
+// to rewrite, and would never reload a cap an earlier run failed to load.
+// The marker is written first and removed last, so every way of stopping in
+// between leaves it for the next run. systemd ignores it (no .conf suffix).
+//
+// The whole of it runs under a lock on the drop-in's directory. The verb is
+// run by hand and may be run by a timer, and two runs interleaved could have
+// one remove the marker the other had just left for a reload that failed.
+//
+// The number of databases is asked for inside the lock, through count, and
+// the verb answers from the config on disk at that moment, not from the set
+// it computed before it queued. Of two overlapping runs the one that takes
+// the lock last then sizes the cap for the config that is actually there,
+// whichever of them wrote it; a run that sized from its own earlier count
+// could leave a config naming 200 databases under a cap fitted to 32.
+func writeMemoryDropIn(path string, count func() (int, error), reload func() error) (n int, changed bool, err error) {
+ pending := path + ".reload-pending"
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return 0, false, err
+ }
+ dir, err := os.Open(filepath.Dir(path))
+ if err != nil {
+ return 0, false, err
+ }
+ defer dir.Close()
+ if err := lockDir(dir); err != nil {
+ return 0, false, err
+ }
+ defer unlockDir(dir)
+
+ if n, err = count(); err != nil {
+ return 0, false, err
+ }
+ want := LitestreamMemoryDropIn(n)
+ prior, readErr := os.ReadFile(path)
+ if readErr != nil && !os.IsNotExist(readErr) {
+ return n, false, readErr
+ }
+ current := readErr == nil && string(prior) == want
+ if _, err := os.Lstat(pending); current && os.IsNotExist(err) {
+ return n, false, nil
+ }
+ if err := safefile.WriteFile(pending, nil, 0o644); err != nil {
+ return n, false, err
+ }
+ if !current {
+ if err := safefile.WriteFile(path, []byte(want), 0o644); err != nil {
+ return n, false, err
+ }
+ }
+ if err := reload(); err != nil {
+ return n, false, fmt.Errorf("systemd did not reload: %w", err)
+ }
+ // systemd has the cap. A marker that will not go only costs the next run
+ // one reload it did not need.
+ _ = os.Remove(pending)
+ return n, true, nil
+}
+
+// configDBCount counts the databases a generated config on disk names.
+func configDBCount(cfgPath string) (int, error) {
+ b, err := os.ReadFile(cfgPath)
+ if err != nil {
+ return 0, err
+ }
+ return len(ParseLitestreamDBs(string(b))), nil
+}
diff --git a/internal/ops/ops.go b/internal/ops/ops.go
index 4e09acbca..bfcb904c7 100644
--- a/internal/ops/ops.go
+++ b/internal/ops/ops.go
@@ -13,6 +13,7 @@ import (
"fmt"
"log"
"os"
+ "os/exec"
"strings"
"time"
@@ -99,6 +100,7 @@ func runLitestream(args []string) {
out := fs.String("out", defaultConfigPath, "config file to write")
lsBin := fs.String("litestream-bin", "litestream", "litestream binary to check the snapshot policy against (pinned release "+litestreamVersion+")")
allowShrink := fs.Bool("allow-shrink", false, "permit a config that replicates FEWER databases than the one it replaces")
+ memDropIn := fs.String("memory-dropin", "", "systemd drop-in that sets the replicator's memory cap from the database count (default "+defaultMemoryDropIn+" when --out is "+defaultConfigPath+"; \"none\" leaves the unit's cap alone)")
fs.Usage = cliflag.Usage(fs, "")
_ = fs.Parse(args)
@@ -153,6 +155,29 @@ should no longer be replicated.`,
}
fmt.Fprintf(os.Stderr, "litestream: %d databases -> s3://%s/%s/ (%s)\n", len(dbs), *bucket, *prefix, *out)
+ // The cap follows the config now on disk (see litestream_memory.go).
+ // A run writing somewhere other than the live config is a preview or a
+ // test, and leaves systemd alone unless told where to write.
+ dropIn := *memDropIn
+ if dropIn == "" && *out == defaultConfigPath {
+ dropIn = defaultMemoryDropIn
+ }
+ if dropIn != "" && dropIn != "none" {
+ n, capped, err := writeMemoryDropIn(dropIn, func() (int, error) { return configDBCount(*out) }, systemdDaemonReload)
+ if err != nil {
+ // Loud, not fatal: the config above is written and correct, and
+ // refusing the restart it needs would trade a cap that may be too
+ // small for a database set that is certainly stale. Nothing is
+ // left half-done: the next run finds the cap unwritten and tries
+ // again.
+ fmt.Fprintf(os.Stderr, "litestream: WARNING: could not apply the memory cap from %s: %v\n The replicator keeps its current cap. The next run will try again.\n", dropIn, err)
+ }
+ if capped {
+ fmt.Fprintf(os.Stderr, "litestream: memory cap %dM for %d databases (%s)\n", LitestreamMemoryMax(n)>>20, n, dropIn)
+ wrote = true
+ }
+ }
+
// The config now STATES a recovery window, so say plainly when the binary
// on this box will ignore it. Loud, not fatal: a box on an old litestream
// still wants its database SET kept current (that is what carries
@@ -175,6 +200,23 @@ should no longer be replicated.`,
}
}
+// daemonReloadTimeout bounds the reload. It runs while the drop-in's
+// directory is locked, so a systemd that never answers must fail this run
+// (the marker makes the next one try again), not hold every later run out.
+const daemonReloadTimeout = time.Minute
+
+// systemdDaemonReload has systemd re-read its unit files, which is what makes
+// a drop-in this verb just wrote the unit's definition at its next start.
+func systemdDaemonReload() error {
+ ctx, cancel := context.WithTimeout(context.Background(), daemonReloadTimeout)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "systemctl", "daemon-reload").CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("systemctl daemon-reload: %v: %s", err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
// runRestoreVerify — restore every database in the generated config from S3
// into a temp dir and prove each opens clean. Exits non-zero on any failure so
// the oneshot unit lands in 'failed' where the fleet sweeps see it.
diff --git a/internal/ops/ops_test.go b/internal/ops/ops_test.go
index c16d4c5aa..4f9b05d01 100644
--- a/internal/ops/ops_test.go
+++ b/internal/ops/ops_test.go
@@ -2,10 +2,13 @@ package ops
import (
"database/sql"
+ "errors"
"os"
"path/filepath"
"slices"
+ "strconv"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -870,3 +873,235 @@ func TestLayoutJournalPresentIsLstatNotAbsent(t *testing.T) {
t.Fatal("another host was reported held")
}
}
+
+// The cap follows the database count: never below the unit's own default, and
+// at the one measured point (#284: 100 databases ran clean under 1G where
+// 256M killed them on every start) at least as large as the cap that held.
+func TestLitestreamMemoryMaxFollowsTheDatabaseCount(t *testing.T) {
+ for _, n := range []int{-1, 0, 1, 10, 32} {
+ if got := LitestreamMemoryMax(n); got != litestreamMemoryFloor {
+ t.Errorf("LitestreamMemoryMax(%d) = %dM, want the %dM floor", n, got>>20, int64(litestreamMemoryFloor)>>20)
+ }
+ }
+ if got := LitestreamMemoryMax(100); got < 1<<30 {
+ t.Errorf("LitestreamMemoryMax(100) = %dM, below the 1G that held 100 databases", got>>20)
+ }
+ prev := LitestreamMemoryMax(0)
+ for n := 1; n <= 2000; n++ {
+ got := LitestreamMemoryMax(n)
+ if got < prev {
+ t.Fatalf("LitestreamMemoryMax(%d) = %d, less than at %d databases (%d)", n, got, n-1, prev)
+ }
+ prev = got
+ }
+}
+
+// The unit file's default and the generator's floor are one number written in
+// two places. If they part, the drop-in either lowers a box's cap or the
+// floor stops being what an ungenerated box runs under.
+func TestLitestreamUnitDefaultIsTheFloor(t *testing.T) {
+ unit, err := os.ReadFile(filepath.Join("..", "host", "units", "carlos-litestream.service"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ floor := int64(litestreamMemoryFloor)
+ for _, want := range []string{
+ "MemoryMax=" + strconv.FormatInt(floor>>20, 10) + "M\n",
+ "Environment=GOMEMLIMIT=" + strconv.FormatInt(litestreamGoMemLimit(floor)>>20, 10) + "MiB\n",
+ } {
+ if !strings.Contains(string(unit), "\n"+want) {
+ t.Errorf("carlos-litestream.service does not carry %q", strings.TrimSpace(want))
+ }
+ }
+ if got := LitestreamMemoryDropIn(0); !strings.Contains(got, "MemoryMax="+strconv.FormatInt(floor>>20, 10)+"M\n") {
+ t.Errorf("the drop-in for an empty config does not state the floor:\n%s", got)
+ }
+}
+
+// A drop-in is a restart-worthy change, so it is written, and systemd asked to
+// re-read its units, only when the count moved the cap.
+func TestWriteMemoryDropInReloadsOnlyOnChange(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "carlos-litestream.service.d", "50-memory.conf")
+ reloads := 0
+ reload := func() error { reloads++; return nil }
+
+ _, changed, err := writeMemoryDropIn(path, dbs(100), reload)
+ if err != nil || !changed || reloads != 1 {
+ t.Fatalf("first write: changed=%v err=%v reloads=%d, want true, nil, 1", changed, err, reloads)
+ }
+ body, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"[Service]\n", "MemoryMax=1056M\n", "Environment=GOMEMLIMIT=792MiB\n"} {
+ if !strings.Contains(string(body), want) {
+ t.Errorf("drop-in for 100 databases lacks %q:\n%s", strings.TrimSpace(want), body)
+ }
+ }
+ if fi, err := os.Stat(path); err != nil || fi.Mode().Perm() != 0o644 {
+ t.Errorf("drop-in mode = %v (%v), want 0644: systemd reads it as root, operators as anyone", fi.Mode().Perm(), err)
+ }
+ if ents, _ := os.ReadDir(filepath.Dir(path)); len(ents) != 1 {
+ t.Errorf("the drop-in directory holds %d entries, want only the drop-in (no staging or marker left behind)", len(ents))
+ }
+
+ // The same count changes no byte, so it reloads nothing.
+ if _, changed, err := writeMemoryDropIn(path, dbs(100), reload); err != nil || changed || reloads != 1 {
+ t.Fatalf("same count: changed=%v err=%v reloads=%d, want false, nil, 1", changed, err, reloads)
+ }
+
+ if _, changed, err := writeMemoryDropIn(path, dbs(101), reload); err != nil || !changed || reloads != 2 {
+ t.Fatalf("one more database: changed=%v err=%v reloads=%d, want true, nil, 2", changed, err, reloads)
+ }
+}
+
+// A reload that fails must not strand the new cap on disk unloaded: every
+// later run would find the file already right and never reload it. The debt
+// is a marker beside the drop-in, so the next run reloads whatever the bytes
+// say, and reports the change once systemd has it.
+func TestWriteMemoryDropInRetriesAfterAFailedReload(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "d", "50-memory.conf")
+ pending := path + ".reload-pending"
+ reloads := 0
+ broken := func() error { reloads++; return errors.New("no systemd here") }
+ working := func() error { reloads++; return nil }
+ want := "MemoryMax=" + strconv.FormatInt(LitestreamMemoryMax(200)>>20, 10) + "M\n"
+
+ if _, changed, err := writeMemoryDropIn(path, dbs(200), broken); changed || err == nil {
+ t.Fatalf("changed=%v err=%v, want false and the reload error", changed, err)
+ }
+ if body, _ := os.ReadFile(path); !strings.Contains(string(body), want) {
+ t.Fatalf("the new cap is not on disk after a failed reload:\n%s", body)
+ }
+ if _, err := os.Stat(pending); err != nil {
+ t.Fatalf("a failed reload left no marker: %v", err)
+ }
+ // The bytes are already right, and it still reloads, twice if it has to.
+ if _, changed, err := writeMemoryDropIn(path, dbs(200), broken); changed || err == nil || reloads != 2 {
+ t.Fatalf("second failure: changed=%v err=%v reloads=%d, want false, an error, 2", changed, err, reloads)
+ }
+ if _, changed, err := writeMemoryDropIn(path, dbs(200), working); !changed || err != nil || reloads != 3 {
+ t.Fatalf("retry: changed=%v err=%v reloads=%d, want true, nil, 3", changed, err, reloads)
+ }
+ if _, err := os.Stat(pending); !os.IsNotExist(err) {
+ t.Fatalf("the marker outlived a successful reload (stat err %v)", err)
+ }
+ if _, changed, err := writeMemoryDropIn(path, dbs(200), working); changed || err != nil || reloads != 3 {
+ t.Fatalf("settled: changed=%v err=%v reloads=%d, want false, nil, 3", changed, err, reloads)
+ }
+
+ // A marker with nothing else wrong (a run stopped after systemd reloaded
+ // but before the marker went) costs one more reload and no more.
+ if err := os.WriteFile(pending, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, changed, err := writeMemoryDropIn(path, dbs(200), working); !changed || err != nil || reloads != 4 {
+ t.Fatalf("stray marker: changed=%v err=%v reloads=%d, want true, nil, 4", changed, err, reloads)
+ }
+}
+
+// Two runs must not interleave. If a second run could start while the first
+// is between its reload and removing its marker, the first would go on to
+// remove the marker the second had just left for a reload that failed, and
+// the second's cap would sit on disk unloaded for good.
+func TestWriteMemoryDropInRunsOneAtATime(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "d", "50-memory.conf")
+ second := make(chan error, 1)
+ firstReload := func() error {
+ go func() {
+ _, _, err := writeMemoryDropIn(path, dbs(300), func() error { return errors.New("no systemd here") })
+ second <- err
+ }()
+ select {
+ case err := <-second:
+ t.Errorf("a second run finished (%v) while the first was still reloading", err)
+ case <-time.After(300 * time.Millisecond):
+ }
+ return nil
+ }
+ if _, changed, err := writeMemoryDropIn(path, dbs(100), firstReload); !changed || err != nil {
+ t.Fatalf("first run: changed=%v err=%v, want true, nil", changed, err)
+ }
+ select {
+ case err := <-second:
+ if err == nil {
+ t.Fatal("the second run's reload was meant to fail")
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("the second run never ran after the first finished")
+ }
+ // The second run's debt is still on record, and the next run pays it.
+ if _, err := os.Stat(path + ".reload-pending"); err != nil {
+ t.Fatalf("the second run's marker is gone: %v", err)
+ }
+ reloads := 0
+ if _, changed, err := writeMemoryDropIn(path, dbs(300), func() error { reloads++; return nil }); !changed || err != nil || reloads != 1 {
+ t.Fatalf("the run after: changed=%v err=%v reloads=%d, want true, nil, 1", changed, err, reloads)
+ }
+}
+
+// dbs is a config that names n databases, for writeMemoryDropIn's count.
+func dbs(n int) func() (int, error) { return func() (int, error) { return n, nil } }
+
+// The cap is sized from the config that is on disk when the run holds the
+// lock, not from what the run counted before it queued. Run A arrives while
+// run B holds the lock; the config changes before B lets go. A must not
+// count until then, and must size the cap for what the config says then.
+func TestWriteMemoryDropInSizesFromTheConfigUnderTheLock(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "d", "50-memory.conf")
+ cfg := filepath.Join(dir, "litestream.yml")
+ write := func(n int) {
+ paths := make([]string, n)
+ for i := range paths {
+ paths[i] = "/data/db" + strconv.Itoa(i) + ".db"
+ }
+ if err := os.WriteFile(cfg, []byte(LitestreamConfig(paths, "bucket", "prefix", "eu-west-1")), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ var aCounted atomic.Bool
+ aCount := func() (int, error) {
+ aCounted.Store(true)
+ return configDBCount(cfg)
+ }
+ aDone := make(chan int, 1)
+ bReload := func() error {
+ // B holds the lock. A arrives and has to wait.
+ go func() {
+ n, _, err := writeMemoryDropIn(path, aCount, func() error { return nil })
+ if err != nil {
+ t.Error(err)
+ }
+ aDone <- n
+ }()
+ time.Sleep(300 * time.Millisecond)
+ if aCounted.Load() {
+ t.Error("A counted the config while B still held the lock")
+ }
+ // The config moves on while A is still queued.
+ write(300)
+ return nil
+ }
+ write(200)
+ if n, changed, err := writeMemoryDropIn(path, func() (int, error) { return configDBCount(cfg) }, bReload); n != 200 || !changed || err != nil {
+ t.Fatalf("B: n=%d changed=%v err=%v, want 200, true, nil", n, changed, err)
+ }
+ select {
+ case n := <-aDone:
+ if n != 300 {
+ t.Fatalf("A sized the cap for %d databases, want the 300 the config named once A held the lock", n)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("A never ran")
+ }
+ body, _ := os.ReadFile(path)
+ if want := "MemoryMax=" + strconv.FormatInt(LitestreamMemoryMax(300)>>20, 10) + "M\n"; !strings.Contains(string(body), want) {
+ t.Fatalf("the cap left on disk is not the one for 300 databases:\n%s", body)
+ }
+
+ if _, _, err := writeMemoryDropIn(path, func() (int, error) { return 0, errors.New("config unreadable") }, func() error { return nil }); err == nil {
+ t.Fatal("a count that fails must fail the cap, not size it for zero databases")
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index cdf76193c..85257bca2 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -73,3 +73,4 @@ plan14-root-reads-domains-buy-nosub.tsv 09ad1d7267b9598c64e89ec0faa7b18839c785c5
plan14-root-reads-wake-storm-cap.tsv b0fc198c53bb0dacba33a54c3d8bf8fe5ac07d94b76a31b8a69e9411115ecd85
plan14-root-reads-domains-check-country.tsv b0fc198c53bb0dacba33a54c3d8bf8fe5ac07d94b76a31b8a69e9411115ecd85
plan14-root-reads-static-stream-extract.tsv 7fb932b118e67e23b33a374c6a4020b38976667c7ec4cfb855c0f8b598b1756b
+plan14-root-reads-ls284.tsv 744b16d970f22476b79982e57c326157ca5137fa96ccaee4a7ae10c25248d124
diff --git a/internal/provision/testdata/plan14-root-reads-ls284.tsv b/internal/provision/testdata/plan14-root-reads-ls284.tsv
new file mode 100644
index 000000000..49395870e
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-ls284.tsv
@@ -0,0 +1,22 @@
+# Census overlay ls284, written by census-propose (#369). census-ruling-ls284, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-ls284.md.
+# 2 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 5 new dispositions: 0 reads re-frozen at their disposition with the claim, 5 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 23b1c3b11f9234e50fee025635877b18f36023cdcdc7f3ab406c1d9cec7fa942 internal/host/units/carlos-litestream.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ls284;basis=MemoryMax 256M -> 512M, adds Environment=GOMEMLIMIT=384MiB and RestartSteps=5/RestartMaxDelaySec=60 backoff; ExecStart, user, sandboxing and the config path it reads are unchanged; no new read file:external@0 2fc82f963202103a16a89aaecdcaeb89c6b9fee8e9d0e09cb76389a2326c1714
+@legacy dd04509f15417806594b31ecb103ccb24601157e90650aad3614fe491e334fbf internal/ops/ops.go runLitestream legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ls284;basis=after writing the config, writes the memory drop-in (default /etc/systemd/system/carlos-litestream.service.d/50-memory.conf only when --out is the default config path; --memory-dropin overrides, "none" skips) and calls systemctl daemon-reload; reads only the config it just wrote, via configDBCount; no tenant input reaches the path data-literal@214,file:Open@1374,file:ReadFile@2348 dc5468ad6e019a78ad8322459979ee697d67a076891c733adfed46db7450d440
+@legacy 044780bc15d8ec27e730edfa96b61e1c03afe1137ced8d94eb6cee76f8e52ce9 internal/host/restartwatch.go loadRestartWatch legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: a non-root agent reads its own saved restart counters at <dataDir>/monitor/restarts.json; any malformed or wrong-shape file is an empty watch. A root-run agent never computes the path, loads or saves it (restartWatchFile, newRestartWatchFile gates on euid 0 first; TestRestartWatchFileRootNeverTouchesThePath), per the round-1 census finding file:ReadFile@81 d1c0460e2692dfa99a1a5f2454c6d47d5678edcdf5830ed495e323c126fab26a
+@legacy 2c49e4c7acda29f8a7e4aab407f8e844cba374b9436dc2d6c0dba30752dd2f81 internal/host/restartwatch.go platformUnitRestarts legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: runs fixed argv "systemctl show --property=Id --property=NRestarts --property=ActiveState carlos-*.service" under a 5s deadline; the glob is a constant, parsed output only feeds the restarts alert file:CommandContext@166 fde6a651c0a8a66c324124a2bd3085959c9b575cae08e2d65d2eb666761b0dcc
+@legacy 6aac66ca978be7447619dc56ec356620f6a04e2e983a5b95c255ed157f9006cb internal/ops/litestream_memory.go configDBCount legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: reads the generated litestream config at --out (root-owned, written by this same run) and counts its dbs entries file:ReadFile@61 6d3fc5e14582c88f3e2198858fd5b8c4d2b2cbb96c54d850effacde083a56dbc
+@legacy f1522edd688152807462d9f3546980806260f1c86040a8a58768e4214cf55288 internal/ops/litestream_memory.go writeMemoryDropIn legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: under a flock on the drop-in directory, Lstat of the .reload-pending marker, ReadFile of the existing drop-in to compare bytes, Open of the directory to lock it; writes via safefile; paths are the root-chosen drop-in path and its marker only file:Lstat@713,file:Open@259,file:ReadFile@551 32347ee060400b8353b0f00924cd62024c1df1f938bd3ec06830dfbf58e64f61
+@legacy a93426482cbcc0dcd4adea2fed7ffa8b8cdf27b06b1ff7b4d68b6118effd226e internal/ops/ops.go systemdDaemonReload legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: runs the fixed argv "systemctl daemon-reload" under a one-minute deadline; no input from any caller file:CommandContext@143 42322a947e1763aa00af63d28155b0919cf72ec9909d49e4ec860cfc7817fd4e
+internal/host/units/carlos-litestream.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ls284;basis=MemoryMax 256M -> 512M, adds Environment=GOMEMLIMIT=384MiB and RestartSteps=5/RestartMaxDelaySec=60 backoff; ExecStart, user, sandboxing and the config path it reads are unchanged; no new read file:external@0 2fc82f963202103a16a89aaecdcaeb89c6b9fee8e9d0e09cb76389a2326c1714
+internal/ops/ops.go runLitestream legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ls284;basis=after writing the config, writes the memory drop-in (default /etc/systemd/system/carlos-litestream.service.d/50-memory.conf only when --out is the default config path; --memory-dropin overrides, "none" skips) and calls systemctl daemon-reload; reads only the config it just wrote, via configDBCount; no tenant input reaches the path data-literal@214,file:Open@1374,file:ReadFile@2348 dc5468ad6e019a78ad8322459979ee697d67a076891c733adfed46db7450d440
+internal/host/restartwatch.go loadRestartWatch legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: a non-root agent reads its own saved restart counters at <dataDir>/monitor/restarts.json; any malformed or wrong-shape file is an empty watch. A root-run agent never computes the path, loads or saves it (restartWatchFile, newRestartWatchFile gates on euid 0 first; TestRestartWatchFileRootNeverTouchesThePath), per the round-1 census finding file:ReadFile@81 d1c0460e2692dfa99a1a5f2454c6d47d5678edcdf5830ed495e323c126fab26a
+internal/host/restartwatch.go platformUnitRestarts legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: runs fixed argv "systemctl show --property=Id --property=NRestarts --property=ActiveState carlos-*.service" under a 5s deadline; the glob is a constant, parsed output only feeds the restarts alert file:CommandContext@166 fde6a651c0a8a66c324124a2bd3085959c9b575cae08e2d65d2eb666761b0dcc
+internal/ops/litestream_memory.go configDBCount legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: reads the generated litestream config at --out (root-owned, written by this same run) and counts its dbs entries file:ReadFile@61 6d3fc5e14582c88f3e2198858fd5b8c4d2b2cbb96c54d850effacde083a56dbc
+internal/ops/litestream_memory.go writeMemoryDropIn legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: under a flock on the drop-in directory, Lstat of the .reload-pending marker, ReadFile of the existing drop-in to compare bytes, Open of the directory to lock it; writes via safefile; paths are the root-chosen drop-in path and its marker only file:Lstat@713,file:Open@259,file:ReadFile@551 32347ee060400b8353b0f00924cd62024c1df1f938bd3ec06830dfbf58e64f61
+internal/ops/ops.go systemdDaemonReload legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: runs the fixed argv "systemctl daemon-reload" under a one-minute deadline; no input from any caller file:CommandContext@143 42322a947e1763aa00af63d28155b0919cf72ec9909d49e4ec860cfc7817fd4e
+@coverage internal/alerting eff79e91825e330284a2d0888a9a073f8f08b4205359106b935cfbcf60c87fa9
+@coverage internal/host 5db4e923bbea86766594782186c9a7388ed37b3e9d739ad0cb788aaf1ced4918
+@coverage internal/host/units 8b6547c7e609e302bc28248809135000175b05e3e4d4e2027274b9baad2430f0
+@coverage internal/metrics 325065f9f1d79549ef830be670ebc553835eb49dfc3a22a21027f090e1a794d5
+@coverage internal/ops de5d433916f363ae8d4a05af780d5fe2b28cb495aec351d53dbacb5403bf895f