diff --git a/doc/2026-11-09_design_id5783.md b/doc/2026-11-09_design_id5783.md new file mode 100644 index 0000000000..65e718918d --- /dev/null +++ b/doc/2026-11-09_design_id5783.md @@ -0,0 +1,158 @@ +# Design: ESP32 hardware platform line — boards, provisioning, firmware lifecycle, OTA, power + +- Date: 2026-11-09 +- Status: **decision-ready proposal** — design only; no firmware is implemented here. +- Issue: [#5783](https://github.com/developing-today/code/issues/5783), parent epic [#2056](https://github.com/developing-today/code/issues/2056). +- Relations: [#2343](https://github.com/developing-today/code/issues/2343) (MQTT bridge — the protocol this platform speaks), [#5686](https://github.com/developing-today/code/issues/5686) (capability providers — the model this platform instantiates), [#5684](https://github.com/developing-today/code/issues/5684) / [#5884](https://github.com/developing-today/code/issues/5884) (identity, setup ceremony), [#5671](https://github.com/developing-today/code/issues/5671) (transport fallback — constrained radios). +- Consumes: the bridge spec + labelled PoC in open PR [#7976](https://github.com/developing-today/code/pull/7976) (decided inputs from #5901: retained manifest only, TLS plus per-device credentials, closed device subset, bridge-as-translator); the setup-ceremony record in open PR [#7850](https://github.com/developing-today/code/pull/7850) for #5884 (key generation, first signatures, signed-hash setup artefact). +- Triage history: triage task 13678 (2026-11-08) verified #5783 real and current with no landed record; fix packet task 14116 produced this design. Re-verified 2026-11-09 for task 14116: #5783 is open with no hard-stop labels, #2343 / #5686 / #5684 / #2056 all still open, #7850 and #7976 both still open (records exist as PRs, not on `main`), and no merged PR or commit referencing #5783 exists. This design is the first landed artifact for this issue. +- Evidence baseline: `origin/main` `c2283a57` (2026-11-09). The `doc/hardware` symlink (hardware-doc repo) is not present in this checkout, so no board claim below depends on it; hardware-doc (`devices/`, `components/`, `vendors/`, `guides/`) is the citable source when the reference board is procured. + +## Decision to make + +How does the ESP32 stop being homeless? #2343 scopes out "firmware for a specific board, OTA, ESPHome components, power profiling" and #5686 is deliberately target-agnostic, so five platform questions have no owner: which board(s), how a device gets (and loses) its identity, how firmware is built/signed/updated/rolled back, what the power posture is against a 1 Hz tick floor, and what the device does when power, Wi-Fi, broker, or time itself misbehaves. This record answers all five, settles the issue's four open questions with named defaults, and states the invariants any implementation must hold. + +## Recommendation + +**One reference board, device-owned identity, flake-built signed Rust firmware with A/B rollback, mains-first power with a battery envelope, and a field posture of distrust-everything.** Concretely: + +1. **Board (§1):** one reference board — ESP32-S3 devkit-class — plus a compatibility *envelope*, not a supported family. Anything that fits the envelope may later become a second reference; nothing is supported by assertion. +2. **Identity (§2):** the provider is bound to the **device's own identity** (answering #5686's question for hardware), enrolled through the #5884 setup ceremony. Factory reset destroys the key and re-enrols as a *new* device; a stolen device yields only its own key, expiry-bounded cached grants, and its journal — never user keys. +3. **Lifecycle (§3):** Nix-flake reproducible builds in CI, offline-signed images, A/B partitions with rollback to last-good, OTA fetched over HTTPS (never inside MQTT frames), and the bridge's device-side journal kept as a checksummed ring across reconnects. +4. **Power (§4):** the v1 reference build is mains-powered (Drew's bench); battery operation is a budgeted envelope, not a tested claim. Wake storms are a fleet property handled by jittered exponential backoff seeded per device, on top of the bridge's 1 Hz `time.tick` floor. +5. **Field (§5):** the device is never a time authority (bridge assigns ingest time; the device counts monotonically), works through broker absence on a bounded store-and-forward buffer with gap signalling, never clicks through captive portals (it surfaces a provisioning AP instead), and treats every flash write as if power will die mid-byte (checksummed, two-slot, verify-before-boot). + +## §1 Board posture: one reference board plus an envelope + +**Decision: a single reference board — ESP32-S3 devkit-class (16 MB flash / octal-PSRAM class, native USB) — and a written compatibility envelope. No supported family in v1.** + +The envelope, not a parts list, is what makes this honest: a board is reference-*eligible* when it provides Wi-Fi, ≥16 MB flash, PSRAM, a hardware RNG, and USB flashing without an external UART bridge. The S3 is chosen as the first occupant because it clears the envelope with margin where the alternatives do not: + +| Board | Why not the reference | +| --- | --- | +| **ESP32-S3 devkit-class (reference)** | Native USB (one-cable flash + console), 512 KB SRAM plus PSRAM headroom for the TLS + frame-buffer budget below, BLE for future provisioning UX, current lifecycle. | +| ESP32 classic (WROOM/WROVER) | No native USB; tighter SRAM once TLS and two 64 KiB frame stages are resident. Eligible only in a WROVER (PSRAM) variant and only after the reference proves the budget. | +| ESP32-C3 / C6 | RAM too tight for the §1.1 budget (TLS session plus staged frames leaves no journal/cache margin). Revisit if the firmware's measured footprint ever halves — named revisit, not rejection-forever. | +| ESP32-S2 | Single core, no BLE; buys nothing the S3 does not and closes a provisioning door. | + +### 1.1 Measured against the 64 KiB frame budget + +The bridge's wire bounds (PR #7976: 64 KiB frames, 8 KiB args, manifest ≤ 64 KiB) are a *RAM* budget on the device, not flash. The envelope budget the reference board must hold resident: + +| Resident | Size | Note | +| --- | --- | --- | +| TLS session + MQTT stack | ~30–50 KB | Per-connection; one connection per device per #2343. | +| Frame staging (RX + TX) | 2 × 64 KiB | Never allocate per-message; two fixed arenas, fail-closed on oversize at parse. | +| Journal ring (RAM view) | ~8–16 KB window | The ring itself lives in a flash partition (§3); RAM holds only the active window. | +| Screen cell buffer | ~1 KiB | 128×64 1-bit, per the bridge spec — the reason pixel screens stay small. | +| RTOS / network / app heap margin | ≥100 KB free at steady state | The number the bring-up measures; see invariant I-9. | + +PSRAM holds frame arenas and journal windows; internal SRAM keeps the hot path. The invariant is the margin, not the table: **an image that cannot keep ≥100 KB free heap at steady state on the reference board does not ship** (I-9), and any second reference board must reproduce the same margin before it is named. + +## §2 Identity provisioning: device-owned, ceremony-enrolled, destroy-on-reset + +**Decision: the device holds its own keypair, generated on-device at first boot; enrolment binds it through the #5884 setup ceremony; factory reset destroys the key and the device re-enrols as a new identity. This answers #5686's provider-binding question for hardware: the provider is bound to the device's own identity, and the *user* reaches it through grants and delegation — the user's identity is never installed on the device.** + +- **Key generation:** on-device at first boot from the hardware RNG; the private key never leaves the device and never crosses the bridge. The #5884 setup artefact (signed hash, first signatures) is the enrolment vehicle: the device presents its pubkey, the ceremony binds device-identity ↔ owner ↔ ceiling, and the bridge learns the per-device credential out of band per #5901. Nothing here re-decides #5684/#5884 custody variants — this record consumes them. +- **Re-provisioning:** re-enrolment is always as a *new* device identity. Resurrecting a previous identity is prohibited: it would revive revoked grants and stale discovery entries (#5686 stale-discovery TTLs assume identities die when devices die). +- **Factory reset:** defined as key destruction (wipe the key partition, both slots — §5) plus journal wipe, then first-boot flow. A "reset" that preserves the key is not a reset; it is a settings clear and must not be labelled as one. +- **What a stolen device knows:** its own private key, expiry-bounded cached grants (no-new-grants-while-offline per #5686), and its buffered journal. It does not know user keys, user credentials, or anything outside its ceiling. The highest-value secret on a stolen device is therefore the Wi-Fi PSK in NVS — the field guidance (§5) treats the network credential, not the device key, as the crown jewels, because the device key's blast radius ends at its own identity and its ceiling. + +## §3 Firmware lifecycle: flake builds, signed images, A/B rollback, journaled reconnects + +**Decision: the firmware lifecycle is CI-owned and rollback-first — reproducible flake builds, offline signing, A/B image slots with automatic rollback to last-good, OTA over HTTPS gated on the signed manifest, and a checksummed journal ring that survives reconnects and brownouts.** + +- **Builds in CI/the flake:** every release image is built by the flake (pinned toolchain, locked inputs); a build that cannot reproduce bit-identically from a clean checkout is not a release. The crate-split workspace (#3447 seams) is shared with the firmware where the target allows: wire-bounds constants (`MAX_WANTS_BYTES`, `MAX_ARGS_BYTES`) and the manifest schema types compile for the device so the 64 KiB/8 KiB limits are one definition, not two matching numbers. +- **Signed images:** release images are signed offline; the device holds only the verification pubkey (two-slot, §5). An unsigned image, or an image whose signature does not verify, never becomes bootable — verification happens before the boot flag flips, never after. +- **OTA with rollback to last-good:** A/B image slots plus an OTA-data record of (boot candidate, boot count, confirmed-good). A newly flashed slot must confirm (successful boot + bridge connect + manifest accept, bounded by a confirmation window) or the bootloader reverts to last-good automatically. Rollback is not a user action; it is what happens when confirmation does not. OTA images are fetched over **HTTPS**, never carried inside MQTT frames — pushing megabytes through 64 KiB `wants`-shaped frames would pervert the bridge's wire budget into a file-transfer protocol. +- **Device-side journaling (the #2343 inheritance, spelt as lifecycle):** the device keeps a checksummed ring journal (ticks, input events, pending results) in a dedicated flash partition. Across reconnects the journal is the continuity: on reconnect the device republishes its manifest (per PR #7976 no other recovery step is needed for the bridge), then replays unacknowledged journal entries in sequence-number order with explicit gap signals for anything dropped under the §4/§5 drop policies. Journal sequence numbers are monotonic per boot epoch; epochs are part of the sequence so a reboot never replays old entries as new. + +## §4 Power: mains-first reference, battery as envelope, wake storms as fleet property + +**Decision: the v1 reference build is mains-powered. Battery operation ships as a budgeted envelope with named numbers, not as a tested claim. Wake-storm avoidance is engineered at the fleet level (jittered, per-device-seeded backoff), not hoped for per device.** + +- **Sleep/wake against the `time.tick` floor:** the bridge's minimum tick is 1 Hz (PR #7976 `MIN_TIME_TICK_MS = 1000`, chosen to avoid wake storms on ESP32-class radios). A mains reference subscribes at 1 Hz freely. A battery build may not: every tick is a radio wake, so battery builds negotiate slower effective rates (downsampled ticks, event-driven wake on inputs) and the firmware treats the 1 Hz floor as a *ceiling on politeness* — the device may always ask for less, never more. Deep sleep between events is the normal battery posture; light/modem sleep covers the middle ground. +- **Battery budget (envelope, to be measured on the reference before any battery claim freezes):** Wi-Fi TX peaks (~hundreds of mA) dominate; a back-of-envelope 3000 mAh cell with a mostly-sleeping sensor build and minute-scale reporting lives in the weeks-to-months band, while a 1 Hz tick subscriber lives in the hours-to-days band. The record deliberately does not publish a battery-life number — the invariant (I-10) requires a measured profile on the reference board before any number ships, because an unmeasured battery claim is how hardware lines lie. +- **Wake-storm avoidance:** reconnect backoff is exponential from 500 ms capped at 30 s (PR #7976), and the firmware MUST jitter it with a per-device seed derived from the device identity hash — so a fleet-wide power event or broker flap does not become a synchronized reconnect hammer. Stagger is a fleet property verified in the fake-device soak (thousands of simulated devices, one broker flap, no synchronized retry spike), not a per-device hope. + +## §5 Field behaviour: distrust power, network, broker, and time — in that order + +**Decision: the field posture is fail-closed and self-describing — the device assumes every dependency is lying or absent until proven otherwise, and every degraded state is visible on the device's own screen.** + +- **No-RTC time:** the device is never a time authority. Before it learns the time it operates *untimed*: journal entries carry (boot epoch, monotonic sequence) instead of wall-clock, and anything needing time (grant expiry checks, backoff scaling) uses the monotonic counter conservatively (assume the worst: grants are treated as near-expiry until real time arrives). Timestamps are assigned at bridge ingest — provenance time is bridge time, and the record states that plainly so no consumer mistakes a device counter for a clock. Whose time the device trusts: the bridge's, delivered inside the authenticated session — never Wi-Fi captive-portal JavaScript, never unauthenticated NTP from the LAN. +- **Broker absence:** bounded store-and-forward. The journal ring absorbs the outage; when full, the drop policy is oldest-first with an explicit gap signal on reconnect (the consumer learns exactly what it missed, per #5686's gap-signalling requirement). Grants are cached with expiry; no new grants are issued or accepted while offline (I-7). Actuation while offline is allowed only under a standing grant whose scope explicitly permits it — the #5686 per-class question answered for hardware: standing-grant actuation yes, novel actuation never. +- **Captive-portal Wi-Fi failures:** association without connectivity is a distinct, detected state (the connectivity check is a TLS handshake to the known broker endpoint, not a plaintext HTTP probe — a portal's intercept page can never satisfy it). The device never clicks through a portal. It surfaces the state on its own screen ("Wi-Fi needs sign-in — see ") and opens its provisioning AP with the fixed SSID pattern, where the owner can supply new credentials. Portal-bypass automation is a non-goal with a reason: it would teach the device to hand credentials to attacker-controlled pages. +- **Brownout mid-write:** every persistent write is checksummed and two-slot. Keys, OTA-data, and journal segments are written to the inactive slot, verified, then flipped; a torn write fails verification and the previous slot stands. The boot path prefers last-good by construction (the same mechanism as OTA rollback — one rule, two callers). NVS holds only the Wi-Fi credential and non-critical settings; anything the device cannot afford to lose lives in the journaled partitions, never in bare NVS. + +## Viable options (rejected alternatives and why) + +| Option | Trade-offs | Decision | +| --- | --- | --- | +| **One S3 reference + envelope (this design)** | One board to buy, measure, and support; the envelope keeps a second board honest later. Costs saying "no family" in v1. | **Recommend.** A family on day one is N untested claims wearing a support badge. | +| Supported family from day one (S3 + C3 + classic) | Feels generous; multiplies bring-up, power, and OTA-matrix work by three before the first field lesson lands. Each variant's RAM story differs, so the "one firmware" claim would already be false. | Reject for v1. The envelope names the path to a second reference (§1). | +| ESP32 classic as reference (cheaper, ubiquitous) | Cheapest bench, most tutorials. But no native USB and the thinnest RAM margin against the §1.1 budget — the reference would start life as the board most likely to violate I-9. | Reject. Eligible as a later second reference in a PSRAM variant only. | +| **Device-owned identity via #5884 ceremony (this design)** | Matches #5686's provider-binding question with the answer that survives theft (§2); keeps user keys off the device. Costs a real enrolment UX. | **Recommend.** | +| Install the user's identity on the device | Simpler enrolment (no binding step). But a stolen device then yields the user's key — the blast radius of a $10 board becomes the user's whole ID. | Reject. This is the failure the custody-honesty requirement in #5684 exists to forbid. | +| Server-held device keys ("provisioning service keeps a copy") | Enables painless re-provisioning and recovery. Creates a key escrow for every field device — a breach database of other people's hardware — and contradicts on-device generation. | Reject. Re-provisioning is by re-enrolment as a new identity (§2), not by key recovery. | +| **Rust on esp-idf, sharing workspace crates (this design)** | Memory safety on a network-facing parser of 64 KiB frames; one definition of wire bounds via shared crates. Costs the Rust-embedded learning curve and esp-idf build weight. | **Recommend** (answers Q1). | +| C on esp-idf / Arduino | Largest example corpus, fastest bench start. Two-language workspace forever, and hand-rolled parsing of hostile-sized frames in C on a radio-connected device. | Reject for the shipping firmware. C remains acceptable for throwaway bench probes that never become product. | +| Bare-metal esp-hal + embassy-net (no esp-idf) | Cleaner Rust, no IDF blob weight. The production Wi-Fi/TLS/OTA stack maturity the line needs in v1 lives in esp-idf today; betting v1 on a still-maturing net stack is schedule risk with no field payoff. | Reject for v1 with a named revisit: re-evaluate when embassy-net on ESP32 carries the TLS+OTA story the line needs. | +| OTA images over MQTT (topics as file transfer) | One transport for everything. Perverts the bridge's 64 KiB wire budget into a file protocol, keeps the radio hot for minutes, and couples firmware delivery fate to broker session fate. | Reject. OTA is HTTPS (§3). | +| Device as time authority (NTP client, RTC module) | Real timestamps at the edge. Adds hardware (RTC + battery) or trusts unauthenticated LAN time; either way consumers cannot distinguish device time from bridge time, so provenance lies by precision. | Reject. Bridge assigns ingest time (§5). | + +## Implementation invariants (must hold; testable where stated) + +- **I-1 (closed subset):** the firmware speaks only the #2343 closed subset (`device.info`, small `screen`/`text`, closed `form.*`, `loc.position` iff GNSS present, key/encoder events). Anything else on the wire is a bug, not an extension. +- **I-2 (retention):** the manifest is the only retained document; `wants` are never retained. Enforced at both ends: the device never sets retain on `wants`, per PR #7976 the bridge rejects retained `wants` outright. +- **I-3 (bounds):** 64 KiB frames, 8 KiB args, enforced at parse on the device before any allocation beyond the arenas — oversize input rejects the document, never grows a buffer. +- **I-4 (fail-closed auth):** TLS plus per-device credentials; unknown device or wrong token refuses before any publish/delivery, and the refusal reveals nothing about which half was wrong (PR #7976's no-oracle rule). +- **I-5 (journal continuity):** journal sequence is monotonic per (epoch, sequence); a reboot starts a new epoch and never replays old entries as new; gaps are signalled, never silent. +- **I-6 (rollback):** no image becomes the boot image without full signature verification; no image becomes last-good without passing the confirmation window; an unconfirmed image reverts automatically. +- **I-7 (offline grants):** cached grants carry expiry and are honoured offline; no new grants are issued or accepted while disconnected; novel actuation while offline is prohibited. +- **I-8 (no device time authority):** no device-originated timestamp is presented as wall-clock to any consumer; provenance time is bridge ingest time. +- **I-9 (heap margin):** steady-state free heap on the reference board stays ≥100 KB; a build that violates this does not ship, whatever it proves. +- **I-10 (measured power):** no battery-life number ships without a measured profile on the reference board; the §4 envelope is a budget, not a claim. + +## Answers to the issue's open questions + +### Q1 — Firmware language/stack: Rust (esp-hal / esp-idf) vs C — and what the crate-split workspace can share? + +**Decision: Rust on esp-idf, sharing the workspace's wire-bounds constants and manifest schema types** (compiled for the target behind the #3447 seams). esp-hal bare-metal is rejected for v1 with a named revisit (embassy-net maturity); C is rejected for the shipping firmware (two-language burden plus hand-parsed hostile frames). The shared-crates answer is the load-bearing part: the 64 KiB/8 KiB limits must be one definition the device and the bridge both compile, so they cannot drift into two matching numbers. + +### Q2 — ESPHome: interop target, migration source, or ignore? + +**Decision: interop target only.** The #2343 Home-Assistant-interop posture extends here unchanged: ESPHome devices in the field stay friendly through HA bridging to the same topics, but nothing in the line depends on ESPHome, migrates from it, or speaks its YAML model. Rationale: the ESPHome component model cannot express the closed capability subset, the grant model, or the declaration artefact — adopting it as source would mean re-deciding #5686 inside YAML. Revisit trigger (named, not ignored): if ESPHome ever gains an external-component story capable of carrying `id.device.v1` semantics, re-evaluate. + +### Q3 — Hardware-in-the-loop: does a physical rig join deterministic testing, or is the fake-device PoC the permanent test double? + +**Decision: the fake device is the permanent deterministic test double; a physical rig never gates.** The `FakeDevice` from PR #7976 (journal, minimum tick, backoff, encoder-as-Key) graduates into the line's conformance double: bounds enforcement, refusal vocabulary, journal replay, gap signalling, and fleet-scale backoff soak all run against it in CI. Drew's bench rig exists for manual and perf validation (power profiles for I-10, real-radio behaviour), and rig results are informational — a rig failure investigates, never blocks. Rationale: a physical rig in the deterministic path is flaky-by-physics and unownable in sandboxed CI; gating on it would make the line's tests nondeterministic by construction. + +### Q4 — Who is the hardware line *for* in v1 — Drew's bench, or a reproducible build others can flash? + +**Decision: Drew's bench first, reproducible-by-construction for everyone else.** The v1 audience is one bench, one reference board, one builder — and the flake-reproducible build (§3) is what makes "others can flash" true without staffing support. Support burden for third-party builders is explicitly deferred: the image is reproducible, the envelope is written, and questions beyond that wait for a v2 audience decision. This keeps the line honest — reproducible but unsupported beats documented-but-unbuildable. + +## What this record does not do (non-goals; #2343 / #5686 / #5684 decisions preserved) + +- No firmware is implemented here, and no board is procured; the reference board is named, not bought. +- The bridge protocol is not re-decided: topic schema, wire bounds, retention rules, backoff numbers, and the closed subset are consumed from #2343 / PR #7976. Where this record answers an open bridge decision (journal shape, jittered fleet backoff, actuation-while-offline), it says so explicitly (§§3–5). +- The provider model is not re-decided: declaration, grants, delegation, and offline semantics are #5686's; this record instantiates them for hardware and answers only the question #5686 posed to hardware (device-owned binding, §2). +- Custody variants are not re-decided: key custody, recovery, and delegation UX are #5684/#5884's; this record consumes the setup artefact and the enrolment binding. +- Transport fallback is not re-designed: #5671 owns fallback ordering; the captive-portal and broker-absence postures here (§5) degrade consistently with it and invent no parallel fallback. + +## Implementation slicing (for follow-on issues, not this design) + +1. **Reference bring-up:** procure the S3 reference, prove the §1.1 heap margin (I-9), publish the measured power profile (I-10). Gates every battery claim. +2. **Firmware skeleton (Rust/esp-idf):** closed-subset speaker against the #7976 `FakeBroker`, sharing workspace wire-bound crates; `FakeDevice` conformance suite as the acceptance gate (Q3). +3. **Provisioning ceremony with #5884:** on-device keygen, enrolment binding UX, factory-reset-as-destruction, stolen-device review against §2. +4. **OTA pipeline:** flake-signed images, HTTPS delivery, A/B + rollback (I-6), journal preservation across updates. +5. **Field hardening:** untimed-mode operation, bounded store-and-forward with gap signals, provisioning-AP portal handling, brownout soak (power-cut test rig, informational per Q3). + +Each slice files as its own implementation issue referencing this design; per the standing rule, this design issue stays open until Drew reviews the design or the first implementation issue supersedes it — a merged design PR is not, by itself, closure. + +## Definition of done for this design ticket + +- [x] A decision-bearing record exists under `doc/` and is linked from #5783, covering board posture (§1), identity provisioning (§2), firmware lifecycle (§3), power (§4), and field behaviour (§5) — each with chosen shape, rejected alternatives, and reasons. +- [x] Implementation invariants I-1–I-10 are stated with testability notes. +- [x] All four open questions are settled with named defaults (Q1 Rust/esp-idf + shared crates; Q2 ESPHome interop-only; Q3 fake-device gates, bench informs; Q4 bench-first, reproducible-by-construction). +- [x] Relations (#2343, #5686, #5684/#5884, #5671, epic #2056) are linked with accurate states, and no parent/sibling decision is silently re-decided. +- [x] No production code or unrelated issue work is included (this PR adds one file).