### Issues Fixed
Anthias has no way to surface host/system logs. `bin/collect_d…ebug.sh` shells out to `journalctl` on bare metal, but that is a manual operator script — nothing in the app or API can read the journal.
### Description
Adds `GET /api/v2/system/logs`: a **snapshot-only** journal read with one contract on both supported platforms. No `follow` on either — the bare-metal backend runs inside the host agent's single-threaded `subscriber_loop`, where a streaming read would queue reboot/shutdown behind it forever, and offering a live tail on Balena alone would mean two divergent contracts.
Parameters: `count` (default 500, hard cap 2000), `unit`, `container`, `since`, `until`.
**Balena** — supervisor `POST /v2/journal-logs`. No compose change and no new privilege; `anthias-server` already carries `io.balena.features.supervisor-api`. Requests `format: json` so the payload is shaped identically to bare metal and one normaliser serves both backends.
**Bare metal** — `anthias-host-agent` over `hostcmd`, now accepting a JSON payload with a correlation ID alongside the original bare-string commands (so rollout order does not matter). The reply goes onto a correlation-keyed Redis list with a TTL and is collected with a bounded `BLPOP` — a blocking pop rather than a completion pub/sub, because it has no subscribe-before-publish race and matches the `anthias.reply.<id>` pattern already used on the viewer bus.
Nothing in the path can block `subscriber_loop`: bounded by lines, by bytes and by a subprocess timeout, and every failure path still writes exactly one reply so the container's pop resolves instead of timing out.
Also here:
- `SupplementaryGroups=systemd-journal` on the host-agent unit, plus a hard refusal when the system journal is unreadable. `journalctl` exits 0 for a caller outside that group and hands back the service account's own user journal with every system record missing — and under `--output=json` it does not even print its stderr hint, so there is no signal to key off. The agent asks the kernel (`os.access`) instead, which also honours the ACL journald grants to `adm`.
- Journald persistence and size caps in the Ansible role, **off by default** behind `anthias_journal_persistent`. See the correction at the bottom: a player writes 19-28 MiB of journal a day, and Raspberry Pi OS pins `Storage=volatile` to keep that off the SD card deliberately. The endpoint does not need persistence, so the role no longer overrides that choice. When an operator does opt in, `99-anthias.conf` wins over `40-rpi-volatile-storage.conf` and is followed by `journalctl --flush`, because a restart alone leaves the journal in `/run` until the next boot.
- `persistent` is reported in the response rather than assumed, measured from which of `/var/log/journal` and `/run/log/journal` holds the live journal. Both cheaper probes give a wrong "yes" on hardware we ship on.
- Secret-looking values (`psk`, `passphrase`, tokens, `Authorization`) are blanked on the way out, keeping the key visible.
**Note for operators:** persistence is opt-in (`anthias_journal_persistent: true`). When enabled, `SystemMaxUse=64M` is enforced by vacuuming, so on an install whose journal already exceeds it the first journald restart discards the excess. A QA x86 board had grown to 1.8 GB and came back at 56 MB. Override `anthias_journal_max_use` where the longer history matters more than the card.
### Checklist
- [x] I have performed a self-review of my own code.
- [x] New and existing unit tests pass locally and on CI with my changes.
- [x] I have done an end-to-end test for Raspberry Pi devices.
- [x] I have tested my changes for x86 devices.
- [ ] I added a documentation for the changes I have made (when necessary).
End-to-end on the QA rig (Pi 5 / aarch64 and x86, both Debian 13), host agent and server overlaid from this commit with hashes verified in place: snapshot, every filter, parameter rejection, five concurrent requests each getting their own result, reply TTL, 2000-line read in 0.49s / 0.80s with the next host command answered ~250ms later, and redaction of a real `logger`-injected line. Both boards restored to their pinned images afterwards.
Verified against the real OS permission state on both boards: with the supplementary group withheld, `journalctl -u docker.service` returns **0** lines and exit code 0; with it, 50. The agent now refuses that case with an actionable error instead of serving a silently empty view.
The Balena backend was exercised over real HTTP inside the server container against a supervisor stub — correct URL, version and API key, correct body, `follow: false`, identical normalised output, redaction, and the 4 MiB cap holding on a streamed 9 MB response. **It has not been run against a real balenaOS supervisor**; the rig has no balena device.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---
### Review follow-ups
Six findings from a review pass, all fixed and re-verified on the Pi 5 and x86 boards:
- **`redact()` was quadratic.** A 48 KB line (journald's default `LineMax`) took about a minute and pinned a request worker; measured 6.3 s at 16 KB. A lookbehind means only a real token start can begin a match — 48 KB is now 0.003 s, with every redaction case unchanged.
- **The Balena path kept the *first* 4 MB while the host agent kept the last.** `journalctl` emits oldest-first, so the supervisor backend was discarding exactly the entries an operator opened the log to read. It now trims from the front, and bounds total bytes read as well as bytes kept.
- **`container` returned an empty 200 on Balena.** It means a name on both platforms, but the supervisor only matches `CONTAINER_ID_FULL`. It is now resolved via `/v2/containerId`, an ID is passed straight through, and an unknown service fails loudly instead of looking like a quiet device.
- **A stopped host agent blocked every request for the full 30 s `BLPOP`.** `PUBLISH` reports its subscriber count; zero means no reply is coming. Now 502s in ~0.02 s.
- **`text=True` decoded journalctl output with the locale encoding and strict errors** — and a systemd unit has no `LANG`, so that is ASCII. One non-ASCII byte would have raised out of `process_message` and killed `subscriber_loop`, the exact failure this feature is built to avoid.
- **`count` help_text claimed "most recent first"**; entries are oldest-first. It is published in the OpenAPI schema.
Chasing the first SonarCloud finding also turned up a real gap: creating `/var/log/journal` ourselves skipped the `a+` tmpfiles line that grants the `adm` group its read ACL, so adm-based journal access would silently not have worked on a host where we made the directory. The role now runs `systemd-tmpfiles --create`, the other half of the recipe documented in `journald.conf(5)`.
---
### Hardware QA follow-up
Full integration run across the QA rig — x86_64, aarch64 (Pi 3/4/5) and armv7l (Pi 2, Pi 3 A+), Debian 13 and Raspbian 13 — turned up one defect in this branch, now fixed here.
**The blocking pop was not bounded by its own timeout.** `BLPOP` ran on the shared `connect_to_redis()` client, which takes redis-py's defaults: `socket_timeout=5` with `Retry(retries=10)`. A 30s pop cannot survive a 5s socket read, so the socket expired first and the retry ladder re-issued the pop ten more times. Measured at **59.6s on x86 and 58.2s on a Pi** against a host agent that was subscribed but not answering — roughly twice `REPLY_TIMEOUT_SECONDS`, which bounded nothing. It also made the `reply is None` branch unreachable, so the case surfaced as *"Could not reach the host agent over Redis"*, pointing an operator at a healthy broker.
The path is reachable on a normal upgrade: with the container updated before the host agent, the old agent is still subscribed, so `PUBLISH` reports a non-zero subscriber count and the fast-fail for a stopped agent does not apply.
The blocking pop now gets its own client — socket outliving the pop timer, no retries — verified on hardware: **30.05s** and the accurate *"Check that anthias-host-agent is running and up to date"* message. A stopped agent still fails in ~0.015s, and slow-but-completing reads are unaffected (six queued 2000-line reads on a Pi 2, waits to 17.7s, all delivered in full).
Also confirmed on hardware, alongside 24/24 API checks on five boards:
- The Ansible role is idempotent, and `99-anthias.conf` beats Raspberry Pi OS's `40-rpi-volatile-storage.conf` — verified both by `systemd-analyze cat-config` and by the journal physically moving out of `/run`.
- `persistent` measured rather than inferred is doing real work: a Pi 5 with 8 stale files in `/var/log/journal` while journald wrote to `/run` correctly reported `false`. Both cheaper probes would have lied on that board.
- **Reboot test** — a line written before a reboot issued through `/api/v2/reboot` was readable through the API afterwards, and previous-boot entries stayed reachable.
- Truncation keeps the newest entries (120 × 47 KB lines: capped at 3.90 MiB, oldest dropped), and `redact()` is linear — 1.40s for a 2000-line read containing 87 × 47 KB lines.
- 2000-line read latency: x86 0.48s, Pi 5 0.30s, Pi 4 0.81s, Pi 3 1.70s, Pi 2 4.20s.
Two notes for reviewers, neither a code change:
- The permission claim above is narrower than written. On these images the install user is already in `adm`, and journald grants `adm` journal access by ACL, so `journalctl -u docker.service` returns rows without `SupplementaryGroups=systemd-journal`. Withholding `adm` as well reproduces the silent empty read exactly as described, so the grant is worth keeping as defence in depth — it just isn't what makes logs readable on a stock install.
- The `SystemMaxUse` warning is real and worth repeating in release notes: on the x86 board the first journald restart took the journal from 1.8 GB to 56 MB, discarding about 3.7 months of history.
`since`/`until` already cover relative and absolute ranges (`-5m`, `-2h`&`-1h`, `@<epoch>`), but two sharp edges are worth knowing for any UI built on this: the API's own `timestamp` is not valid input (the allowlist has no `.`), and absolute timestamps are read in the device's **local** timezone while the API returns UTC — the mismatch yields a `200` with an empty list rather than an error. Both are left as-is here and tracked for the follow-up that surfaces this in the web UI.
---
### Correction: persistent journald is no longer enabled by default
The first version of this branch wrote `Storage=persistent` on every install, overriding the `Storage=volatile` that Raspberry Pi OS pins in `40-rpi-volatile-storage.conf`. That override was wrong. The vendor setting exists to keep journald off the SD card, and a player's journal is not small:
| Board | Journal written |
|---|---|
| Pi 5 (aarch64) | 19-25 MiB/day — ~7-9 GiB/year |
| Pi 2 (armv7l) | 21-28 MiB/day — ~8-10 GiB/year |
| x86 | 27 MiB/day |
Measured over 1h/6h/24h windows on **idle** QA players carrying the normal Anthias stack, before any real content churn. The bulk is our own containers: `anthias-server` and `anthias-celery` together account for roughly half the entries. It is also the write pattern SD cards handle worst — small appends with a periodic fsync, amplified by the card's internal block management.
**The endpoint never needed it.** The host agent reads the volatile journal in `/run` perfectly well. Verified on a Pi 5 left on the image default: `GET /api/v2/system/logs` returns 500 entries with `persistent: false`, and `unit`, `container` and `since` filters all work — 24/24 of the API suite passes with journald writing nothing to the card. Persistence only buys history that survives a reboot, and `persistent` in the response already tells a client which one it got, so a device on the default is honest about showing current-boot-only logs rather than silently truncated ones.
So it is now `anthias_journal_persistent`, defaulting to `false`:
- With the flag off the role writes nothing and leaves the image default intact — verified on a Pi 5, where a full role run skips all four persistence tasks and leaves `Storage=volatile` with the journal still in `/run`.
- It also **removes** `99-anthias.conf` when the flag is off, so flipping it back restores the vendor setting instead of stranding our override. Verified by enabling, confirming `Storage=persistent` with the journal moved to `/var/log/journal`, then disabling and watching it converge back to `volatile` and `/run`.
- Creating `/var/log/journal` moved inside the conditional too. On an image without the Pi vendor drop-in, Debian's `Storage=auto` means creating that directory is itself the persistence switch.
- `SupplementaryGroups=systemd-journal` on the host-agent unit is unaffected — that is what actually makes the journal readable, and it costs nothing in writes.
Both tunables moved from `vars/` to a new `defaults/`, because role vars outrank inventory and group_vars: a per-device override set the normal way would have been silently ignored from where they were.