Skip to main content

embassy_supervisor/
lib.rs

1// `no_std` for the shipped crate and the embedded build; under `cargo test` the
2// crate is built for the host, where the test harness and the unit tests need `std`.
3#![cfg_attr(not(test), no_std)]
4#![forbid(unsafe_code)]
5#![deny(missing_docs)]
6//! # embassy-supervisor — a task-lifecycle supervisor for [embassy](https://embassy.dev)
7//!
8//! Application- and HAL-agnostic primitives for orchestrating a set of embassy
9//! tasks: bringing them up in dependency order, tearing them down in reverse,
10//! scaling an elastic worker pool with load, placing nodes on interrupt-priority
11//! tiers or a second core, and starting/stopping/pausing/resuming individual
12//! tasks at runtime while keeping the dependency graph consistent. The supervisor
13//! orchestrates task *lifecycle* and leaves the rest — allocation, HAL, power,
14//! what the tasks do — to the application.
15//!
16//! ## The model
17//!
18//!   * The graph is declared once with the [`supervisor_graph!`] macro: each
19//!     managed task becomes a [`TaskNode`] `static`, and the macro bundles the node
20//!     slots, dependency table, and a topological order computed **at compile time**
21//!     into a single [`Graph`] (`GRAPH`). The whole graph is validated at compile
22//!     time — a dependency cycle, an unknown or duplicate dependency, a duplicate
23//!     name, or bad pool bounds are compile errors.
24//!   * [`Supervisor::new`] takes `&GRAPH` (no work, no failure) and uses the order
25//!     to bring tasks up in dependency order ([`Supervisor::start`]) and tear them
26//!     down in reverse ([`Supervisor::teardown`]).
27//!   * `executor NAME;` items declare runtime-filled [`SpawnerSlot`]s, and
28//!     `executor: NAME` on a node (or a whole pool) routes its spawn through one —
29//!     an interrupt-priority tier or the second core. Bring-up *awaits* the slot
30//!     (bounded), so an executor that comes up late — or on another core — is a
31//!     rendezvous, not a race.
32//!   * Each managed task names its worker with either `task:` (preferred) — a
33//!     **plain `async fn`** that the macro wraps in a generated
34//!     `#[embassy_executor::task]` shell (one concrete shell per declaration, so a
35//!     *generic* worker is fine) — or `spawn:`, naming a hand-written
36//!     `#[embassy_executor::task]` directly. A `task:` pool emits one shell sized to
37//!     its members; `pool_size: N` sizes a single node's shell.
38//!   * `resources: [NAME: Type, ..]` on a `task:` node threads **owned resources
39//!     from `main`** into the worker through macro-emitted [`ResourceSlot`]s —
40//!     compile-time exclusive ownership (the `Peripherals` field is consumed, no
41//!     `steal()` inside the task), fail-closed provisioning (an unprovided slot
42//!     fails `start` with `SpawnError::Busy`), and restore-on-exit so a respawn
43//!     re-takes the *same instance*. Per-entry kind markers refine that
44//!     default: `consume` hands the worker the value **by value** with no
45//!     restore (drop-at-teardown drivers; rebuilt-per-cycle resources — a
46//!     respawn fail-closes until the app re-`provide()`s); `shared` is a
47//!     fan-out slot for a `Copy` handle (the glue copies via
48//!     [`ResourceSlot::get`], the slot stays filled — any number of nodes and
49//!     whole pools may declare the same name); and `local` swaps in a
50//!     graph-site slot without the `T: Send` bound (`!Send` driver handles,
51//!     single-core contract) — it makes the macro emit an `unsafe impl Sync`
52//!     into the consuming crate, so it requires the non-default
53//!     `local-resources` feature. See the macro docs for the markers' fine
54//!     print.
55//!   * The pre-spawn waits are per-node tunable (`slot_timeout:` /
56//!     [`TaskNode::with_slot_timeout`]), which makes **provider nodes** work: a
57//!     first-in-topo node whose worker *builds* resources at runtime and
58//!     `provide()`s them into other nodes' slots (the graph-native `hw_init`);
59//!     consumers size their timeout to the build and the gate wait becomes a
60//!     rendezvous.
61//!   * Two flags span every lifecycle operation: **disabled** (stopped until an
62//!     explicit `Activate` — declared `disabled` in the graph or control-stopped;
63//!     see [`TaskNode::set_disabled`]) and **detached** (self-managed: after
64//!     [`TaskNode::set_detached`] no supervisor operation touches the node).
65//!   * Each node carries a `TaskHandle` of per-node atomic flags and
66//!     single-consumer `Signal`s. Every node is single-instance — no counts, no
67//!     fan-out. See [`TaskHandle`].
68//!
69//! ## Three lifecycles, distinguished by [`Mode`]
70//!
71//!   * [`Mode::Terminate`] — the task exits its loop on shutdown and is respawned
72//!     on the next bring-up. Stateless services (a network listener, a logger).
73//!   * [`Mode::Pause`] — the task acks the shutdown then parks on
74//!     `wait_resume()`; it is resumed in place, never respawned. Tasks that
75//!     retain a resource across the pause (an open peripheral handle, a socket).
76//!   * [`Mode::OnDemand`] — like `Terminate`, but not started at boot and not
77//!     auto-respawned; the supervisor brings it up and down at runtime to scale
78//!     an elastic worker pool ([`ElasticPool`]) with load.
79//!
80//! ## Writing a supervised task
81//!
82//! A supervised worker's first parameter is its node. With `task:` you write a
83//! plain `async fn` and the macro stamps the `#[embassy_executor::task]` shell
84//! (and, with `resources:`, hands it `&mut` resource handles after the node, in
85//! declared order); with `spawn:` you write the `#[embassy_executor::task]`
86//! yourself. Either way the macro's glue passes the node, and extra arguments come
87//! from the partial-call spawn form. Four rules cover the task side of the protocol:
88//!
89//!   1. race long-lived work against the stop request — that's how a stop reaches
90//!      you. [`TaskNode::run_cancellable_acked`] is the everyday body (it owns the
91//!      `select` and acks for you; `Err(`[`Aborted`]`)` means a stop won),
92//!      [`TaskNode::run_cancellable`] the variant with cleanup between the two, and
93//!      [`TaskNode::wait_shutdown`] the raw signal when you write the `select`
94//!      yourself;
95//!   2. ack exactly once per stop with [`TaskNode::ack_dropped`]: on exit
96//!      (`Terminate`/`OnDemand`), or on each pause (`Pause`) *before* parking on
97//!      [`TaskNode::wait_resume`];
98//!   3. an autonomous exit calls [`TaskNode::mark_exited`] instead — it acks *and*
99//!      records completion, so the supervisor sees the node as down and
100//!      [`TaskNode::has_exited`] tells a body that returned on its own from one
101//!      that was stopped (a `task:` shell does it for you);
102//!   4. resources follow the mode: a `Terminate` task re-acquires everything on
103//!      respawn (drop-on-exit is the cleanup), a `Pause` task keeps what it holds
104//!      across the park.
105//!
106//! Pool workers additionally report load with [`TaskNode::mark_busy`] /
107//! [`TaskNode::mark_idle`] (a real transition fires the scale signal itself), and
108//! a self-managed daemon or run-once job opts out of supervision with
109//! [`TaskNode::set_detached`]. The README's *Writing supervised tasks* section has
110//! per-mode skeletons.
111//!
112//! ## Beyond bring-up
113//!
114//!   * [`Supervisor::run`] is bring-up plus the driver loop (pool scaling and the
115//!     control mailbox) in one call; it returns only on a [`RunError`], which the
116//!     application escalates. Drive the pieces yourself when the loop must watch
117//!     extra wake sources.
118//!   * Every shutdown path is fallible, never a library panic: [`Supervisor::teardown`]
119//!     aborts at the first node that misses its ack and returns a [`ShutdownTimeout`]
120//!     naming it, [`Supervisor::teardown_continue`] presses on through the rest and
121//!     reports the first failure at the end (the "hardware reset next anyway" path).
122//!   * `exit: Type` on a node adds a typed exit-value slot the application awaits
123//!     with [`ResourceSlot::wait_take`] — a run-once job hands its result back.
124//!     `state: Type = expr` (feature `heap-state`) boxes per-activation state that
125//!     is freed when the task exits, so a stopped subsystem costs no RAM.
126//!   * Feature `readiness` separates *spawned* from *serving*: a task asserts
127//!     `set_ready()` and a `deps: [NET ready]` edge makes bring-up (and pool growth)
128//!     wait for it. Feature `liveness` adds a per-node heartbeat (`beat()` /
129//!     `is_stale()`) for alive-but-wedged detection.
130//!   * A graph can span crates: `supervisor_fragment!` declares a module's nodes and
131//!     [`compose_graph!`] assembles the fragments into one graph. `name: IDENT;`
132//!     gives a second graph in the same binary its own statics and [`Supervisor`],
133//!     for a subordinate sub-graph an application starts and tears down as a unit.
134//!
135//! ## What the supervisor does *not* do
136//!
137//!   * It does not model any power-state transition (sleep/wake): it reacts to
138//!     "teardown" and "bring-up" requests; the application drives them.
139//!   * It does not allocate, and does no work at construction: the topological
140//!     sort runs at compile time (see the `supervisor_graph!` macro).
141//!   * It does not observe task internals. Tasks self-report their drop state via
142//!     `ack_dropped()` / `mark_exited()`; a task that misses the ack window comes
143//!     back as a [`ShutdownTimeout`] naming the node, for the application to act on.
144//!   * It does not catch panics: a panicking task is not captured or restarted.
145//!     Pair the supervisor with a hardware watchdog for crashes, and the `liveness`
146//!     heartbeat for tasks that are alive but wedged.
147//!
148//! ## Cargo features
149//!
150//!   * `control` *(default)* — the runtime control plane: [`ControlOp`],
151//!     [`request_control`], [`Supervisor::apply_control`].
152//!   * `pool` *(default)* — elastic worker pools: [`ElasticPool`],
153//!     [`Supervisor::run_pools`], and the `pools` field of [`Graph`].
154//!   * `macros` *(default)* — the [`supervisor_graph!`] graph-declaration macro (and
155//!     `supervisor_fragment!` / [`compose_graph!`]).
156//!   * `local-resources` — permit the `local` resource kind; ⚠ opting in to the macro
157//!     emitting a documented `unsafe impl Sync` into your crate.
158//!   * `readiness` — `set_ready`/`clear_ready`/`wait_ready` plus the `ready` dep
159//!     marker, gating bring-up and pool growth on *serving*, not merely spawned.
160//!   * `liveness` — a per-node heartbeat: `beat()`, `ticks_since_beat()`,
161//!     `is_stale(max_age)`. A fresh spawn counts as a beat.
162//!   * `heap-state` — the `state: Type = expr` clause: per-activation boxed state,
163//!     reclaimed on task exit; ⚠ emits a small `unsafe` fallible-boxing helper and
164//!     needs a `#[global_allocator]`.
165//!   * `defmt` — route the supervisor's logs through `defmt`; without it the log
166//!     macros are no-ops.
167//!   * `trace` family (all opt-in) — `trace`: the `trace` module's recorders consuming
168//!     embassy-executor's `_embassy_trace_*` hooks; `trace-hooks`:
169//!     `supervisor_graph!` also *defines* the hook symbols; `metadata-names`: node
170//!     names stamped into task Metadata for external consumers (rtos-trace/
171//!     SystemView) — independent of `trace`, so it needs no hook symbols and pairs
172//!     with embassy's own `rtos-trace`; `trace-names`: shorthand for `trace` +
173//!     `metadata-names`; `trace-nested`: preemption-exact accounting (a nested
174//!     higher-tier poll credits its time back to the window it interrupted).
175//!
176//! Build with `default-features = false` for a minimal core that only does
177//! dependency-ordered bring-up/teardown (drops the control plane and pools,
178//! trimming flash and a couple of statics).
179//!
180//! ## Example
181//!
182//! [`supervisor_graph!`] declares the whole graph once — it generates the node
183//! `static`s and a single [`Graph`] value `GRAPH` bundling the node slots, dep
184//! table, and compile-time topological order (a dependency cycle is a compile
185//! error), which [`Supervisor::new`] consumes.
186//!
187//! ```ignore
188//! use embassy_executor::Spawner;
189//! use embassy_supervisor::{supervisor_graph, RunError, Supervisor, TaskNode};
190//!
191//! // `app` depends on `net`; `task:` names a plain async worker fn the macro wraps
192//! // in its `#[embassy_executor::task]` shell (`spawn:` takes one you wrote yourself).
193//! supervisor_graph! {
194//!     node NET = Terminate, deps: [], task: net_task;
195//!     node APP = Terminate, deps: [NET], task: app_task;
196//! }
197//!
198//! // Plain async fns taking the node first — no embassy attribute needed. The
199//! // combinator owns the shutdown `select` and the ack.
200//! async fn net_task(node: &'static TaskNode) {
201//!     let _ = node.run_cancellable_acked(async { /* serve forever */ }).await;
202//! }
203//! async fn app_task(node: &'static TaskNode) {
204//!     let _ = node.run_cancellable_acked(async { /* serve forever */ }).await;
205//! }
206//!
207//! #[embassy_executor::task]
208//! async fn supervisor_task(spawner: Spawner) {
209//!     // Infallible: the order is precomputed, so a dependency cycle is a compile error.
210//!     let sup = Supervisor::new(&GRAPH);
211//!     // Brings up `net`, then `app`, then drives pool scaling and runtime control
212//!     // requests (start/stop/pause/resume, applied in dependency order) forever;
213//!     // returns only on error, which the application escalates — typically a panic
214//!     // into a hardware-watchdog reset.
215//!     match sup.run(spawner).await {
216//!         RunError::Spawn(_) => panic!("bring-up failed"),
217//!         RunError::Shutdown(e) => panic!("{} missed its shutdown ack", e.node.name),
218//!     }
219//!     // Call the pieces yourself (`start`, then a `select(run_pools, wait_control)`
220//!     // loop) when the driver must watch extra wake sources.
221//! }
222//! ```
223//!
224//! The `firmware` crate in the [repository](https://github.com/cedrivard/embassy-supervisor)
225//! is a complete working example (USB-net, an HTTP control plane, an elastic pool,
226//! and OTA).
227
228#[macro_use]
229mod fmt;
230
231use core::cell::Cell;
232use core::future::Future;
233use core::sync::atomic::Ordering;
234
235use embassy_executor::{SendSpawner, SpawnError, Spawner};
236use embassy_futures::select::{Either, select};
237use embassy_sync::blocking_mutex::Mutex as BlockingMutex;
238use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
239#[cfg(feature = "control")]
240use embassy_sync::channel::Channel;
241use embassy_sync::signal::Signal;
242use embassy_time::{Timer, with_timeout};
243use portable_atomic::AtomicBool;
244#[cfg(any(feature = "trace", feature = "liveness"))]
245use portable_atomic::AtomicU32;
246
247// ─── Scale-request signal (task → supervisor) ──────────────────────────────
248//
249// Elastic pool workers fire this when their busy/idle status changes; the
250// supervisor's `run_pools` loop awaits it and re-runs the pool policies
251// (`ElasticPool`). Single-consumer `Signal`: many tasks may `signal()`, only the
252// supervisor `wait()`s. This is the *only* path by which task status reaches the
253// supervisor — it never polls.
254#[cfg(feature = "pool")]
255static SCALE_REQ: Signal<CriticalSectionRawMutex, ()> = Signal::new();
256
257/// Fire the scale-request signal. Called by a task on a busy/idle transition.
258/// A no-op when the `pool` feature is disabled (no pools to re-evaluate).
259pub fn request_scale() {
260    #[cfg(feature = "pool")]
261    SCALE_REQ.signal(());
262}
263
264/// Await the next scale request. The supervisor's driver loop selects this
265/// against its other wake sources and runs the scaling policy on each wake.
266#[cfg(feature = "pool")]
267pub async fn wait_scale() {
268    SCALE_REQ.wait().await;
269}
270
271// ─── Runtime control commands (app → supervisor) ───────────────────────────
272//
273// An application's control surface (e.g. a network endpoint) usually can't drive
274// the supervisor directly: the `Supervisor` and the `Spawner` live on the
275// supervisor task's stack, not in a `static`. So control is decoupled via this
276// channel — the caller `request_control()`s a (node, op) pair; the supervisor's
277// driver loop `wait_control()`s it and runs the dependency-honoring
278// `apply_control`. A `Channel` (not a `Signal`) so back-to-back requests aren't
279// coalesced; capacity 4 is ample for hand-driven control. Delivery is lossless:
280// `request_control` awaits free capacity, and the sync `try_request_control`
281// surfaces a full mailbox as an error instead of dropping the request — a
282// silently vanished emergency stop is the one failure mode this mailbox is not
283// allowed to have.
284
285/// Which way to drive a node. Higher-level verbs fold onto these two:
286/// `start`/`resume` → `Activate`, `stop`/`pause` → `Deactivate`. The concrete
287/// mechanism (respawn vs resume vs leave-to-pool) is then chosen per node `Mode`
288/// by the supervisor when it applies the command ([`Supervisor::apply_control`]).
289#[cfg(feature = "control")]
290#[derive(Clone, Copy, PartialEq, Eq, Debug)]
291pub enum ControlOp {
292    /// Bring the node up (start a stopped `Terminate` node, resume a `Pause` node).
293    Activate,
294    /// Take the node down (and its dependents, per the graph).
295    Deactivate,
296}
297
298/// A runtime control request: drive `node` (and, per the dependency graph and
299/// pool membership, the nodes it implies) in the `op` direction.
300#[cfg(feature = "control")]
301#[derive(Clone, Copy, Debug)]
302pub struct ControlCommand {
303    /// The node to drive.
304    pub node: &'static TaskNode,
305    /// The direction to drive it.
306    pub op: ControlOp,
307}
308
309/// App → supervisor control mailbox. `&'static TaskNode` is `Copy + Sync`, so
310/// the target rides the channel directly — no name lookup needed supervisor-side.
311#[cfg(feature = "control")]
312static CONTROL_REQ: Channel<CriticalSectionRawMutex, ControlCommand, 4> = Channel::new();
313
314/// The control mailbox was full (4 outstanding requests) and the request was
315/// not enqueued. Returned by [`try_request_control`]; retry after the
316/// supervisor's driver loop has drained a command, or use the awaiting
317/// [`request_control`] from async contexts.
318#[cfg(feature = "control")]
319#[derive(Clone, Copy, PartialEq, Eq, Debug)]
320pub struct ControlQueueFull;
321
322#[cfg(all(feature = "control", feature = "defmt"))]
323impl defmt::Format for ControlQueueFull {
324    fn format(&self, fmt: defmt::Formatter) {
325        defmt::write!(fmt, "control queue full");
326    }
327}
328
329/// Enqueue a control request, waiting for mailbox capacity if it is full.
330/// Lossless — the request is delivered once the supervisor's driver loop drains
331/// an earlier command. Called by the application's control surface.
332#[cfg(feature = "control")]
333pub async fn request_control(node: &'static TaskNode, op: ControlOp) {
334    CONTROL_REQ.send(ControlCommand { node, op }).await;
335}
336
337/// Non-blocking variant of [`request_control`] for sync contexts (ISRs,
338/// callbacks). Fails with [`ControlQueueFull`] instead of dropping the request
339/// when the mailbox is full — the caller decides whether to retry or surface it.
340#[cfg(feature = "control")]
341pub fn try_request_control(node: &'static TaskNode, op: ControlOp) -> Result<(), ControlQueueFull> {
342    CONTROL_REQ
343        .try_send(ControlCommand { node, op })
344        .map_err(|_| ControlQueueFull)
345}
346
347/// Await the next control request. Selected by the supervisor's driver loop
348/// against pool scaling and any other application wake sources.
349#[cfg(feature = "control")]
350pub async fn wait_control() -> ControlCommand {
351    CONTROL_REQ.receive().await
352}
353
354/// Per-node timeout for `wait_dropped`. A task that doesn't ack within this
355/// window is a bug (e.g. a missing `ack_dropped()` call) or a wedge; the
356/// shutdown paths surface it as a [`ShutdownTimeout`] naming the node, and the
357/// application decides the escalation. 2 s comfortably exceeds a typical task's
358/// poll period and peripheral settle time.
359const SHUTDOWN_ACK_TIMEOUT_MS: u64 = 2_000;
360
361/// A node failed to ack a requested shutdown within `SHUTDOWN_ACK_TIMEOUT_MS`.
362/// Returned by [`Supervisor::stop_node`], [`Supervisor::teardown`],
363/// [`Supervisor::teardown_continue`] and (feature `control`)
364/// [`Supervisor::apply_control`]. The node is still marked running; the sane
365/// escalations are app-level — a hardware watchdog reset, `panic!`, or a retry.
366#[derive(Clone, Copy, Debug)]
367pub struct ShutdownTimeout {
368    /// The node that missed its ack window.
369    pub node: &'static TaskNode,
370}
371
372#[cfg(feature = "defmt")]
373impl defmt::Format for ShutdownTimeout {
374    fn format(&self, fmt: defmt::Formatter) {
375        defmt::write!(fmt, "{} missed shutdown ack", self.node.name);
376    }
377}
378
379/// Why [`Supervisor::run`] stopped — it only returns on error, and every arm is
380/// an app-level escalation (typically `panic!` into a hardware-watchdog reset).
381#[cfg(any(feature = "pool", feature = "control"))]
382#[derive(Clone, Copy, Debug)]
383pub enum RunError {
384    /// Bring-up failed: a spawn error out of the initial [`Supervisor::start`]
385    /// (task-pool exhaustion, or a gate/slot wait that timed out as `Busy`).
386    Spawn(SpawnError),
387    /// A node missed its shutdown ack during a control cascade or pool shrink.
388    Shutdown(ShutdownTimeout),
389}
390
391#[cfg(all(any(feature = "pool", feature = "control"), feature = "defmt"))]
392impl defmt::Format for RunError {
393    fn format(&self, fmt: defmt::Formatter) {
394        match self {
395            RunError::Spawn(_) => defmt::write!(fmt, "bring-up spawn failed"),
396            RunError::Shutdown(e) => defmt::write!(fmt, "{}", e),
397        }
398    }
399}
400
401/// The shutdown side of [`TaskNode::run_cancellable`]'s result: the raced work
402/// future was cancelled at its await point because a stop/pause request won the
403/// select. Pairs naturally with the `exit:` slot — a worker returning
404/// `Result<R, Aborted>` records completed-vs-cancelled for whoever reads the
405/// exit value.
406#[derive(Clone, Copy, PartialEq, Eq, Debug)]
407pub struct Aborted;
408
409#[cfg(feature = "defmt")]
410impl defmt::Format for Aborted {
411    fn format(&self, fmt: defmt::Formatter) {
412        defmt::write!(fmt, "aborted by shutdown");
413    }
414}
415
416/// How long the supervisor's bring-up waits for a node's `executor:`
417/// [`SpawnerSlot`] to be filled before failing the spawn with
418/// [`SpawnError::Busy`]. A genuine cross-core rendezvous resolves in microseconds;
419/// a slot empty this long is a misconfiguration (the app never registered that
420/// executor's spawner). Bounded, so a misconfigured graph fails loudly instead of
421/// hanging bring-up forever.
422const SLOT_READY_TIMEOUT: embassy_time::Duration = embassy_time::Duration::from_millis(100);
423
424// ─── Mode ────────────────────────────────────────────────────────────────
425
426/// Lifecycle policy for a managed task: what the task does on shutdown and what
427/// the supervisor does to bring it back.
428#[derive(Clone, Copy, PartialEq, Eq, Debug)]
429pub enum Mode {
430    /// Task exits its loop on shutdown. The supervisor respawns it via the
431    /// node's `spawn` fn from `respawn_terminate`.
432    Terminate,
433    /// Task acks shutdown and parks on `wait_resume()`. The supervisor resumes
434    /// it from `resume_pausable`; the task is never respawned, so it keeps any
435    /// resource it holds (a peripheral handle, a socket) across the pause.
436    Pause,
437    /// Like `Terminate` (exits on shutdown), but **not** started at boot and
438    /// **not** auto-respawned. The supervisor brings it up and down at runtime
439    /// via `start_node` / `stop_node` in response to load — see [`ElasticPool`].
440    /// `start()` skips it; `respawn_terminate()` leaves it down (it
441    /// re-grows under demand); `teardown()` only acts on it while it is running.
442    OnDemand,
443}
444
445impl Mode {
446    /// Stable lower-case wire name, used both for serialization (e.g. a JSON
447    /// task-state view) and for `defmt` logging — the single source of these
448    /// strings.
449    pub fn as_str(&self) -> &'static str {
450        match self {
451            Mode::Terminate => "terminate",
452            Mode::Pause => "pause",
453            Mode::OnDemand => "ondemand",
454        }
455    }
456}
457
458#[cfg(feature = "defmt")]
459impl defmt::Format for Mode {
460    fn format(&self, f: defmt::Formatter) {
461        defmt::write!(f, "{}", self.as_str());
462    }
463}
464
465// ─── TaskHandle ──────────────────────────────────────────────────────────
466
467/// Coordination state for one task. Embedded inside [`TaskNode`].
468///
469/// Every node is single-instance, so each field is a per-node atomic flag or a
470/// single-consumer signal — no counts, no fan-out. Written by one side (task or
471/// supervisor) and read by the other:
472///   * `shutdown` / `shutdown_wake` — supervisor requests exit; the task parks
473///     on the signal and reads the flag.
474///   * `dropped` / `dropped_wake` — the task acks its exit; the supervisor
475///     parks on the signal (with a timeout) and reads the flag.
476///   * `resume_wake` — supervisor resumes a parked Pause-mode task.
477///   * `running` — supervisor's record that the node is spawned; `busy` — the
478///     task's active/idle status. Both read by the elastic scaling policy.
479///   * `disabled` — the node has been manually deactivated; see below.
480pub struct TaskHandle {
481    /// Set true by the supervisor when shutdown is requested.
482    /// Cleared by `reset()` before the next spawn.
483    shutdown: AtomicBool,
484    /// Wake source for `wait_shutdown()`. Fired by `signal_shutdown()`.
485    shutdown_wake: Signal<CriticalSectionRawMutex, ()>,
486    /// Set true by the instance when it acks the shutdown (a bool, not a count,
487    /// since every node is single-instance). Cleared by `reset()`.
488    dropped: AtomicBool,
489    /// Wake source for `wait_dropped()`. Fired by `ack_dropped()`.
490    dropped_wake: Signal<CriticalSectionRawMutex, ()>,
491    /// True while the supervisor has the node spawned and it hasn't exited.
492    /// Always-on nodes are set true by `start()`; `OnDemand` nodes are set
493    /// true/false by `start_node()` / `stop_node()`. `teardown()` only acts on
494    /// `running` nodes, so a down `OnDemand` node doesn't stall it.
495    running: AtomicBool,
496    /// True while the task is actively serving (its active/idle status). Set by
497    /// `mark_busy()` / `mark_idle()`; read by the scaling policy.
498    busy: AtomicBool,
499    /// Set true by `mark_exited()` when the task body has returned — by the
500    /// generated `task:` shell automatically, or by a hand-written `spawn:` task
501    /// on its way out. Cleared by `reset()` before the next spawn. Together with
502    /// the lifecycle-spanning `shutdown` flag this distinguishes an autonomous
503    /// completion (`completed && !shutdown`) from an acked stop.
504    completed: AtomicBool,
505    /// Wake source for `wait_resume()` on Pause-mode tasks. Fired by
506    /// `signal_resume()`.
507    resume_wake: Signal<CriticalSectionRawMutex, ()>,
508    /// Task-asserted readiness ("initialized and serving", e.g. DHCP bound) —
509    /// distinct from `running` (spawned). Set by `set_ready()`, cleared by
510    /// `clear_ready()` and by `reset()` so a respawned provider re-asserts.
511    #[cfg(feature = "readiness")]
512    ready: AtomicBool,
513    /// Wake source for `wait_ready()`. Latching; the supervisor's bring-up is
514    /// the only pre-fill waiter (single-waiter Signal semantics).
515    #[cfg(feature = "readiness")]
516    ready_wake: Signal<CriticalSectionRawMutex, ()>,
517    /// Instant ticks (truncated) of the last `beat()`; also stamped by
518    /// `set_running(true)` so a freshly spawned node is never instantly stale.
519    #[cfg(feature = "liveness")]
520    last_beat: AtomicU32,
521    /// True while the node has been manually deactivated (stopped/paused) via the
522    /// runtime control interface (`Supervisor::deactivate`). Unlike the other
523    /// flags this one is **lifecycle-spanning**: it is *not* cleared by
524    /// `reset()`, so a manual stop "sticks" — the automatic bring-up paths
525    /// (`start`, `respawn_terminate`, `resume_pausable`, and the elastic pool's
526    /// grow) skip a node while it is set. Cleared only by `Supervisor::activate`.
527    /// Because it lives in a `static`, it also survives a power-state transition
528    /// that retains RAM (e.g. a warm-resume from deep sleep).
529    disabled: AtomicBool,
530    /// Self-managed: while set, the supervisor never drives this node — teardown,
531    /// deactivate/activate, `stop_node`, respawn, and pause-resume all skip it. Not
532    /// cleared by `reset()`. Full rationale on [`TaskNode::set_detached`].
533    detached: AtomicBool,
534    /// The executor task id currently running this node (`TaskRef::id()`, captured
535    /// from the `SpawnToken` by the macro's spawn glue). `0` = unknown (not yet
536    /// spawned, or a parked/closure-spawned node that never registered). Overwritten
537    /// on every (re)spawn, so — unlike an external tracker — it stays correct across
538    /// respawns without any unlinking.
539    #[cfg(feature = "trace")]
540    task_id: AtomicU32,
541    /// Accumulated executor-poll time for this node, in embassy-time ticks,
542    /// wrapping. Consumers sample twice and `wrapping_sub` to get a rate; the
543    /// crate does no windowing.
544    #[cfg(feature = "trace")]
545    exec_ticks: AtomicU32,
546    /// Number of executor polls of this node, wrapping.
547    #[cfg(feature = "trace")]
548    polls: AtomicU32,
549    /// Longest single poll ever observed, in ticks — the "never yields" watermark.
550    /// A large value names the node that hogged the executor even after the fact,
551    /// which a live check cannot do from the blocked executor itself.
552    #[cfg(feature = "trace")]
553    max_poll_ticks: AtomicU32,
554}
555
556impl TaskHandle {
557    const fn new(disabled_at_boot: bool) -> Self {
558        Self {
559            shutdown: AtomicBool::new(false),
560            shutdown_wake: Signal::new(),
561            dropped: AtomicBool::new(false),
562            dropped_wake: Signal::new(),
563            running: AtomicBool::new(false),
564            busy: AtomicBool::new(false),
565            completed: AtomicBool::new(false),
566            resume_wake: Signal::new(),
567            #[cfg(feature = "readiness")]
568            ready: AtomicBool::new(false),
569            #[cfg(feature = "readiness")]
570            ready_wake: Signal::new(),
571            #[cfg(feature = "liveness")]
572            last_beat: AtomicU32::new(0),
573            disabled: AtomicBool::new(disabled_at_boot),
574            detached: AtomicBool::new(false),
575            #[cfg(feature = "trace")]
576            task_id: AtomicU32::new(0),
577            #[cfg(feature = "trace")]
578            exec_ticks: AtomicU32::new(0),
579            #[cfg(feature = "trace")]
580            polls: AtomicU32::new(0),
581            #[cfg(feature = "trace")]
582            max_poll_ticks: AtomicU32::new(0),
583        }
584    }
585}
586
587// ─── Executor spawner slots ──────────────────────────────────────────────
588
589/// A runtime-filled slot holding the [`SendSpawner`] of an executor other than
590/// the one the supervisor runs on — an `InterruptExecutor` tier, the second
591/// core's executor, any foreign thread executor (via `Spawner::make_send()`).
592///
593/// Declared by the `executor NAME;` item of [`supervisor_graph!`]; nodes carrying
594/// `executor: NAME` are spawned through the slot instead of the supervisor's own
595/// `Spawner`. The application fills it once at startup — before, or concurrently
596/// with, [`Supervisor::start`] (e.g. from the second core's bring-up):
597///
598/// ```ignore
599/// static EXECUTOR_HIGH: InterruptExecutor = InterruptExecutor::new();
600/// HIGH.set(EXECUTOR_HIGH.start(interrupt::SWI_IRQ_0));
601/// sup.start(spawner).await?;   // nodes declared `executor: HIGH` spawn on that tier
602/// ```
603///
604/// The supervisor's bring-up (`start` / `start_node` / `respawn_terminate`) awaits
605/// [`ready`](Self::ready) for a node's slot before spawning it, so a tier filled
606/// late — or from another core — is handled without a race; a slot still empty after
607/// the supervisor's bounded wait fails the spawn with [`SpawnError::Busy`] rather
608/// than silently dropping the task. Spawned futures must be `Send` (a non-`Send`
609/// `executor:` task is a compile error at the glue).
610pub struct SpawnerSlot {
611    slot: BlockingMutex<CriticalSectionRawMutex, Cell<Option<SendSpawner>>>,
612    /// Wakes a `ready()` waiter when `set` fills the slot (cross-core safe:
613    /// `Signal` is critical-section based and latches).
614    filled: Signal<CriticalSectionRawMutex, ()>,
615}
616
617impl SpawnerSlot {
618    /// An empty slot (`const` — it lives in a `static` the macro emits).
619    pub const fn new() -> Self {
620        Self {
621            slot: BlockingMutex::new(Cell::new(None)),
622            filled: Signal::new(),
623        }
624    }
625
626    /// Fill the slot (last set wins) and wake a [`ready`](Self::ready) waiter.
627    /// Call before [`Supervisor::start`] — or from the other core's bring-up,
628    /// with the supervisor awaiting `ready()`.
629    pub fn set(&self, spawner: SendSpawner) {
630        self.slot.lock(|c| c.set(Some(spawner)));
631        self.filled.signal(());
632    }
633
634    /// The registered spawner, or `None` while unfilled.
635    pub fn get(&self) -> Option<SendSpawner> {
636        self.slot.lock(Cell::get)
637    }
638
639    /// Await the slot and return the spawner. The rendezvous primitive: the
640    /// supervisor's bring-up awaits this for a node's `executor:` slot before
641    /// spawning it (bounded, see [`Supervisor::start`]), so a tier filled late — or
642    /// from another core — is handled without a race. Returns immediately once the
643    /// slot is filled, so any number of *late* callers are fine (an application can
644    /// gate work on the executor being up). While the slot is still empty, at most
645    /// one task should be parked here: the underlying `Signal` holds a single waker,
646    /// so a second pre-fill waiter would displace the first.
647    pub async fn ready(&self) -> SendSpawner {
648        loop {
649            if let Some(sp) = self.get() {
650                return sp;
651            }
652            // `Signal` latches: a `set()` racing between the check above and
653            // this wait still wakes us.
654            self.filled.wait().await;
655        }
656    }
657}
658
659impl Default for SpawnerSlot {
660    fn default() -> Self {
661        Self::new()
662    }
663}
664
665// ─── ResourceSlot ────────────────────────────────────────────────────────
666
667/// Type-erased readiness view of a [`ResourceSlot`], for the supervisor's
668/// bring-up wait.
669///
670/// A `TaskNode` can gate on any number of slots of *different* `T`s, so the node
671/// stores `&'static [&'static dyn ResourceGate]` (object-safe: no `T` in the
672/// signatures). Same shape as embassy's `dyn` driver registries — see
673/// <https://doc.rust-lang.org/reference/items/traits.html#object-safety>.
674/// The supervisor only needs "is it filled?" plus the signal to park on; taking
675/// the value stays in the generated spawn glue, where the concrete `T` is known.
676pub trait ResourceGate: Sync {
677    /// Non-consuming "is the slot currently filled" check.
678    fn is_filled(&self) -> bool;
679    /// The latching [`Signal`] fired by `provide`/`restore`, for the supervisor's
680    /// bounded pre-spawn wait (see [`Supervisor::start`]).
681    fn filled_signal(&self) -> &Signal<CriticalSectionRawMutex, ()>;
682}
683
684/// A one-value handoff cell threading an owned resource from `main` into a
685/// supervised task — the safe replacement for `Peripherals::steal()` inside
686/// the task body.
687///
688/// Declared (as a `pub static`) by [`supervisor_graph!`] for each entry in a
689/// node's `resources:` clause. The protocol:
690///
691/// 1. `main` splits `Peripherals` and **moves** the resource in with
692///    [`provide`](Self::provide). This is where the compile-time guarantee
693///    lives: the singleton field is *consumed*, so no second owner — and no
694///    `unsafe` steal — can exist.
695/// 2. The generated spawn glue [`take`](Self::take)s it just before spawning
696///    the node. An empty slot fails the spawn with `SpawnError::Busy` — a
697///    fail-closed error out of [`Supervisor::start`], not a panic inside the
698///    task (compare `static_cell::StaticCell`, which panics on misuse).
699/// 3. The generated task shell hands the worker `&mut T` and
700///    [`restore`](Self::restore)s the value after the worker returns, so a
701///    `Terminate` respawn re-takes the *same instance* instead of stealing a
702///    fresh one. (A `Pause` worker never returns — it parks — so it simply
703///    retains the resource, exactly like a hand-written parked task.)
704///
705/// Same primitives as [`SpawnerSlot`]: a critical-section
706/// [`BlockingMutex`]`<`[`Cell`]`<Option<T>>>` for the value (`Sync` for
707/// `T: Send`, provided by embassy-sync — no `unsafe` here) plus a latching
708/// [`Signal`] so the supervisor can await late provisioning (bounded; see
709/// [`Supervisor::start`]).
710pub struct ResourceSlot<T> {
711    slot: BlockingMutex<CriticalSectionRawMutex, Cell<Option<T>>>,
712    /// Wakes the supervisor's pre-spawn wait when `provide`/`restore` fills the
713    /// slot (latching, so a fill racing the check-then-wait still wakes it).
714    filled: Signal<CriticalSectionRawMutex, ()>,
715}
716
717impl<T> ResourceSlot<T> {
718    /// An empty slot (`const` — it lives in a `static` the macro emits).
719    pub const fn new() -> Self {
720        Self {
721            slot: BlockingMutex::new(Cell::new(None)),
722            filled: Signal::new(),
723        }
724    }
725
726    /// Move the resource in (from `main`'s `Peripherals` split) and wake the
727    /// supervisor's pre-spawn wait. Call before [`Supervisor::start`]; a slot
728    /// still empty after the supervisor's bounded wait fails that node's spawn
729    /// with `SpawnError::Busy`. Filling an occupied slot replaces (drops) the
730    /// old value — don't: one resource, one slot, moved exactly once.
731    pub fn provide(&self, value: T) {
732        self.slot.lock(|c| c.set(Some(value)));
733        self.filled.signal(());
734    }
735
736    /// Take the resource out, leaving the slot empty. Called by the generated
737    /// spawn glue just before the spawn; `None` means "not provided yet" or
738    /// "currently held by a live task instance".
739    pub fn take(&self) -> Option<T> {
740        self.slot.lock(Cell::take)
741    }
742
743    /// Copy the resource out **without emptying the slot** — the `shared`
744    /// resource kind's read: any number of consumers (several nodes, a whole
745    /// pool) get the same `Copy` handle, and the slot stays filled for the
746    /// next one. Only for `T: Copy` (a `Stack`-like handle, a `&'static`
747    /// registry ref); an owned singleton uses [`take`](Self::take).
748    pub fn get(&self) -> Option<T>
749    where
750        T: Copy,
751    {
752        // Same peek shape as `is_filled`: `Cell` has no `&T` access, so
753        // take-copy-put-back under one critical section.
754        self.slot.lock(|c| {
755            let v = c.take();
756            c.set(v);
757            v
758        })
759    }
760
761    /// Put the resource back for the next spawn. Called by the generated task
762    /// shell after the worker returns (i.e. after its clean shutdown ack), so a
763    /// respawn re-takes the same instance.
764    pub fn restore(&self, value: T) {
765        self.provide(value);
766    }
767
768    /// Await the slot being filled, then take the value — how an application
769    /// reads a node's `exit:` slot (the shell `provide()`s the worker's return
770    /// value there just before recording the exit). Check-then-park, so a value
771    /// provided earlier is returned immediately; the latching signal carries
772    /// the same single-pre-fill-waiter caveat as [`SpawnerSlot::ready`] — for
773    /// N concurrent readers fan out through an app-owned `Watch` instead.
774    pub async fn wait_take(&self) -> T {
775        loop {
776            if let Some(v) = self.take() {
777                return v;
778            }
779            self.filled.wait().await;
780        }
781    }
782}
783
784// `T: Send` (not just any `T`): the gate is reachable from the supervisor task,
785// which may run on a different core than the provider — the same bound the
786// inner `BlockingMutex` requires for `Sync`, restated here so the `dyn` upcast
787// can't outrun it.
788impl<T: Send> ResourceGate for ResourceSlot<T> {
789    fn is_filled(&self) -> bool {
790        // Peek without consuming: `Cell` has no `&T` access (no `T: Copy`
791        // here), so take-and-put-back under the same critical section.
792        self.slot.lock(|c| {
793            let v = c.take();
794            let filled = v.is_some();
795            c.set(v);
796            filled
797        })
798    }
799
800    fn filled_signal(&self) -> &Signal<CriticalSectionRawMutex, ()> {
801        &self.filled
802    }
803}
804
805impl<T> Default for ResourceSlot<T> {
806    fn default() -> Self {
807        Self::new()
808    }
809}
810
811// ─── TaskNode ────────────────────────────────────────────────────────────
812
813/// A node in the supervisor's task graph.
814///
815/// Designed to live in `static` memory: every field is `Sync`, all constructors
816/// are `const`. Declared by [`supervisor_graph!`], which emits one per managed
817/// task along with the [`Graph`] (`GRAPH`) that [`Supervisor::new`] consumes.
818pub struct TaskNode {
819    /// Human-readable name. Used in defmt logs and panic messages.
820    pub name: &'static str,
821    /// Lifecycle policy. See [`Mode`].
822    pub mode: Mode,
823    /// App-provided spawn function (typically an inline closure at the node's
824    /// declaration). Called once at boot from `Supervisor::start`, again from
825    /// `respawn_terminate` for Terminate nodes, and at runtime from `start_node`
826    /// for `OnDemand` nodes. `None` for a **parked** node the application spawns
827    /// itself (e.g. a `Pause` sensor holding a peripheral handle): the supervisor
828    /// tracks its lifecycle but never spawns it.
829    pub spawn: Option<fn(Spawner) -> Result<(), SpawnError>>,
830    /// The executor [`SpawnerSlot`] this node spawns through (`executor: NAME` in
831    /// the graph), or `None` to spawn on the supervisor's own `Spawner`. When
832    /// `Some`, the supervisor awaits the slot's [`ready`](SpawnerSlot::ready)
833    /// (bounded by [`SLOT_READY_TIMEOUT`]) *before* invoking `spawn`, so the
834    /// generated glue's own non-blocking `SpawnerSlot::get` is already filled. Set
835    /// by the macro via [`with_executor`](Self::with_executor); `const`, zero-cost.
836    spawn_slot: Option<&'static SpawnerSlot>,
837    /// The [`ResourceSlot`]s this node's spawn takes from (`resources:` in the
838    /// graph), type-erased to their [`ResourceGate`] readiness view. The
839    /// supervisor awaits every gate being filled (bounded by
840    /// [`SLOT_READY_TIMEOUT`]) *before* invoking `spawn`, so (a) a `main` that
841    /// provides late is tolerated and (b) a respawn cannot race the previous
842    /// instance's shell restoring the value (the restore happens after the
843    /// worker's shutdown ack). Empty for nodes without `resources:`. Set by the
844    /// macro via [`with_resources`](Self::with_resources); `const`, zero-cost.
845    resource_gates: &'static [&'static dyn ResourceGate],
846    /// Deps whose task-asserted readiness (`set_ready`) bring-up awaits before
847    /// spawning this node — the `ready`-marked subset of `deps:`. Spawn-order
848    /// deps stay in the graph's dep table; this is the readiness overlay.
849    #[cfg(feature = "readiness")]
850    ready_deps: &'static [&'static TaskNode],
851    /// Bound on the pre-spawn waits for this node's `executor:` slot and
852    /// `resources:` gates. Defaults to [`SLOT_READY_TIMEOUT`] (100 ms — sized
853    /// for "main provided before start"); raise it (`slot_timeout:` in the
854    /// graph) for a node whose slots are filled by a **provider node** at
855    /// runtime — e.g. an async radio bring-up worth hundreds of milliseconds.
856    /// Set by the macro via [`with_slot_timeout`](Self::with_slot_timeout).
857    slot_timeout: embassy_time::Duration,
858    handle: TaskHandle,
859}
860
861impl TaskNode {
862    /// A single-instance node started at boot (`Terminate`/`Pause`) or on demand
863    /// (`Mode::OnDemand`). Every node is single-instance; an elastic service is
864    /// modelled as several `OnDemand` nodes of the same pooled task fn.
865    ///
866    /// A `TaskNode` carries only its own identity and behaviour; the graph's
867    /// dependency edges live in the compile-time index table that
868    /// [`supervisor_graph!`] emits and [`Supervisor::new`] consumes.
869    /// `disabled_at_boot` seeds the node's disabled flag so a control-started node
870    /// (e.g. an OTA task) can be declared down and started later via a control op.
871    /// `spawn` is `None` for a parked node the application spawns itself.
872    pub const fn new(
873        name: &'static str,
874        mode: Mode,
875        spawn: Option<fn(Spawner) -> Result<(), SpawnError>>,
876        disabled_at_boot: bool,
877    ) -> Self {
878        Self {
879            name,
880            mode,
881            spawn,
882            spawn_slot: None,
883            resource_gates: &[],
884            #[cfg(feature = "readiness")]
885            ready_deps: &[],
886            slot_timeout: SLOT_READY_TIMEOUT,
887            handle: TaskHandle::new(disabled_at_boot),
888        }
889    }
890
891    /// Route this node's spawn through the given executor [`SpawnerSlot`] (the
892    /// `executor: NAME` graph annotation). The supervisor awaits the slot before
893    /// spawning the node, so a tier filled late — or from another core — is handled
894    /// without a race, and the generated glue's non-blocking `get` is already filled.
895    /// `const` and chainable in a `static` initializer; emitted by [`supervisor_graph!`].
896    pub const fn with_executor(mut self, slot: &'static SpawnerSlot) -> Self {
897        self.spawn_slot = Some(slot);
898        self
899    }
900
901    /// Declare the [`ResourceSlot`]s this node's spawn takes from (the
902    /// `resources:` graph clause). The supervisor awaits every gate being
903    /// filled before spawning the node, so the generated glue's non-blocking
904    /// `take()` finds the value. `const` and chainable in a `static`
905    /// initializer; emitted by [`supervisor_graph!`].
906    pub const fn with_resources(mut self, gates: &'static [&'static dyn ResourceGate]) -> Self {
907        self.resource_gates = gates;
908        self
909    }
910
911    /// Declare the deps whose task-asserted readiness bring-up awaits before
912    /// spawning this node (the `ready`-marked subset of `deps:`). `const` and
913    /// chainable in a `static` initializer; emitted by [`supervisor_graph!`].
914    #[cfg(feature = "readiness")]
915    pub const fn with_ready_deps(mut self, deps: &'static [&'static TaskNode]) -> Self {
916        self.ready_deps = deps;
917        self
918    }
919
920    /// Override the pre-spawn slot/gate wait bound for this node (the
921    /// `slot_timeout: <millis>` graph clause). The default
922    /// (`SLOT_READY_TIMEOUT`, 100 ms) assumes slots are provided *before*
923    /// `start()`; a node consuming a **provider node's** outputs must cover the
924    /// provider's async build time (the failure mode stays a loud
925    /// `SpawnError::Busy`, just later). `const` and chainable in a `static`
926    /// initializer; emitted by [`supervisor_graph!`].
927    pub const fn with_slot_timeout(mut self, timeout: embassy_time::Duration) -> Self {
928        self.slot_timeout = timeout;
929        self
930    }
931
932    // ── Task-side API ────────────────────────────────────────────────────
933    //
934    // Called from inside the `#[embassy_executor::task] async fn` body. The
935    // whole task-side protocol is four rules (the README's "Writing supervised
936    // tasks" section has per-mode skeletons):
937    //   1. select long-lived work against `wait_shutdown()`;
938    //   2. `ack_dropped()` exactly once per stop — on exit (Terminate/OnDemand)
939    //      or on each pause (Pause), before parking on `wait_resume()`;
940    //   3. an autonomous exit calls `mark_exited()` (acks + records completion;
941    //      `task:` shells do it automatically);
942    //   4. resources follow the mode: Terminate re-acquires on respawn, Pause
943    //      retains across park.
944
945    /// True iff the supervisor has requested shutdown. Checked at the loop top
946    /// alongside `wait_shutdown()` in a `select`.
947    pub fn shutdown_requested(&self) -> bool {
948        self.handle.shutdown.load(Ordering::Acquire)
949    }
950
951    /// Park until shutdown is requested. Returns immediately if shutdown has
952    /// already been requested. Use this for single-instance tasks in a `select`
953    /// against the task's main work future.
954    pub async fn wait_shutdown(&self) {
955        // Fast path — already requested. (Important because the signal is
956        // edge-triggered: if `signal()` fired before we got here, the bare
957        // `wait()` below would block forever.)
958        if self.handle.shutdown.load(Ordering::Acquire) {
959            return;
960        }
961        self.handle.shutdown_wake.wait().await;
962    }
963
964    /// Mark this instance as having shut down: clears the running flag and acks
965    /// the teardown handshake (so the supervisor's `wait_dropped` completes).
966    /// Every instance must call this exactly once on exit (Terminate/OnDemand
967    /// mode) or on each pause (Pause mode). It also covers an **autonomous** exit
968    /// the supervisor didn't request — e.g. a pool worker backing off — so the
969    /// pool sees the instance as down and can re-grow it under later demand.
970    pub fn ack_dropped(&self) {
971        self.handle.running.store(false, Ordering::Release);
972        self.handle.dropped.store(true, Ordering::Release);
973        self.handle.dropped_wake.signal(());
974    }
975
976    /// Record that this node's task body has **returned**. Called automatically
977    /// by the generated `task:` shell after the worker returns (and after
978    /// resource restores); call it manually at the end of a hand-written
979    /// `spawn:` task that can exit, where you would previously have called
980    /// [`ack_dropped`](Self::ack_dropped) alone. Idempotent, and subsumes
981    /// `ack_dropped`: it acks the teardown handshake *and* records completion,
982    /// so a body that returns on its own — the case the supervisor previously
983    /// could not observe — reads as down ([`is_running`](Self::is_running) →
984    /// `false`, [`has_exited`](Self::has_exited) → `true`) instead of running
985    /// forever, and a control `Activate` can respawn it.
986    pub fn mark_exited(&self) {
987        self.handle.completed.store(true, Ordering::Release);
988        self.ack_dropped();
989    }
990
991    /// True once the last instance's body returned — set by
992    /// [`mark_exited`](Self::mark_exited), cleared by the pre-spawn reset.
993    /// `has_exited() && !shutdown_requested()` distinguishes an autonomous
994    /// completion from an acked stop (the shutdown flag persists until the next
995    /// reset).
996    pub fn has_exited(&self) -> bool {
997        self.handle.completed.load(Ordering::Acquire)
998    }
999
1000    /// Assert readiness: "initialized and serving" (DHCP bound, registration
1001    /// done, calibration finished) — the task-side half of a `ready`-marked
1002    /// dependency edge. Distinct from *running* (spawned): `deps:` orders
1003    /// spawns; a `deps: [THIS ready]` edge additionally awaits this call.
1004    /// Latching until [`clear_ready`](Self::clear_ready) or the pre-spawn
1005    /// reset (a respawned provider re-asserts).
1006    #[cfg(feature = "readiness")]
1007    pub fn set_ready(&self) {
1008        self.handle.ready.store(true, Ordering::Release);
1009        self.handle.ready_wake.signal(());
1010    }
1011
1012    /// Withdraw readiness — **status, not control**: dependents are NOT stopped
1013    /// or notified (pair with a control `Deactivate` for a cascade); it defers
1014    /// future bring-up (a ready-marked dependent's spawn, pool growth) until
1015    /// [`set_ready`](Self::set_ready) again. Use for "link lost, still
1016    /// reconnecting" style states.
1017    #[cfg(feature = "readiness")]
1018    pub fn clear_ready(&self) {
1019        self.handle.ready.store(false, Ordering::Release);
1020    }
1021
1022    /// True while the node asserts readiness. Pool growth checks this for
1023    /// `ready`-marked deps; also useful in app health views.
1024    #[cfg(feature = "readiness")]
1025    pub fn is_ready(&self) -> bool {
1026        self.handle.ready.load(Ordering::Acquire)
1027    }
1028
1029    /// Park until this node asserts readiness (immediately if it already has).
1030    /// The supervisor's bring-up is the intended pre-fill waiter; the latching
1031    /// signal has the same single-pre-fill-waiter caveat as
1032    /// [`SpawnerSlot::ready`] — for N concurrent app-side waiters fan out
1033    /// through an app-owned `embassy_sync::watch::Watch` fed by the ready task.
1034    #[cfg(feature = "readiness")]
1035    pub async fn wait_ready(&self) {
1036        loop {
1037            if self.is_ready() {
1038                return;
1039            }
1040            self.handle.ready_wake.wait().await;
1041        }
1042    }
1043
1044    /// True when every `ready`-marked dep currently asserts readiness — the
1045    /// sync form pool growth uses (no wait: a not-ready dep just defers the
1046    /// grow to the next evaluation).
1047    #[cfg(all(feature = "pool", feature = "readiness"))]
1048    pub(crate) fn ready_deps_ok(&self) -> bool {
1049        self.ready_deps.iter().all(|d| d.is_ready())
1050    }
1051    #[cfg(all(feature = "pool", not(feature = "readiness")))]
1052    pub(crate) fn ready_deps_ok(&self) -> bool {
1053        true
1054    }
1055
1056    /// Record a liveness heartbeat. Call once per work loop (or per served
1057    /// request); an app watchdog task reads [`is_stale`](Self::is_stale).
1058    #[cfg(feature = "liveness")]
1059    pub fn beat(&self) {
1060        self.handle.last_beat.store(
1061            embassy_time::Instant::now().as_ticks() as u32,
1062            Ordering::Release,
1063        );
1064    }
1065
1066    /// Ticks since the last [`beat`](Self::beat) (wrapping arithmetic; correct
1067    /// for gaps under the u32 tick wrap, ~71 min at 1 MHz — far above any sane
1068    /// `max_age`).
1069    #[cfg(feature = "liveness")]
1070    pub fn ticks_since_beat(&self) -> u32 {
1071        (embassy_time::Instant::now().as_ticks() as u32)
1072            .wrapping_sub(self.handle.last_beat.load(Ordering::Acquire))
1073    }
1074
1075    /// True when the node is running but hasn't beaten within `max_age` — the
1076    /// alive-but-wedged detector (a task hogging nothing, parked on an await
1077    /// that will never complete). Not-running nodes are never stale: a stopped
1078    /// or completed node is *down*, which `is_running`/`has_exited` already
1079    /// report. Complements the `trace` stall watermark, which catches the
1080    /// opposite failure (a poll that never yields).
1081    #[cfg(feature = "liveness")]
1082    pub fn is_stale(&self, max_age: embassy_time::Duration) -> bool {
1083        self.is_running() && u64::from(self.ticks_since_beat()) > max_age.as_ticks()
1084    }
1085
1086    /// Pause-mode only: park until the supervisor signals resume. Call *after*
1087    /// [`ack_dropped`](Self::ack_dropped) — ack the pause, then park; held
1088    /// resources stay owned across the park.
1089    pub async fn wait_resume(&self) {
1090        self.handle.resume_wake.wait().await;
1091    }
1092
1093    /// Race `fut` against this node's shutdown: `Ok(output)` when the work
1094    /// completes, `Err(Aborted)` when a stop/pause request wins. Owns the
1095    /// `select` that rule 1 of the task protocol otherwise has you write by
1096    /// hand. Does **not** ack — run your cleanup, then call
1097    /// [`ack_dropped`](Self::ack_dropped) (or return through
1098    /// [`run_cancellable_acked`](Self::run_cancellable_acked) when there is no
1099    /// cleanup between the select and the ack).
1100    ///
1101    /// ```ignore
1102    /// match node.run_cancellable(conn.serve()).await {
1103    ///     Ok(done) => handle(done),
1104    ///     Err(Aborted) => { flush().await; node.ack_dropped(); return; }
1105    /// }
1106    /// ```
1107    pub async fn run_cancellable<F: Future>(&self, fut: F) -> Result<F::Output, Aborted> {
1108        match select(fut, self.wait_shutdown()).await {
1109            Either::First(out) => Ok(out),
1110            Either::Second(()) => Err(Aborted),
1111        }
1112    }
1113
1114    /// [`run_cancellable`](Self::run_cancellable) that additionally calls
1115    /// [`ack_dropped`](Self::ack_dropped) before returning `Err(Aborted)` — for
1116    /// bodies with no teardown work between the select and the ack, e.g. a
1117    /// runner whose drop *is* the cleanup:
1118    ///
1119    /// ```ignore
1120    /// let _ = node.run_cancellable_acked(runner.run()).await; // drop releases the pins
1121    /// ```
1122    pub async fn run_cancellable_acked<F: Future>(&self, fut: F) -> Result<F::Output, Aborted> {
1123        let out = self.run_cancellable(fut).await;
1124        if out.is_err() {
1125            self.ack_dropped();
1126        }
1127        out
1128    }
1129
1130    /// Report that this task started serving a request (active). Fires the
1131    /// scale-request signal on a real idle→busy transition so the scaling policy
1132    /// can react (e.g. grow the pool); a redundant call doesn't re-signal.
1133    pub fn mark_busy(&self) {
1134        if !self.handle.busy.swap(true, Ordering::Release) {
1135            request_scale();
1136        }
1137    }
1138
1139    /// Report that this task finished serving and is idle again. Fires the
1140    /// scale-request signal on a real busy→idle transition so the scaling policy
1141    /// can react (e.g. shrink the pool); a redundant call doesn't re-signal.
1142    pub fn mark_idle(&self) {
1143        if self.handle.busy.swap(false, Ordering::Release) {
1144            request_scale();
1145        }
1146    }
1147
1148    /// True while this task is actively serving. Read by the scaling policy.
1149    pub fn is_busy(&self) -> bool {
1150        self.handle.busy.load(Ordering::Acquire)
1151    }
1152
1153    /// True while the supervisor has this node spawned (and it hasn't exited).
1154    /// Read by the scaling policy to count live instances, and by a task-state
1155    /// view.
1156    pub fn is_running(&self) -> bool {
1157        self.handle.running.load(Ordering::Acquire)
1158    }
1159
1160    /// True while the node is disabled: declared `disabled` in the graph
1161    /// (stopped-at-boot, up on an explicit `Activate`), or manually deactivated
1162    /// via the control interface and not yet re-activated. Read by a task-state
1163    /// view and by the automatic bring-up paths (which skip a disabled node).
1164    pub fn is_disabled(&self) -> bool {
1165        self.handle.disabled.load(Ordering::Acquire)
1166    }
1167
1168    /// Mark/clear this node as **detached**: a self-managing node the supervisor
1169    /// brings up once (via [`start`](Supervisor::start)) and then stops managing
1170    /// **entirely**. Every runtime lifecycle operation skips a detached node: full
1171    /// [`teardown`](Supervisor::teardown), the control deactivate/activate cascades,
1172    /// [`stop_node`](Supervisor::stop_node), [`respawn_terminate`](Supervisor::respawn_terminate),
1173    /// and pause-resume. It keeps running (or, for a one-shot, stays exited) across a
1174    /// teardown/wake cycle instead of being stopped, re-enabled, or re-spawned. Use it
1175    /// for a task that must outlive the teardown it participates in — e.g. a sleep/power
1176    /// coordinator that tears the graph down, sleeps, then wakes it — or a self-managed
1177    /// one-shot whose `deps:` exist only for start-ordering. The node owns its own
1178    /// shutdown; the supervisor will not drive it.
1179    pub fn set_detached(&self, detached: bool) {
1180        self.handle.detached.store(detached, Ordering::Release);
1181    }
1182
1183    /// True while this node is [detached](Self::set_detached): self-managed, skipped by
1184    /// every runtime lifecycle operation (teardown, deactivate/activate, `stop_node`,
1185    /// respawn, pause-resume). Only the initial `start` brings it up.
1186    pub fn is_detached(&self) -> bool {
1187        self.handle.detached.load(Ordering::Acquire)
1188    }
1189
1190    // ── Trace/observability API (features `trace`/`trace-names`) ───────────
1191
1192    /// Record the executor task id (`SpawnToken::id()` / `TaskRef::id()`) currently
1193    /// backing this node, so the [`trace`] recorders can attribute executor polls to
1194    /// it. Called automatically by the spawn glue `supervisor_graph!` generates;
1195    /// call it manually only for a **parked** node (no `spawn:`) or a verbatim-closure
1196    /// `spawn:`, where the macro cannot see the token. Overwrites on every (re)spawn.
1197    #[cfg(feature = "trace")]
1198    pub fn set_task_id(&self, id: u32) {
1199        self.handle.task_id.store(id, Ordering::Release);
1200    }
1201
1202    /// Register an externally-spawned token as this node's live task: records
1203    /// the task id for the [`trace`] recorders and (feature `metadata-names`)
1204    /// stamps the node name into the task Metadata. One call replaces the
1205    /// manual [`set_task_id`](Self::set_task_id) dance wherever the macro can't
1206    /// see the token — parked nodes and verbatim-closure `spawn:` forms:
1207    ///
1208    /// ```ignore
1209    /// let t = environment_task(i2c_dev)?;
1210    /// BME280.adopt(&t);
1211    /// high_spawner.spawn(t);
1212    /// ```
1213    #[cfg(feature = "trace")]
1214    pub fn adopt<S>(&self, token: &embassy_executor::SpawnToken<S>) {
1215        self.set_task_id(token.id());
1216        #[cfg(feature = "metadata-names")]
1217        self.stamp_name(token);
1218    }
1219
1220    /// Stamp this node's name into the task's embassy `Metadata` (feature
1221    /// `metadata-names`), so external consumers — rtos-trace/SystemView, debuggers —
1222    /// show the graph node name instead of an opaque task id. Unlike
1223    /// [`adopt`](Self::adopt) this does **not** capture the task id or touch the
1224    /// supervisor's [`trace`] recorders, so it needs neither the `trace` feature nor
1225    /// the `_embassy_trace_*` hook symbols: it is the name-only spawn path emitted
1226    /// when `metadata-names` is on but `trace` is off (pair it with embassy's
1227    /// `rtos-trace`). Called automatically by the spawn glue; call it manually only
1228    /// for a parked or verbatim-closure node the macro can't see.
1229    ///
1230    /// Requires `embassy-executor`'s `metadata-name` feature, which `metadata-names`
1231    /// pulls in; without a registered name the task keeps embassy's default.
1232    #[cfg(feature = "metadata-names")]
1233    pub fn stamp_name<S>(&self, token: &embassy_executor::SpawnToken<S>) {
1234        token.metadata().set_name(self.name);
1235    }
1236
1237    /// The executor task id last recorded by [`set_task_id`](Self::set_task_id)
1238    /// (`0` = never spawned / not registered).
1239    #[cfg(feature = "trace")]
1240    pub fn task_id(&self) -> u32 {
1241        self.handle.task_id.load(Ordering::Acquire)
1242    }
1243
1244    /// Accumulated executor-poll time of this node, in embassy-time ticks. Wrapping:
1245    /// sample twice and `wrapping_sub` the readings to get a rate over a window.
1246    #[cfg(feature = "trace")]
1247    pub fn exec_ticks(&self) -> u32 {
1248        self.handle.exec_ticks.load(Ordering::Relaxed)
1249    }
1250
1251    /// Number of executor polls of this node (wrapping counter).
1252    #[cfg(feature = "trace")]
1253    pub fn poll_count(&self) -> u32 {
1254        self.handle.polls.load(Ordering::Relaxed)
1255    }
1256
1257    /// Longest single executor poll of this node ever observed, in ticks — the
1258    /// "never yields" watermark. A poll is expected to be microseconds; a large
1259    /// value names the node that hogged its executor, even after the fact.
1260    #[cfg(feature = "trace")]
1261    pub fn max_poll_ticks(&self) -> u32 {
1262        self.handle.max_poll_ticks.load(Ordering::Relaxed)
1263    }
1264
1265    // ── Supervisor-side API ──────────────────────────────────────────────
1266    //
1267    // Driven by the `Supervisor` struct. Kept `pub(crate)` so app code doesn't
1268    // accidentally bypass the supervisor's orchestration.
1269
1270    pub(crate) fn signal_shutdown(&self) {
1271        self.handle.shutdown.store(true, Ordering::Release);
1272        self.handle.shutdown_wake.signal(());
1273    }
1274
1275    pub(crate) fn signal_resume(&self) {
1276        self.handle.resume_wake.signal(());
1277    }
1278
1279    pub(crate) fn set_running(&self, running: bool) {
1280        self.handle.running.store(running, Ordering::Release);
1281        // Stamp a beat at spawn so a freshly running node is never instantly
1282        // stale (its body may not reach its first beat() for a while).
1283        #[cfg(feature = "liveness")]
1284        if running {
1285            self.handle.last_beat.store(
1286                embassy_time::Instant::now().as_ticks() as u32,
1287                Ordering::Release,
1288            );
1289        }
1290    }
1291
1292    /// Set/clear the manual-deactivation flag. Set by `Supervisor::deactivate`,
1293    /// cleared by `Supervisor::activate`. Deliberately *not* touched by
1294    /// `reset()`, so a manual stop survives respawn cycles and RAM-retaining
1295    /// power-state transitions.
1296    ///
1297    /// Public so an application can pre-disable a `Terminate` node *before*
1298    /// `Supervisor::start`, making it a stopped-at-boot task that only comes up on
1299    /// an explicit `Activate` control (a node started by control rather than at boot).
1300    pub fn set_disabled(&self, disabled: bool) {
1301        self.handle.disabled.store(disabled, Ordering::Release);
1302    }
1303
1304    /// Wait until the instance has called `ack_dropped()`. Single-instance, so
1305    /// one ack ends the wait. The fast-path flag check handles the ack landing
1306    /// before this await (the `dropped_wake` signal is edge-triggered).
1307    /// True when an instance acked a stop WITHOUT exiting — for a `Pause` node
1308    /// that is exactly "parked on `wait_resume()`" (the protocol acks, then
1309    /// parks; a full exit would have set `completed` via `mark_exited`).
1310    /// Readable only before the pre-spawn `reset()` clears both flags.
1311    pub(crate) fn has_acked_stop(&self) -> bool {
1312        self.handle.dropped.load(Ordering::Acquire)
1313            && !self.handle.completed.load(Ordering::Acquire)
1314    }
1315
1316    pub(crate) async fn wait_dropped(&self) {
1317        if self.handle.dropped.load(Ordering::Acquire) {
1318            return;
1319        }
1320        self.handle.dropped_wake.wait().await;
1321    }
1322
1323    /// Clear the shutdown flag, dropped flag, busy flag, completed flag, and the
1324    /// shutdown / dropped wake-signals so the next cycle starts clean. Doesn't
1325    /// touch `running` (managed around spawn/stop), `resume_wake`
1326    /// (`resume_pausable` fires that for Pause nodes), or `disabled`
1327    /// (lifecycle-spanning).
1328    pub(crate) fn reset(&self) {
1329        self.handle.shutdown.store(false, Ordering::Release);
1330        self.handle.dropped.store(false, Ordering::Release);
1331        self.handle.busy.store(false, Ordering::Release);
1332        self.handle.completed.store(false, Ordering::Release);
1333        // A respawned provider must re-assert readiness for its new instance.
1334        #[cfg(feature = "readiness")]
1335        {
1336            self.handle.ready.store(false, Ordering::Release);
1337            self.handle.ready_wake.reset();
1338        }
1339        self.handle.shutdown_wake.reset();
1340        self.handle.dropped_wake.reset();
1341    }
1342}
1343
1344/// Manual impl: the private `TaskHandle` (Signals + atomics) has no `Debug`, and a
1345/// snapshot of the *live* flags is more useful than raw handle internals anyway.
1346/// `finish_non_exhaustive` marks the elided fields (`spawn`, the handle).
1347impl core::fmt::Debug for TaskNode {
1348    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1349        f.debug_struct("TaskNode")
1350            .field("name", &self.name)
1351            .field("mode", &self.mode)
1352            .field("running", &self.is_running())
1353            .field("busy", &self.is_busy())
1354            .field("disabled", &self.is_disabled())
1355            .field("detached", &self.is_detached())
1356            .finish_non_exhaustive()
1357    }
1358}
1359
1360// ─── Graph ───────────────────────────────────────────────────────────────
1361
1362/// The compile-time task graph produced by [`supervisor_graph!`]: the node slots,
1363/// the dependency-index table, the topological order, and the elastic pools — the
1364/// single value [`Supervisor::new`] consumes. The macro emits one `pub static GRAPH`
1365/// of this type. The fields are public so the application can read them directly
1366/// (e.g. a status endpoint iterating `GRAPH.nodes` / `GRAPH.deps`).
1367///
1368/// `N` is capped at 256 (graph indices are `u8`); the macro enforces this at
1369/// expansion time.
1370pub struct Graph<const N: usize> {
1371    /// Node slots, one per declared node. `None` marks a `#[cfg]`-ed-out node.
1372    pub nodes: &'static [Option<&'static TaskNode>; N],
1373    /// Per-node dependency indices into `nodes` (`deps[i]` lists node `i`'s deps).
1374    pub deps: &'static [&'static [u8]; N],
1375    /// Topologically sorted indices into `nodes` (dependencies before dependents;
1376    /// reverse iteration is the teardown order). A dependency cycle is a compile error.
1377    pub order: [u8; N],
1378    /// Elastic worker pools to register with the supervisor (empty when unused).
1379    #[cfg(feature = "pool")]
1380    pub pools: &'static [&'static dyn Pool],
1381}
1382
1383// ─── Supervisor ──────────────────────────────────────────────────────────
1384
1385/// Orchestrates a set of managed tasks across spawn / teardown / bring-up.
1386///
1387/// Owned by a single supervisor task. Concurrent access from other tasks goes
1388/// through each [`TaskNode`]'s own atomic state, not the `Supervisor` struct.
1389pub struct Supervisor<const N: usize> {
1390    /// Node slots, one per declared node. `None` marks a slot whose node was
1391    /// `#[cfg]`-ed out of the build (feature-gated); every method skips those.
1392    nodes: &'static [Option<&'static TaskNode>],
1393    /// Per-node dependency indices into `nodes` (`deps[i]` lists the indices of
1394    /// the nodes that node `i` depends on). The single runtime source of graph
1395    /// topology, generated alongside `order` by the `supervisor_graph!` macro.
1396    #[cfg(any(feature = "control", feature = "pool"))]
1397    deps: &'static [&'static [u8]],
1398    /// Topologically sorted indices into `nodes`: dependencies before their
1399    /// dependents; reverse iteration is the teardown order. Precomputed at
1400    /// compile time (a cycle is a compile error), so construction does no work.
1401    /// Borrowed from the `static` [`Graph`] rather than copied: a `Supervisor`
1402    /// usually lives inside a task future (i.e. in that task's `static`
1403    /// storage), so an inline `[u8; N]` would cost N bytes of RAM per
1404    /// supervisor plus the copy code for no benefit.
1405    order: &'static [u8; N],
1406    /// Elastic pools, so the control interface can co-control a whole pool from
1407    /// any one member (`apply_control` expands the target through
1408    /// [`Pool::members`]) — the same registry `run_pools` drives. Taken from
1409    /// `GRAPH.pools` at construction (empty when no pool is declared).
1410    #[cfg(feature = "pool")]
1411    pools: &'static [&'static dyn Pool],
1412}
1413
1414/// Await a node's `executor:` [`SpawnerSlot`] (if it has one), bounded by the
1415/// node's [`slot_timeout`](TaskNode::with_slot_timeout) (default
1416/// [`SLOT_READY_TIMEOUT`]). A slot still empty after the wait yields
1417/// [`SpawnError::Busy`] — a loud misconfiguration, not a silent hang. A node with no
1418/// slot returns immediately, so a same-executor bring-up never touches the timer.
1419async fn await_spawn_slot(node: &'static TaskNode) -> Result<(), SpawnError> {
1420    if let Some(slot) = node.spawn_slot {
1421        with_timeout(node.slot_timeout, slot.ready())
1422            .await
1423            .map_err(|_| SpawnError::Busy)?;
1424    }
1425    Ok(())
1426}
1427
1428/// Await every [`ResourceSlot`] a node's `resources:` clause takes from being
1429/// filled, bounded by the node's
1430/// [`slot_timeout`](TaskNode::with_slot_timeout) (default
1431/// [`SLOT_READY_TIMEOUT`]) per gate. Covers three windows: `main` providing
1432/// after `start` was entered; — on respawn — the previous instance's shell
1433/// still between the shutdown ack and its `restore()` call (on another core
1434/// the two can genuinely overlap); and a **provider node** still building the
1435/// values this node consumes (size `slot_timeout:` to the build time). A gate
1436/// still empty at the deadline yields [`SpawnError::Busy`] — an unprovided
1437/// slot is a loud misconfiguration, not a silent hang. Nodes without
1438/// `resources:` have an empty gate list and never touch the timer. Same
1439/// check-then-park loop as [`SpawnerSlot::ready`]; the `filled` signal
1440/// latches, so a fill racing the check still wakes the wait (and the same
1441/// single-pre-fill-waiter caveat applies — the supervisor task is the only
1442/// intended waiter).
1443async fn await_resources(node: &'static TaskNode) -> Result<(), SpawnError> {
1444    for gate in node.resource_gates {
1445        let wait = async {
1446            loop {
1447                if gate.is_filled() {
1448                    break;
1449                }
1450                gate.filled_signal().wait().await;
1451            }
1452        };
1453        with_timeout(node.slot_timeout, wait)
1454            .await
1455            .map_err(|_| SpawnError::Busy)?;
1456    }
1457    Ok(())
1458}
1459
1460/// Await every `ready`-marked dep's task-asserted readiness before spawning
1461/// `node`, each bounded by the node's `slot_timeout` (same budget as its
1462/// resource gates — both are "my inputs aren't there yet"). Timeout maps to
1463/// `SpawnError::Busy` like the other pre-spawn gates; the log line names the
1464/// dep so a readiness timeout is distinguishable from a slot timeout.
1465#[cfg(feature = "readiness")]
1466async fn await_ready_deps(node: &'static TaskNode) -> Result<(), SpawnError> {
1467    for dep in node.ready_deps {
1468        if with_timeout(node.slot_timeout, dep.wait_ready())
1469            .await
1470            .is_err()
1471        {
1472            warn!(
1473                "supervisor: ready-dep {} not ready within {}ms (spawning {})",
1474                dep.name,
1475                node.slot_timeout.as_millis(),
1476                node.name,
1477            );
1478            return Err(SpawnError::Busy);
1479        }
1480    }
1481    Ok(())
1482}
1483#[cfg(not(feature = "readiness"))]
1484async fn await_ready_deps(_node: &'static TaskNode) -> Result<(), SpawnError> {
1485    Ok(())
1486}
1487
1488impl<const N: usize> Supervisor<N> {
1489    /// Build a supervisor from a precomputed [`Graph`] — the `GRAPH` that
1490    /// `supervisor_graph!` emits (node slots, dependency-index table, compile-time
1491    /// topological `order`, and the elastic pools). A dependency cycle is a
1492    /// *compile* error, so construction is infallible and does no work —
1493    /// `start` / `teardown` / `respawn_terminate` just iterate.
1494    pub const fn new(graph: &'static Graph<N>) -> Self {
1495        Self {
1496            nodes: graph.nodes,
1497            #[cfg(any(feature = "control", feature = "pool"))]
1498            deps: graph.deps,
1499            order: &graph.order,
1500            #[cfg(feature = "pool")]
1501            pools: graph.pools,
1502        }
1503    }
1504
1505    /// Bring the graph from any quiescent state to running, in dependency
1506    /// order — cold boot AND re-entry (a sub-graph supervisor is legitimately
1507    /// `start()`/`teardown()`-cycled per app phase). Idempotent: running nodes
1508    /// are skipped; detached nodes are skipped on re-entry (their instance
1509    /// survived the teardown — the first start still spawns them, the flag is
1510    /// app-set afterwards); a `Pause` instance parked by an earlier teardown is
1511    /// **resumed in place** (never double-spawned; like
1512    /// [`resume_pausable`](Self::resume_pausable) this bypasses the gate waits,
1513    /// since the parked instance retains its resources and its slots are empty
1514    /// by design). `Mode::OnDemand` nodes are skipped — they're brought up at
1515    /// runtime by `start_node`. A **parked** node (no `spawn` fn) is spawned
1516    /// externally by `main()` (with hardware handles main owns); it's still
1517    /// marked `running` here. Disabled nodes, and `#[cfg]`-ed-out slots, are
1518    /// skipped.
1519    ///
1520    /// Async because an `executor: NAME` node first awaits its [`SpawnerSlot::ready`]
1521    /// (bounded by `SLOT_READY_TIMEOUT` — the rendezvous with a tier or second core
1522    /// that comes up asynchronously); a slot still empty at the deadline fails the
1523    /// bring-up with [`SpawnError::Busy`]. A node with no `executor:` slot never
1524    /// touches the timer.
1525    pub async fn start(&self, spawner: Spawner) -> Result<(), SpawnError> {
1526        // Register the node slots with the trace recorders.
1527        #[cfg(feature = "trace")]
1528        trace::register_graph(self.nodes);
1529
1530        for i in self.order.iter() {
1531            let Some(node) = self.nodes[*i as usize] else {
1532                continue;
1533            };
1534            if matches!(node.mode, Mode::OnDemand) || node.is_disabled() {
1535                continue;
1536            }
1537            // Re-entry guards, making start() the universal quiescent-to-running
1538            // op (cold boot, post-teardown cycle, partial states) — all three
1539            // are no-ops on a cold boot:
1540            // * already running -> skip (idempotent; trustworthy because a
1541            //   cleanly returned body clears `running` via mark_exited);
1542            // * detached -> skip (its instance survived the teardown that
1543            //   preceded this start; spawning again would double-spawn — the
1544            //   flag is app-set at runtime, so first-start still spawns it);
1545            // * a Pause instance parked by an earlier teardown -> resume it in
1546            //   place below, never spawn a second one.
1547            if node.is_running() || node.is_detached() {
1548                continue;
1549            }
1550            if matches!(node.mode, Mode::Pause) && node.has_acked_stop() {
1551                // Same sequence as resume_pausable, and like it deliberately
1552                // WITHOUT the spawn path's gate waits: the parked instance
1553                // retains its resources, so its slots are empty by design and
1554                // await_resources would time out Busy.
1555                node.reset();
1556                info!("supervisor: resuming {} in place", node.name);
1557                node.signal_resume();
1558                node.set_running(true);
1559                continue;
1560            }
1561            // Clean handle per cycle (like start_node): a sub-graph supervisor
1562            // is legitimately start()/teardown()-cycled per app phase, and the
1563            // teardown latches the shutdown flag — without this reset a second
1564            // start()'s workers would observe it instantly. No-op at boot.
1565            node.reset();
1566            info!("supervisor: spawning {} ({})", node.name, node.mode);
1567            if let Some(spawn) = node.spawn {
1568                // For an `executor:` node, wait (bounded) for its slot to be filled
1569                // before spawning; a same-executor node has no slot, so this is an
1570                // immediate no-op and the bring-up loop stays tight. Then wait for
1571                // the node's `resources:` slots (if any) so the glue's take() finds
1572                // the value even if main provides late.
1573                await_spawn_slot(node).await?;
1574                await_resources(node).await?;
1575                await_ready_deps(node).await?;
1576                spawn(spawner)?;
1577            }
1578            node.set_running(true);
1579        }
1580        Ok(())
1581    }
1582
1583    /// The canonical driver, as one call: [`start`](Self::start) the graph,
1584    /// then drive elastic-pool scaling and/or runtime control forever. Returns
1585    /// **only on error** — every arm is an app-level escalation (typically
1586    /// `panic!` into a hardware-watchdog reset):
1587    ///
1588    /// ```ignore
1589    /// match sup.run(spawner).await {
1590    ///     RunError::Spawn(_) => defmt::panic!("supervisor: bring-up failed"),
1591    ///     RunError::Shutdown(e) => defmt::panic!("supervisor: {} missed ack", e.node.name),
1592    /// }
1593    /// ```
1594    ///
1595    /// Apps that select extra wake sources into the driver loop (their own
1596    /// signals, a wake timer) keep writing the loop by hand:
1597    /// `select(sup.run_pools(spawner), wait_control())` + `apply_control`.
1598    #[cfg(any(feature = "pool", feature = "control"))]
1599    pub async fn run(&self, spawner: Spawner) -> RunError {
1600        if let Err(e) = self.start(spawner).await {
1601            return RunError::Spawn(e);
1602        }
1603        #[cfg(all(feature = "pool", feature = "control"))]
1604        loop {
1605            match select(self.run_pools(spawner), wait_control()).await {
1606                Either::First(e) => return RunError::Shutdown(e),
1607                Either::Second(cmd) => {
1608                    if let Err(e) = self.apply_control(cmd, spawner).await {
1609                        return RunError::Shutdown(e);
1610                    }
1611                }
1612            }
1613        }
1614        #[cfg(all(feature = "pool", not(feature = "control")))]
1615        return RunError::Shutdown(self.run_pools(spawner).await);
1616        #[cfg(all(feature = "control", not(feature = "pool")))]
1617        loop {
1618            let cmd = wait_control().await;
1619            if let Err(e) = self.apply_control(cmd, spawner).await {
1620                return RunError::Shutdown(e);
1621            }
1622        }
1623    }
1624
1625    /// Start a single node at runtime — e.g. growing an elastic pool. Resets the
1626    /// handle, spawns one instance via the node's `spawn` fn (which must launch
1627    /// exactly one), and marks it `running`. Returns `SpawnError::Busy` if the
1628    /// underlying embassy task pool is exhausted (the ceiling), which the caller
1629    /// treats as "can't grow".
1630    pub async fn start_node(
1631        &self,
1632        node: &'static TaskNode,
1633        spawner: Spawner,
1634    ) -> Result<(), SpawnError> {
1635        node.reset();
1636        if let Some(spawn) = node.spawn {
1637            await_spawn_slot(node).await?;
1638            await_resources(node).await?;
1639            await_ready_deps(node).await?;
1640            spawn(spawner)?;
1641        }
1642        node.set_running(true);
1643        info!("supervisor: started {}", node.name);
1644        Ok(())
1645    }
1646
1647    /// Signal `node` to shut down, wait for its ack, then clear `running`.
1648    /// A missed ack (a missing `ack_dropped()`/`mark_exited()` somewhere, or a
1649    /// wedged task) is returned as [`ShutdownTimeout`] — the node keeps running
1650    /// and the caller decides the escalation. Shared by `stop_node` and
1651    /// `teardown`; the caller must have checked `is_running`.
1652    async fn shutdown_and_wait(&self, node: &'static TaskNode) -> Result<(), ShutdownTimeout> {
1653        node.signal_shutdown();
1654        if let Either::Second(()) = select(
1655            node.wait_dropped(),
1656            Timer::after_millis(SHUTDOWN_ACK_TIMEOUT_MS),
1657        )
1658        .await
1659        {
1660            warn!(
1661                "supervisor: task {} did not ack shutdown within {}ms",
1662                node.name, SHUTDOWN_ACK_TIMEOUT_MS,
1663            );
1664            return Err(ShutdownTimeout { node });
1665        }
1666        node.set_running(false);
1667        Ok(())
1668    }
1669
1670    /// Stop a single running node at runtime — e.g. shrinking an elastic pool.
1671    /// For a `Pause` node this IS the single-node "pause": the worker acks and
1672    /// parks on `wait_resume()`, and [`resume_node`](Self::resume_node) is the
1673    /// symmetric other half. Signals shutdown, waits for the ack, clears
1674    /// `running`. No-op `Ok` if the node isn't running, or is
1675    /// [detached](TaskNode::set_detached) (self-managed — the supervisor never
1676    /// stops it). A node that misses the ack window is returned as
1677    /// [`ShutdownTimeout`] and stays marked running.
1678    pub async fn stop_node(&self, node: &'static TaskNode) -> Result<(), ShutdownTimeout> {
1679        if !node.is_running() || node.is_detached() {
1680            return Ok(());
1681        }
1682        self.shutdown_and_wait(node).await?;
1683        info!("supervisor: stopped {}", node.name);
1684        Ok(())
1685    }
1686
1687    /// Signal every **running** node to shut down in **reverse** topological
1688    /// order, awaiting each node's ack before moving to its dependency. Down
1689    /// `OnDemand` nodes are skipped (no instance to ack). Pause-mode nodes ack
1690    /// and park on `wait_resume()`; Terminate/OnDemand nodes exit.
1691    ///
1692    /// **Aborts on the first missed ack**, returning the offending node as
1693    /// [`ShutdownTimeout`]: continuing would stop dependencies out from under a
1694    /// still-live dependent. After `Err` the graph is partially down — the sane
1695    /// escalations are app-level (hardware watchdog reset, `panic!`, retry, or
1696    /// [`teardown_continue`](Self::teardown_continue) when quiescing the rest
1697    /// still matters before a reset).
1698    pub async fn teardown(&self) -> Result<(), ShutdownTimeout> {
1699        for i in self.order.iter().rev() {
1700            let Some(node) = self.nodes[*i as usize] else {
1701                continue;
1702            };
1703            if !node.is_running() {
1704                continue;
1705            }
1706            // A detached node is self-managed; never tear it down. See
1707            // [`TaskNode::set_detached`].
1708            if node.is_detached() {
1709                continue;
1710            }
1711            info!("supervisor: tearing down {}", node.name);
1712            self.shutdown_and_wait(node).await?;
1713        }
1714        Ok(())
1715    }
1716
1717    /// Best-effort variant of [`teardown`](Self::teardown) for the
1718    /// "hardware reset next" escalation path: presses on past a non-acking node
1719    /// (still in reverse topological order) so the remaining nodes get their
1720    /// chance to flush and park, and returns the **first** timeout after
1721    /// visiting every node. The wedged node's dependencies are stopped under it
1722    /// — acceptable only because the caller is about to reset anyway.
1723    pub async fn teardown_continue(&self) -> Result<(), ShutdownTimeout> {
1724        let mut first_err = Ok(());
1725        for i in self.order.iter().rev() {
1726            let Some(node) = self.nodes[*i as usize] else {
1727                continue;
1728            };
1729            if !node.is_running() || node.is_detached() {
1730                continue;
1731            }
1732            info!("supervisor: tearing down {}", node.name);
1733            if let Err(e) = self.shutdown_and_wait(node).await {
1734                if first_err.is_ok() {
1735                    first_err = Err(e);
1736                }
1737            }
1738        }
1739        first_err
1740    }
1741
1742    /// Resume ONE `Pause` node parked by an earlier [`stop_node`](Self::stop_node)
1743    /// or [`teardown`](Self::teardown) — the single-node partner of
1744    /// [`resume_pausable`](Self::resume_pausable), same sequence and the same
1745    /// deliberate absence of dependency gating (the parked instance retains its
1746    /// resources). Cheap and synchronous. No-op unless the node is `Pause`
1747    /// mode, actually parked (an instance acked without exiting), and neither
1748    /// [disabled](TaskNode::is_disabled) (a control pause sticks — clear it
1749    /// with [`activate`](Self::activate)) nor
1750    /// [detached](TaskNode::set_detached).
1751    pub fn resume_node(&self, node: &'static TaskNode) {
1752        if !matches!(node.mode, Mode::Pause)
1753            || node.is_disabled()
1754            || node.is_detached()
1755            || !node.has_acked_stop()
1756        {
1757            return;
1758        }
1759        node.reset();
1760        info!("supervisor: resuming {}", node.name);
1761        node.signal_resume();
1762        node.set_running(true);
1763    }
1764
1765    /// Signal every Pause-mode node to resume. Cheap and synchronous — the tasks
1766    /// were parked on `wait_resume()` and pick up immediately. Called separately
1767    /// from `respawn_terminate` so the application can fire resume independently
1768    /// of the respawn step. Disabled (manually-paused) nodes are skipped so a
1769    /// manual pause sticks, and detached (self-managed) Pause nodes are left
1770    /// parked; there is intentionally no dependency gate here.
1771    pub fn resume_pausable(&self) {
1772        for i in self.order.iter() {
1773            let Some(node) = self.nodes[*i as usize] else {
1774                continue;
1775            };
1776            if matches!(node.mode, Mode::Pause) && !node.is_disabled() && !node.is_detached() {
1777                node.reset();
1778                info!("supervisor: resuming {}", node.name);
1779                node.signal_resume();
1780                node.set_running(true);
1781            }
1782        }
1783    }
1784
1785    /// Reset and re-spawn every Terminate-mode node in dependency order.
1786    /// Pause-mode nodes are untouched (use `resume_pausable`); `OnDemand` nodes
1787    /// are left down — they re-grow under load via `start_node`. Disabled nodes
1788    /// are skipped so a manual stop sticks across the bring-up. Detached nodes are
1789    /// skipped too: `teardown` never brought them down, so they are still running
1790    /// and re-spawning would double-spawn them (see [`TaskNode::set_detached`]). The
1791    /// reset happens before the spawn so newly-running tasks see a clean handle.
1792    pub async fn respawn_terminate(&self, spawner: Spawner) -> Result<(), SpawnError> {
1793        for i in self.order.iter() {
1794            let Some(node) = self.nodes[*i as usize] else {
1795                continue;
1796            };
1797            if matches!(node.mode, Mode::Terminate) && !node.is_disabled() && !node.is_detached() {
1798                node.reset();
1799                info!("supervisor: respawning {}", node.name);
1800                if let Some(spawn) = node.spawn {
1801                    await_spawn_slot(node).await?;
1802                    // A `resources:` node's previous instance restores its slot
1803                    // value only after the shutdown ack, so wait (bounded) for
1804                    // the restore before the glue's take().
1805                    await_resources(node).await?;
1806                    await_ready_deps(node).await?;
1807                    spawn(spawner)?;
1808                }
1809                node.set_running(true);
1810            }
1811        }
1812        Ok(())
1813    }
1814}
1815
1816// ─── Runtime control (dependency- and pool-honoring start/stop) ────────────
1817//
1818// The `apply_control` entry point drives one `ControlCommand` from the
1819// application's control surface. Unlike the pool's bare `start_node`/`stop_node`,
1820// these honor the graph: a stop cascades through dependents (so nothing is left
1821// running without a dependency), a start cascades through deps (so nothing comes
1822// up before what it needs), and either expands across a whole `ElasticPool` so
1823// the pool is controlled as a unit. A manual stop/pause also sets the
1824// lifecycle-spanning `disabled` flag, so it sticks against the elastic policy and
1825// the wake respawn.
1826
1827// Graph-index helpers used by BOTH the control plane and the pool driver, so they
1828// are gated on either feature — `pool` alone (no `control`) must still compile.
1829#[cfg(any(feature = "control", feature = "pool"))]
1830impl<const N: usize> Supervisor<N> {
1831    /// Position of `node` in `self.nodes` (pointer identity — every node is a
1832    /// `&'static`). `None` only if the node isn't in this graph (impossible for
1833    /// targets sourced from `GRAPH.nodes`; treated as a no-op by callers).
1834    fn index_of(&self, node: &'static TaskNode) -> Option<usize> {
1835        self.nodes
1836            .iter()
1837            .position(|n| n.is_some_and(|x| core::ptr::eq(x, node)))
1838    }
1839
1840    /// Whether every dependency of `node` is currently running, resolved through
1841    /// the graph's index table. The pool driver checks this before growing a
1842    /// worker, so a pool member is never spawned while one of its dependencies is
1843    /// down.
1844    #[cfg(feature = "pool")]
1845    pub(crate) fn deps_running(&self, node: &'static TaskNode) -> bool {
1846        match self.index_of(node) {
1847            Some(i) => self.deps[i]
1848                .iter()
1849                .all(|&di| self.nodes[di as usize].is_some_and(|n| n.is_running())),
1850            None => false,
1851        }
1852    }
1853}
1854
1855#[cfg(feature = "control")]
1856impl<const N: usize> Supervisor<N> {
1857    /// Seed a membership set with `target` plus — if `target` belongs to an
1858    /// elastic pool — every member of that pool, so control is applied to the
1859    /// whole pool atomically. Pool membership is read from `GRAPH.pools`; with no
1860    /// pools (the `pool` feature off, or none declared) this is just `{target}`.
1861    fn seed(&self, target: &'static TaskNode, set: &mut [bool; N]) {
1862        if let Some(i) = self.index_of(target) {
1863            set[i] = true;
1864        }
1865        #[cfg(feature = "pool")]
1866        for pool in self.pools {
1867            let members = pool.members();
1868            if members.iter().any(|m| core::ptr::eq(*m, target)) {
1869                for m in members {
1870                    if let Some(i) = self.index_of(m) {
1871                        set[i] = true;
1872                    }
1873                }
1874            }
1875        }
1876    }
1877
1878    /// Apply one control command, honoring pool membership and the dependency
1879    /// graph — the mailbox-dispatch form of [`activate`](Self::activate) /
1880    /// [`deactivate`](Self::deactivate) (call those directly when you hold the
1881    /// supervisor). Run from the supervisor's driver loop (never concurrently
1882    /// with itself), so the cascade is atomic from the application's
1883    /// perspective. A `Deactivate` cascade propagates a missed shutdown ack as
1884    /// [`ShutdownTimeout`] (the cascade aborts at the offending node, dependents
1885    /// already stopped); `Activate` cannot fail this way.
1886    pub async fn apply_control(
1887        &self,
1888        cmd: ControlCommand,
1889        spawner: Spawner,
1890    ) -> Result<(), ShutdownTimeout> {
1891        match cmd.op {
1892            ControlOp::Deactivate => self.deactivate(cmd.node).await,
1893            ControlOp::Activate => {
1894                self.activate(cmd.node, spawner).await;
1895                Ok(())
1896            }
1897        }
1898    }
1899
1900    /// Bring `target` (and its pool, and every transitive dependent) down, in
1901    /// reverse-topological order so each dependent stops before the dependency it
1902    /// relies on — the cascading "turn this subsystem off" verb, and the exit
1903    /// half of the subordinate sub-graph pattern's one-graph variant. Marks
1904    /// the whole set `disabled` so the stop sticks against the elastic policy
1905    /// and the wake respawn until a matching [`activate`](Self::activate).
1906    /// Aborts with [`ShutdownTimeout`] on a missed ack (the offending node stays
1907    /// running and disabled; dependents visited before it are already down).
1908    ///
1909    /// Contrast [`stop_node`](Self::stop_node): ONE node, no cascade, no
1910    /// `disabled` latch (the pool-shrink primitive). Call this directly when
1911    /// you hold the supervisor; [`request_control`] +
1912    /// [`apply_control`](Self::apply_control) is the same operation routed
1913    /// through the mailbox from code that doesn't.
1914    pub async fn deactivate(&self, target: &'static TaskNode) -> Result<(), ShutdownTimeout> {
1915        let mut set = [false; N];
1916        self.seed(target, &mut set);
1917
1918        // Grow the set to include transitive dependents. `order` is
1919        // dependency-first, so when we reach a node its deps are already decided;
1920        // a node joins if any dep it declares is already in the set.
1921        for i in self.order.iter() {
1922            let j = *i as usize;
1923            if set[j] {
1924                continue;
1925            }
1926            let Some(node) = self.nodes[j] else {
1927                continue;
1928            };
1929            // A detached node declares its dep only for start ordering and intends
1930            // to outlive it, so it's never pulled into the cascade.
1931            if node.is_detached() {
1932                continue;
1933            }
1934            if self.deps[j].iter().any(|&di| set[di as usize]) {
1935                set[j] = true;
1936            }
1937        }
1938
1939        // Tear down in reverse topo order (dependents before their deps).
1940        for i in self.order.iter().rev() {
1941            let j = *i as usize;
1942            if !set[j] {
1943                continue;
1944            }
1945            let Some(node) = self.nodes[j] else {
1946                continue;
1947            };
1948            // A detached node is self-managed — never control-stop it. The growth loop
1949            // keeps detached *dependents* out of the set; this also covers a detached
1950            // node that was seeded directly (or a detached pool member). Without it a
1951            // detached one-shot that already exited (stale `is_running`, no ack path)
1952            // would be signalled a shutdown it can never acknowledge, failing here
1953            // with a spurious `ShutdownTimeout`.
1954            if node.is_detached() {
1955                continue;
1956            }
1957            node.set_disabled(true);
1958            if node.is_running() {
1959                info!("supervisor: control-stop {}", node.name);
1960                self.shutdown_and_wait(node).await?;
1961            }
1962        }
1963        Ok(())
1964    }
1965
1966    /// Bring `target` (and its pool, and every transitive dependency) up, in
1967    /// topological order so each dependency starts before its dependent — the
1968    /// cascading "turn this subsystem on" verb, and the entry half of the
1969    /// subordinate sub-graph pattern's one-graph variant: `activate` on a
1970    /// subtree's LEAF pulls its whole dependency chain up, skipping
1971    /// already-running nodes. Per-node spawn errors are deliberately swallowed
1972    /// (a cascade is best-effort; a `Busy` member is re-driven by the pool
1973    /// policy or a later activate), so this returns `()` — asymmetric with
1974    /// [`deactivate`](Self::deactivate) on purpose. Clears
1975    /// `disabled` across the set. `OnDemand` (pool) members are only re-enabled,
1976    /// not force-spawned — the elastic policy re-grows them under load, which is
1977    /// the whole point of the pool.
1978    pub async fn activate(&self, target: &'static TaskNode, spawner: Spawner) {
1979        let mut set = [false; N];
1980        self.seed(target, &mut set);
1981
1982        // Grow the set to include transitive deps. Walk dependents-first
1983        // (reverse topo); when a set member is seen, pull in its direct deps.
1984        // A detached member's `deps:` are start-ordering only (the node is
1985        // self-managed), so don't expand from it — mirrors deactivate's guard;
1986        // otherwise activating a detached target would un-disable deps that
1987        // were independently disabled.
1988        for i in self.order.iter().rev() {
1989            let j = *i as usize;
1990            if set[j] && !self.nodes[j].is_some_and(|n| n.is_detached()) {
1991                for &di in self.deps[j] {
1992                    set[di as usize] = true;
1993                }
1994            }
1995        }
1996
1997        // Bring up in topo order (deps before dependents).
1998        for i in self.order.iter() {
1999            let j = *i as usize;
2000            if !set[j] {
2001                continue;
2002            }
2003            let Some(node) = self.nodes[j] else {
2004                continue;
2005            };
2006            // A detached node is self-managed — the supervisor never re-enables or
2007            // re-starts it, even when it is a dependency of an activated target.
2008            if node.is_detached() {
2009                continue;
2010            }
2011            node.set_disabled(false);
2012            if node.is_running() {
2013                continue;
2014            }
2015            match node.mode {
2016                Mode::Terminate => {
2017                    info!("supervisor: control-start {}", node.name);
2018                    // SpawnError::Busy (pool exhausted) → can't start, skip.
2019                    let _ = self.start_node(node, spawner).await;
2020                }
2021                Mode::Pause => {
2022                    info!("supervisor: control-resume {}", node.name);
2023                    node.reset();
2024                    node.signal_resume();
2025                    node.set_running(true);
2026                }
2027                // Pool worker — leave it down; the elastic policy regrows it on
2028                // demand now that `disabled` is cleared.
2029                Mode::OnDemand => {}
2030            }
2031        }
2032    }
2033}
2034
2035// ─── Topological sort (Kahn's algorithm, const) ───────────────────────────
2036//
2037// Computes the topological order at *compile time* over a per-node
2038// dependency-index table; a dependency cycle is a compile error.
2039
2040/// Topologically sort a graph given as a per-node dependency-index table.
2041///
2042/// `deps[i]` lists the indices of the nodes that node `i` depends on; the result
2043/// lists node indices in dependency-first order (a dependency appears before its
2044/// dependents). The supervisor iterates it forward for `start` /
2045/// `respawn_terminate` and in reverse for `teardown`.
2046///
2047/// Evaluated at compile time by the code `supervisor_graph!` generates — a
2048/// dependency **cycle is a compile error** (the `panic!` fires during const
2049/// evaluation). `#[doc(hidden)]`: an engine for the macro, not a user-facing API.
2050///
2051/// Supports at most 256 nodes: indices are `u8`, so a larger `N` would truncate.
2052/// The macro rejects bigger graphs at expansion; the assert below is defense in
2053/// depth for a manual caller (a const-eval panic, i.e. a compile error).
2054#[doc(hidden)]
2055#[must_use]
2056pub const fn topo_sort_const<const N: usize>(deps: &[&'static [u8]; N]) -> [u8; N] {
2057    assert!(
2058        N <= 256,
2059        "supervisor graph exceeds 256 node slots (indices are u8)"
2060    );
2061    // in_degree[i] = number of deps of node i not yet resolved.
2062    let mut in_degree = [0u8; N];
2063    let mut i = 0;
2064    while i < N {
2065        in_degree[i] = deps[i].len() as u8;
2066        i += 1;
2067    }
2068
2069    // Queue (fixed array, head/tail indices) seeded with the dependency-free nodes.
2070    let mut queue = [0u8; N];
2071    let mut tail = 0;
2072    i = 0;
2073    while i < N {
2074        if in_degree[i] == 0 {
2075            queue[tail] = i as u8;
2076            tail += 1;
2077        }
2078        i += 1;
2079    }
2080
2081    let mut order = [0u8; N];
2082    let mut produced = 0;
2083    let mut head = 0;
2084    while head < tail {
2085        let node = queue[head] as usize;
2086        head += 1;
2087        order[produced] = node as u8;
2088        produced += 1;
2089
2090        // Decrement the in-degree of every node that depends on `node`.
2091        let mut j = 0;
2092        while j < N {
2093            if in_degree[j] != 0 {
2094                let mut depends = false;
2095                let mut k = 0;
2096                while k < deps[j].len() {
2097                    if deps[j][k] as usize == node {
2098                        depends = true;
2099                    }
2100                    k += 1;
2101                }
2102                if depends {
2103                    in_degree[j] -= 1;
2104                    if in_degree[j] == 0 {
2105                        queue[tail] = j as u8;
2106                        tail += 1;
2107                    }
2108                }
2109            }
2110            j += 1;
2111        }
2112    }
2113
2114    // A cycle leaves some nodes unproduced. During const eval this panic is a
2115    // compile error, so cyclic graphs are rejected at build time. `core::panic!`
2116    // (not the crate's defmt-shimmed `panic!`) keeps this const-evaluable.
2117    if produced != N {
2118        core::panic!("supervisor_graph!: dependency cycle");
2119    }
2120    order
2121}
2122
2123#[cfg(feature = "pool")]
2124mod pool;
2125#[cfg(feature = "pool")]
2126pub use pool::*;
2127
2128#[cfg(feature = "trace")]
2129pub mod trace;
2130
2131#[cfg(feature = "macros")]
2132pub use embassy_supervisor_macros::supervisor_fragment;
2133/// Declare a supervised task graph and compute its topological order at compile
2134/// time (single source of nodes, deps, pool, and order). See the
2135/// `embassy-supervisor-macros` crate for the surface syntax.
2136#[cfg(feature = "macros")]
2137pub use embassy_supervisor_macros::supervisor_graph;
2138
2139/// Assemble one graph from `supervisor_fragment!` relays plus compose-site
2140/// items:
2141///
2142/// ```ignore
2143/// embassy_supervisor::compose_graph! {
2144///     fragments: [::net_stack::NET_FRAG, HTTP_FRAG],
2145///     graph: {
2146///         node APP = Terminate, deps: [NET], task: app_worker; // cross-fragment dep
2147///     }
2148/// }
2149/// ```
2150///
2151/// Fragments expand in listed order, then the `graph:` items; everything
2152/// reaches ONE `supervisor_graph!` expansion, so cross-fragment deps resolve by
2153/// name (forward references included) and every compile-time pass — name map,
2154/// u8 slot indices, topological order, shared-slot dedup, the 256-node cap —
2155/// checks the whole composed graph. One compose site per binary (it emits the
2156/// usual `GRAPH`/`NODES`/`DEPS` statics and, under `trace-hooks`, the hook
2157/// symbols). Name collisions across fragments hit the ordinary duplicate-name
2158/// errors, attributed to the owning fragment; prefix fragment-public names.
2159#[cfg(feature = "macros")]
2160#[macro_export]
2161macro_rules! compose_graph {
2162    // `name: X,` first renames the composed graph static (see
2163    // `supervisor_graph!`'s `name:`) — seeded into the accumulator ahead of
2164    // every fragment's items so it stays the expansion's first item.
2165    (name: $n:ident, fragments: [$f:path $(, $r:path)* $(,)?], graph: {$($g:tt)*}) => {
2166        $f! { @emit $crate::compose_graph, [$($r),*], {name: $n;}, {$($g)*} }
2167    };
2168    (fragments: [$f:path $(, $r:path)* $(,)?], graph: {$($g:tt)*}) => {
2169        $f! { @emit $crate::compose_graph, [$($r),*], {}, {$($g)*} }
2170    };
2171    (@next [], {$($acc:tt)*}, {$($g:tt)*}) => {
2172        $crate::supervisor_graph! { $($acc)* $($g)* }
2173    };
2174    (@next [$f:path $(, $r:path)*], {$($acc:tt)*}, $g:tt) => {
2175        $f! { @emit $crate::compose_graph, [$($r),*], {$($acc)*}, $g }
2176    };
2177}
2178
2179/// Building blocks for `supervisor_graph!`-generated code — NOT public API.
2180///
2181/// The macro's `local`-marked `resources:` entries emit a slot *type* at the
2182/// graph declaration site (it needs an `unsafe impl Sync`, — same reason the
2183/// `trace-hooks` symbols are emitted there). That generated type must name
2184/// the exact `Signal`/mutex types in [`ResourceGate`]'s signature; re-exporting
2185/// them here keeps the macro's contract that a consumer only needs
2186/// `embassy-supervisor` itself as a real-named dependency (not `embassy-sync`).
2187#[doc(hidden)]
2188pub mod _export {
2189    pub use embassy_sync::blocking_mutex::Mutex as BlockingMutex;
2190    pub use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
2191    pub use embassy_sync::signal::Signal;
2192    // For the `slot_timeout:` clause's emitted `with_slot_timeout(..)` call.
2193    pub use embassy_time::Duration;
2194}