Skip to main content

agentmux_srv_core/broker/
process.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Process Broker — Phase A of the process-tracking consolidation.
5//!
6//! See `docs/specs/REPORT_PROCESS_ARCHITECTURE_STATE_AND_RETHINK_2026_07_22.md`
7//! for the full rationale. AgentMux answers "is this agent/process alive and
8//! what's it doing" six different, only-partially-overlapping ways today
9//! (`blockcontroller::CONTROLLER_REGISTRY`, `process_tracker`, the `reactive`
10//! handler's own registration list, `pidregistry`, `TurnActivityTracker`'s
11//! turn-active bookkeeping, and `watchdog.rs`'s PTY-idle timers). This
12//! module is the consolidation point for the two callers that most directly
13//! motivated it (the Agent pane's process badge and the Swarm pane's block
14//! discovery/overview), modeled on `broker::scheduler`'s Credential Broker
15//! (same crate, sibling module — same "one broker, register your own
16//! backing store" pattern applied to a second domain) and on
17//! `agentmux-srv::reducer`'s existing discipline of computing state through
18//! one arbiter with explicit transition logic rather than letting every
19//! caller mutate a shared map directly (see `lifecycle_from` below, which
20//! mirrors `reducer/lifecycle.rs::handle_register`'s shape: pure function,
21//! explicit rule per legal state, no bare field copy).
22//!
23//! **Phase A scope:** read-side only. `status()`/`list()` compute a
24//! normalized `ProcessStatus` by querying today's existing sources
25//! (`blockcontroller` for lifecycle — authoritative, has an entry for every
26//! controller type; `process_tracker` for OS-process detail — only
27//! populated for `subprocess`/`persistent` controllers today) and cache the
28//! result, single-flight-guarded per call. This closes the concrete,
29//! reported bug directly: `agent.tracked-blocks`'s `.chain()` of
30//! `process_tracker` + the `reactive` handler's registration list (two
31//! structurally different registries unioned with no reconciliation) is
32//! replaced by `blockcontroller::get_all_controllers()`, which is already
33//! authoritative for "which blocks exist" across every controller type.
34//!
35//! **Deferred to later phases** (see the report's §6 open questions):
36//! migrating each `Controller` impl to register with this broker directly
37//! at spawn (closing the coverage gap at the write side, not just papering
38//! over it at the read side); consolidating the two independent
39//! activity-summary pipelines; moving the Swarm pane's client-side-only
40//! fine-grained activity chip server-side. None of that is touched here.
41
42use std::collections::HashMap;
43use std::sync::{Arc, OnceLock};
44
45use parking_lot::Mutex;
46
47use crate::backend::blockcontroller::{self, BlockControllerRuntimeStatus};
48use crate::backend::process_tracker::{self, TrackedProcess, TrackingConfidence};
49use crate::backend::mps::Broker as WpsBroker;
50
51/// MPS event name for a `ProcessStatus` change. Scoped `block:<id>`, same
52/// convention as `agent:process-added`/`controllerstatus`. Consumers that
53/// want the unified signal subscribe to this instead of the two separate
54/// events the old `.chain()`-based discovery relied on.
55pub const EVENT_STATUS_CHANGED: &str = "processbroker:status-changed";
56
57/// MPS event name for "`list()`/`list_agent_panes()` membership may have
58/// changed" — published whenever `blockcontroller::register_controller` or
59/// `delete_controller` runs. Unscoped (no `block:<id>` — see
60/// `emit_tracked_blocks_changed`'s doc comment for why).
61pub const EVENT_TRACKED_BLOCKS_CHANGED: &str = "processbroker:tracked-blocks-changed";
62
63/// Coarse "is it alive" question, normalized from `BlockControllerRuntimeStatus`'s
64/// `turn_active`/`shellprocstatus`/`shellprocexitcode` fields into one enum —
65/// the Pod-phase-equivalent signal in the Kubernetes phase/status/probe
66/// analogy the report draws in §4.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
68#[ts(export, export_to = "../../../frontend/types/rpc/")]
69#[serde(rename_all = "snake_case")]
70pub enum Lifecycle {
71    Running,
72    Idle,
73    Done,
74    Error,
75    /// No controller found for this block_id at all — distinct from `Idle`,
76    /// which means a controller exists and reports it's not mid-turn.
77    Unknown,
78}
79
80/// The broker's public read shape — one struct every consumer (Agent pane,
81/// Swarm pane, future consumers) reads instead of composing raw registry
82/// data themselves.
83#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
84#[ts(export, export_to = "../../../frontend/types/rpc/")]
85pub struct ProcessStatus {
86    pub block_id: String,
87    pub lifecycle: Lifecycle,
88    /// OS-process-tree detail — empty for controller types `process_tracker`
89    /// doesn't cover yet (today: `shell`, `acp`; report §1/§5.2). Presence of
90    /// entries here is opportunistic enrichment, not a liveness signal on
91    /// its own — use `lifecycle`, not `!processes.is_empty()`, to answer
92    /// "is it alive."
93    pub processes: Vec<TrackedProcess>,
94    pub liveness_confidence: TrackingConfidence,
95    /// Controller type string (`"shell"`, `"cmd"`, `"subprocess"`,
96    /// `"persistent"`, `"acp"`, `"app-server"`) — see `is_agent()` for why this
97    /// matters beyond being informational.
98    pub controller_type: String,
99    pub is_agent_pane: bool,
100    #[ts(type = "number")]
101    pub last_computed_ms: u64,
102    /// The raw `BlockControllerRuntimeStatus` `compute_status` already reads
103    /// to derive `lifecycle`/`is_agent_pane` above — exposed so callers that
104    /// want the finer-grained fields (`shellprocstatus`, `spawn_ts_ms`,
105    /// `turn_active` itself, not just the `lifecycle` it was folded into)
106    /// don't have to read the controller registry a second time and risk a
107    /// second, possibly-inconsistent snapshot (codex P2 on PR #2380 — the
108    /// `muxspect describe` route originally did exactly that).
109    pub controller_status: Option<BlockControllerRuntimeStatus>,
110}
111
112impl ProcessStatus {
113    fn unknown(block_id: &str) -> Self {
114        Self {
115            block_id: block_id.to_string(),
116            lifecycle: Lifecycle::Unknown,
117            processes: Vec::new(),
118            liveness_confidence: TrackingConfidence::None,
119            controller_type: String::new(),
120            is_agent_pane: false,
121            last_computed_ms: now_ms(),
122            controller_status: None,
123        }
124    }
125
126    /// True if this block is an agent pane rather than a plain terminal.
127    ///
128    /// `is_agent_pane` alone is NOT sufficient: `subprocess`/`persistent`/
129    /// `acp` controllers exist *only* for agent CLIs (one-shot-per-turn,
130    /// long-lived stream-json, and JSON-RPC/ACP agents respectively — see
131    /// `blockcontroller/mod.rs`'s controller-type doc), but
132    /// `SubprocessController` unconditionally reports `is_agent_pane:
133    /// false` in its runtime status regardless (reagent/codex P1 on
134    /// #2273 — filtering on the flag alone would wrongly exclude every
135    /// `subprocess`-type agent pane). Only `shell`/`cmd` controllers can
136    /// legitimately be either a plain terminal or an agent running inside
137    /// one, so `is_agent_pane` (set dynamically at PTY spawn time — see
138    /// `shell/lifecycle.rs`) is the correct signal for exactly those two
139    /// types, and only those two.
140    pub fn is_agent(&self) -> bool {
141        match self.controller_type.as_str() {
142            blockcontroller::BLOCK_CONTROLLER_SUBPROCESS
143            | blockcontroller::BLOCK_CONTROLLER_PERSISTENT
144            | blockcontroller::BLOCK_CONTROLLER_ACP
145            | blockcontroller::BLOCK_CONTROLLER_MSP => true,
146            _ => self.is_agent_pane,
147        }
148    }
149}
150
151use agentmux_common::time::now_ms_u64 as now_ms;
152
153/// Pure reducer over one block's raw controller status: decides
154/// `Lifecycle` via explicit per-case rules, not a bare field copy. Isolated
155/// from I/O so the transition rules are unit-testable without a real
156/// controller instance — mirrors `reducer/lifecycle.rs::handle_register`'s
157/// shape (compute the legal next state from the current observation,
158/// rather than trusting the caller's intent unconditionally).
159fn lifecycle_from(status: &BlockControllerRuntimeStatus) -> Lifecycle {
160    // turn_active is the only signal that distinguishes "actively
161    // generating a turn" from "process alive, idle between turns" for a
162    // PersistentSubprocessController — shellprocstatus alone can't tell
163    // the difference (see BlockControllerRuntimeStatus's own doc comment).
164    if status.turn_active {
165        return Lifecycle::Running;
166    }
167    match status.shellprocstatus.as_str() {
168        blockcontroller::STATUS_RUNNING => Lifecycle::Idle,
169        blockcontroller::STATUS_INIT => Lifecycle::Idle,
170        blockcontroller::STATUS_DONE if status.shellprocexitcode == 0 => Lifecycle::Done,
171        blockcontroller::STATUS_DONE => Lifecycle::Error,
172        _ => Lifecycle::Unknown,
173    }
174}
175
176/// Compute a block's current `ProcessStatus` from today's underlying
177/// sources. Pure with respect to its two inputs — the only I/O is the two
178/// read calls themselves (both cheap in-memory lock acquisitions, not
179/// blocking I/O — process_tracker's registry and blockcontroller's
180/// CONTROLLER_REGISTRY are both `parking_lot`/`std` sync locks guarding
181/// plain maps).
182fn compute_status(block_id: &str) -> ProcessStatus {
183    let controller = blockcontroller::get_controller(block_id);
184    let controller_status = controller.as_ref().map(|c| c.get_runtime_status());
185    let (processes, liveness_confidence) = process_tracker::registry::global()
186        .map(|r| (r.list_block(block_id), r.confidence_of(block_id)))
187        .unwrap_or((Vec::new(), TrackingConfidence::None));
188
189    match (controller, controller_status) {
190        (Some(controller), Some(status)) => ProcessStatus {
191            block_id: block_id.to_string(),
192            lifecycle: lifecycle_from(&status),
193            processes,
194            liveness_confidence,
195            controller_type: controller.controller_type().to_string(),
196            is_agent_pane: status.is_agent_pane,
197            last_computed_ms: now_ms(),
198            controller_status: Some(status),
199        },
200        _ => ProcessStatus::unknown(block_id),
201    }
202}
203
204pub struct ProcessBroker {
205    /// Broker-owned cache — the single source future callers read from,
206    /// rather than each composing `blockcontroller`/`process_tracker`
207    /// themselves. `parking_lot::Mutex`, not an async mutex: unlike the
208    /// credential broker's `Entry::lock` (which guards an actual network
209    /// refresh call and must not block a tokio worker thread while held),
210    /// this cache's critical section is two cheap in-memory map reads plus
211    /// a struct build — synchronous and fast, the same reasoning
212    /// `process_tracker::registry::AgentProcessRegistry` already uses
213    /// `parking_lot::Mutex` for. Coarse-grained (one mutex, not
214    /// per-block_id): contention is expected to be negligible for the same
215    /// reason; narrow the granularity later if profiling says otherwise.
216    /// If a later phase adds a genuinely blocking liveness check (report
217    /// §3.0.3 point 1 — e.g. a real health-probe round-trip), that phase
218    /// should revisit this as an async lock at the same time, not before.
219    cache: Mutex<HashMap<String, ProcessStatus>>,
220    mps_broker: Option<Arc<WpsBroker>>,
221}
222
223impl ProcessBroker {
224    pub fn new(mps_broker: Option<Arc<WpsBroker>>) -> Self {
225        Self {
226            cache: Mutex::new(HashMap::new()),
227            mps_broker,
228        }
229    }
230
231    /// Recompute and return one block's status. Single-flight-guarded by
232    /// holding the cache lock across the *entire* read-compare-write
233    /// sequence, not just the write — `compute_status` must run inside the
234    /// critical section, not before it. reagent P1 on #2273 caught this:
235    /// with the read outside the lock, two concurrent callers (e.g. an
236    /// Agent pane mount and Swarm's refresh landing near-simultaneously)
237    /// could interleave so the thread that *read* first but *wrote*
238    /// second overwrites a fresher value the other thread already wrote —
239    /// the cache regresses to a stale snapshot even though a newer read
240    /// already happened. Locking around the whole sequence (safe here
241    /// because `compute_status` is synchronous and cheap — see the `cache`
242    /// field's own doc comment) makes "last writer wins" and "last reader
243    /// wins" the same thing, which is what single-flight is supposed to
244    /// guarantee.
245    pub fn status(&self, block_id: &str) -> ProcessStatus {
246        let mut cache = self.cache.lock();
247        let fresh = compute_status(block_id);
248        // Never cache (or emit a change event for) a block with no real
249        // controller — `list()`'s own callers only ever pass real,
250        // discovered block_ids (from `get_all_controllers()`), but this
251        // broker is also reachable directly with caller-supplied input via
252        // `muxspect describe` (crates/srv/src/server/muxspect_handlers.rs)
253        // — the first RPC-adjacent surface to call `status()` with an
254        // arbitrary string rather than one already known to exist. Without
255        // this guard, repeated queries for distinct nonexistent block_ids
256        // would grow this cache unboundedly, since `forget()` is only ever
257        // called from real controller teardown and never sees IDs that were
258        // never real to begin with (reagent + codex, independently, on
259        // PR #2380).
260        if fresh.lifecycle == Lifecycle::Unknown {
261            drop(cache);
262            return fresh;
263        }
264        let changed = cache
265            .get(block_id)
266            .map(|prev| {
267                prev.lifecycle != fresh.lifecycle || prev.processes.len() != fresh.processes.len()
268            })
269            .unwrap_or(true);
270        cache.insert(block_id.to_string(), fresh.clone());
271        drop(cache);
272        if changed {
273            self.emit_changed(&fresh);
274        }
275        fresh
276    }
277
278    /// The missing batch query (report §5.4) — replaces both
279    /// `agent.tracked-blocks`'s `.chain()` of two independent registries
280    /// and the N sequential single-block `GetControllerStatus` calls
281    /// Swarm's `subscribeToBlockStatuses` issues today with one call.
282    /// Discovery source is `blockcontroller::get_all_controllers` —
283    /// authoritative for every controller type, closing the coverage gap
284    /// `process_tracker` alone has for `shell`/`acp` blocks (report §1).
285    ///
286    /// Returns EVERY controller-backed block — plain `shell`/`cmd`
287    /// terminals included, not just agent panes. Use `list_agent_panes()`
288    /// for the agent-scoped subset (which is what `agent.tracked-blocks`
289    /// actually needs — see that method's doc comment).
290    pub fn list(&self) -> Vec<ProcessStatus> {
291        blockcontroller::get_all_controllers()
292            .into_keys()
293            .map(|block_id| self.status(&block_id))
294            .collect()
295    }
296
297    /// Agent-scoped subset of `list()`. `agent.tracked-blocks`'s original
298    /// (pre-broker) implementation was implicitly agent-only — the two
299    /// registries it unioned (`process_tracker`, populated only by
300    /// agent-CLI controller types, and `reactive`'s registration list,
301    /// populated only via `register_agent`) never included a plain
302    /// terminal. `list()` alone loses that scoping because
303    /// `get_all_controllers()` is controller-type-agnostic by design
304    /// (reagent/codex P1 on #2273 — an earlier version of this PR fed
305    /// `list()` straight into `agent.tracked-blocks`, which made every
306    /// open terminal pane show up in Swarm mislabeled as an "Agent").
307    /// See `ProcessStatus::is_agent` for the exact classification rule.
308    pub fn list_agent_panes(&self) -> Vec<ProcessStatus> {
309        self.list().into_iter().filter(|s| s.is_agent()).collect()
310    }
311
312    /// Drop a block from the cache. Call on pane close so `list()` doesn't
313    /// keep serving a stale entry for a block whose controller is gone —
314    /// `compute_status` would report `Lifecycle::Unknown` for it on the
315    /// next `status()` call regardless, but a closed pane shouldn't appear
316    /// in `list()` (sourced from `get_all_controllers()`, which already
317    /// won't include it) while a stale cache entry lingers unreachable.
318    pub fn forget(&self, block_id: &str) {
319        self.cache.lock().remove(block_id);
320    }
321
322    /// Test-only: current cache size, to prove unknown/nonexistent
323    /// block_ids never get inserted (see `status()`'s own guard and the
324    /// regression test below).
325    #[cfg(test)]
326    fn cache_len(&self) -> usize {
327        self.cache.lock().len()
328    }
329
330    fn emit_changed(&self, status: &ProcessStatus) {
331        let Some(ref broker) = self.mps_broker else {
332            return;
333        };
334        broker.publish_event::<crate::backend::mps_events::ProcessStatusChanged>(status, vec![format!("block:{}", status.block_id)], 0);
335    }
336
337    /// Announce that `list()`/`list_agent_panes()` membership may have
338    /// changed — i.e. `blockcontroller::register_controller`/
339    /// `delete_controller` just ran. Unscoped (no `block:<id>`, unlike
340    /// `emit_changed` above): this is "recompute your list," not a status
341    /// update for one already-known block, so there is no single block
342    /// scope to attach it to.
343    ///
344    /// Exists because `agent.tracked-blocks`'s only data source
345    /// (`CONTROLLER_REGISTRY`) never announced its own writes — Swarm's
346    /// `agent.tracked-blocks` list was refreshed only by two *different*,
347    /// independently-timed mechanisms standing in as proxies
348    /// (`process_tracker`'s 2s poll-and-diff loop, and `reactive`'s own
349    /// registration events), neither directly coupled to when a controller
350    /// actually got registered or removed. That gap let restored agent
351    /// panes' controllers register successfully (confirmed via
352    /// `resync_controller`'s own logging) while Swarm's client-side list —
353    /// fetched once at mount, refreshed only by those two proxies — stayed
354    /// stale indefinitely for any block whose proxy signal didn't happen to
355    /// fire. See docs/reports/REPORT_SWARM_MOUNT_DEPENDENT_TRACKING_GAP_2026_09_15.md.
356    pub fn emit_tracked_blocks_changed(&self) {
357        let Some(ref broker) = self.mps_broker else {
358            return;
359        };
360        broker.publish_event::<crate::backend::mps_events::TrackedBlocksChanged>(&(), vec![], 0);
361    }
362}
363
364static GLOBAL: OnceLock<Arc<ProcessBroker>> = OnceLock::new();
365
366pub fn set_global(broker: Arc<ProcessBroker>) {
367    let _ = GLOBAL.set(broker);
368}
369
370pub fn global() -> Option<Arc<ProcessBroker>> {
371    GLOBAL.get().cloned()
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    fn status_with(shellprocstatus: &str, turn_active: bool, exit_code: i32) -> BlockControllerRuntimeStatus {
379        BlockControllerRuntimeStatus {
380            shellprocstatus: shellprocstatus.to_string(),
381            turn_active,
382            shellprocexitcode: exit_code,
383            ..Default::default()
384        }
385    }
386
387    fn process_status_with(controller_type: &str, is_agent_pane: bool) -> ProcessStatus {
388        ProcessStatus {
389            block_id: "test-block".to_string(),
390            lifecycle: Lifecycle::Idle,
391            processes: Vec::new(),
392            liveness_confidence: TrackingConfidence::None,
393            controller_type: controller_type.to_string(),
394            is_agent_pane,
395            last_computed_ms: 0,
396            controller_status: None,
397        }
398    }
399
400    #[test]
401    fn subprocess_controller_is_always_agent_even_when_is_agent_pane_is_false() {
402        // reagent/codex P1 on #2273: SubprocessController unconditionally
403        // reports is_agent_pane: false in its own runtime status (see
404        // subprocess/mod.rs) despite existing only for agent CLIs — is_agent()
405        // must not rely on the flag for this controller type.
406        let status = process_status_with(blockcontroller::BLOCK_CONTROLLER_SUBPROCESS, false);
407        assert!(status.is_agent());
408    }
409
410    #[test]
411    fn persistent_and_acp_controllers_are_always_agent() {
412        for ty in [
413            blockcontroller::BLOCK_CONTROLLER_PERSISTENT,
414            blockcontroller::BLOCK_CONTROLLER_ACP,
415            blockcontroller::BLOCK_CONTROLLER_MSP,
416        ] {
417            let status = process_status_with(ty, false);
418            assert!(status.is_agent(), "{ty} should always classify as agent");
419        }
420    }
421
422    #[test]
423    fn shell_and_cmd_controllers_defer_to_the_real_is_agent_pane_flag() {
424        for ty in [
425            blockcontroller::BLOCK_CONTROLLER_SHELL,
426            blockcontroller::BLOCK_CONTROLLER_CMD,
427        ] {
428            assert!(
429                !process_status_with(ty, false).is_agent(),
430                "{ty} with is_agent_pane=false must not classify as agent (this is the exact regression reagent/codex caught — a plain terminal wrongly showing up in Swarm as an agent)"
431            );
432            assert!(
433                process_status_with(ty, true).is_agent(),
434                "{ty} with is_agent_pane=true (agent running inside a terminal) must classify as agent"
435            );
436        }
437    }
438
439    #[test]
440    fn unknown_block_is_never_classified_as_agent() {
441        let status = ProcessStatus::unknown("no-such-block");
442        assert!(!status.is_agent());
443    }
444
445    #[test]
446    fn active_turn_is_running_regardless_of_shellprocstatus() {
447        let status = status_with(blockcontroller::STATUS_RUNNING, true, 0);
448        assert_eq!(lifecycle_from(&status), Lifecycle::Running);
449    }
450
451    #[test]
452    fn running_without_active_turn_is_idle() {
453        let status = status_with(blockcontroller::STATUS_RUNNING, false, 0);
454        assert_eq!(lifecycle_from(&status), Lifecycle::Idle);
455    }
456
457    #[test]
458    fn init_is_idle() {
459        let status = status_with(blockcontroller::STATUS_INIT, false, 0);
460        assert_eq!(lifecycle_from(&status), Lifecycle::Idle);
461    }
462
463    #[test]
464    fn done_with_zero_exit_code_is_done() {
465        let status = status_with(blockcontroller::STATUS_DONE, false, 0);
466        assert_eq!(lifecycle_from(&status), Lifecycle::Done);
467    }
468
469    #[test]
470    fn done_with_nonzero_exit_code_is_error() {
471        let status = status_with(blockcontroller::STATUS_DONE, false, 1);
472        assert_eq!(lifecycle_from(&status), Lifecycle::Error);
473    }
474
475    #[test]
476    fn unrecognized_shellprocstatus_is_unknown() {
477        let status = status_with("some-future-status", false, 0);
478        assert_eq!(lifecycle_from(&status), Lifecycle::Unknown);
479    }
480
481    #[test]
482    fn status_of_a_block_with_no_controller_is_unknown() {
483        let broker = ProcessBroker::new(None);
484        let status = broker.status("no-such-block-id");
485        assert_eq!(status.lifecycle, Lifecycle::Unknown);
486        assert!(status.processes.is_empty());
487    }
488
489    #[test]
490    fn unknown_block_ids_are_never_cached_unbounded_growth_guard() {
491        // reagent + codex, independently, on PR #2380: `muxspect describe`
492        // is the first caller to reach `status()` with arbitrary,
493        // caller-supplied block_ids rather than ones already known to be
494        // real (list()'s own callers only ever pass IDs from
495        // get_all_controllers()). Without this guard, a loop probing
496        // distinct nonexistent block_ids would grow the cache forever,
497        // since forget() only ever fires from real controller teardown.
498        let broker = ProcessBroker::new(None);
499        for i in 0..50 {
500            let _ = broker.status(&format!("garbage-block-{i}"));
501        }
502        assert_eq!(broker.cache_len(), 0, "unknown block_ids must never be cached");
503    }
504
505    #[test]
506    fn ten_concurrent_callers_for_the_same_block_all_get_a_consistent_answer() {
507        // Not a call-count assertion (unlike the credential broker's
508        // analogous test — that one collapses concurrent refreshes onto
509        // one actual call; this one recomputes on every call by design,
510        // report §5.1, since the underlying reads are cheap in-memory
511        // lookups, not an expensive operation worth collapsing). What must
512        // hold is that concurrent callers across real OS threads never
513        // observe a torn/partial write to the shared cache.
514        let broker = Arc::new(ProcessBroker::new(None));
515        let handles: Vec<_> = (0..10)
516            .map(|_| {
517                let broker = broker.clone();
518                std::thread::spawn(move || broker.status("some-block"))
519            })
520            .collect();
521        for h in handles {
522            let status = h.join().unwrap();
523            assert_eq!(status.lifecycle, Lifecycle::Unknown);
524        }
525    }
526
527    #[test]
528    fn forget_does_not_panic_on_an_untracked_block() {
529        let broker = ProcessBroker::new(None);
530        broker.forget("never-seen-this-block");
531    }
532
533    #[test]
534    fn list_block_ids_exactly_match_the_controller_registrys_current_keys() {
535        // CONTROLLER_REGISTRY is a process-wide static shared by every test
536        // in this binary (`cargo test` runs unit tests concurrently in one
537        // process by default), so this can't assert `list()` is empty —
538        // another test running at the same time may have a real controller
539        // registered. What must hold regardless of what else is registered:
540        // list()'s block_ids exactly match get_all_controllers()'s current
541        // keys, with nothing added or dropped in between the two calls.
542        let broker = ProcessBroker::new(None);
543        let mut from_broker: Vec<String> =
544            broker.list().into_iter().map(|s| s.block_id).collect();
545        let mut from_registry: Vec<String> =
546            blockcontroller::get_all_controllers().into_keys().collect();
547        from_broker.sort();
548        from_registry.sort();
549        assert_eq!(from_broker, from_registry);
550    }
551}