Skip to main content

aft_base/
fleet_status.rs

1//! Publisher for AFT's segment on the fleet status-holder plane.
2//!
3//! The holder owns retention and composed rendering. While its route is live,
4//! AFT publishes its project-scoped segment. A live route only proves that a
5//! publisher exists: AFT leaves the agent-facing bar to the holder's host plugin
6//! only while the holder's publish acks show that something is actually reading
7//! the project's scope (see [`FleetStatusClient::reader_present`]).
8
9use std::collections::HashMap;
10use std::path::Path;
11use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
12use std::sync::{Arc, Weak};
13use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
14
15use serde::Deserialize;
16use serde_json::{json, Value};
17use subc_client_rs::{
18    CallOptions, CatalogList, CloseRouteOptions, ConnectionState, ConsumerOptions, ControlPush,
19    PushEvent, RouteCloseReason, RouteHandle, SubcConsumer,
20};
21use subc_protocol::manifest::ProviderRole;
22use subc_protocol::{BindIdentity, RouteTarget};
23use tokio::sync::mpsc;
24use tokio::task::JoinHandle;
25
26const STATUS_CADENCE: Duration = Duration::from_millis(2_500);
27const CATALOG_BACKSTOP: Duration = Duration::from_secs(5 * 60);
28/// How recent the holder's last `status.line` read of a scope must be for AFT
29/// to count it as a live reader. Prefrontal's status stamper polls every 3 s, so
30/// a few of its cadences separate a live renderer from a stale or one-off
31/// diagnostic read.
32const READER_FRESH_WINDOW_MS: u64 = 10_000;
33const DISCOVERY_INITIAL_BACKOFF: Duration = Duration::from_millis(250);
34/// Upper bound of the doubling backoff between failed discoveries or failed
35/// holder route opens. A holder that is restarting is usually back within a
36/// few doublings; one that stays unreachable is asked once a minute rather
37/// than every few seconds.
38const DISCOVERY_MAX_BACKOFF: Duration = Duration::from_secs(60);
39const STATUS_PUBLISH_TTL_MS: u64 = 7_500;
40const STATUS_MODULE: &str = "aft";
41const STATUS_HOLDER_MODULE: &str = crate::prefrontal::MODULE_ID;
42const STATUS_LINE_OPERATION: &str = "status.line";
43
44#[cfg(any(test, feature = "test-support"))]
45#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
46#[cfg_attr(not(test), allow(dead_code))]
47pub(crate) struct StatusLineSegment {
48    pub(crate) module: String,
49    pub(crate) scope: String,
50    pub(crate) text: String,
51}
52
53#[cfg(any(test, feature = "test-support"))]
54#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
55#[cfg_attr(not(test), allow(dead_code))]
56pub(crate) struct StatusLineSnapshot {
57    pub(crate) line: String,
58    pub(crate) segments: Vec<StatusLineSegment>,
59}
60
61#[cfg(any(test, feature = "test-support"))]
62impl StatusLineSnapshot {
63    #[cfg_attr(not(test), allow(dead_code))]
64    fn parse(body: &[u8]) -> Option<Self> {
65        serde_json::from_slice(body).ok()
66    }
67
68    #[cfg_attr(not(test), allow(dead_code))]
69    fn has_foreign_segment(&self) -> bool {
70        self.segments
71            .iter()
72            .any(|segment| segment.module != STATUS_MODULE && !segment.text.is_empty())
73    }
74}
75
76#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
77pub(crate) struct StatusPublishAck {
78    pub(crate) epoch: u64,
79    pub(crate) accepted_revision: u64,
80    /// Holder wall clock (ms since the Unix epoch) at the last `status.line`
81    /// read that named the published scope. Null when nothing has read the
82    /// scope in the holder process; absent from holders that predate the field.
83    /// Both of those mean "no evidence of a reader".
84    #[serde(default)]
85    pub(crate) last_read_at_ms: Option<u64>,
86}
87
88impl StatusPublishAck {
89    fn parse(body: &[u8]) -> Option<Self> {
90        serde_json::from_slice(body).ok()
91    }
92}
93
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
95struct PublishFence {
96    epoch: u64,
97    accepted_revision: u64,
98}
99
100impl PublishFence {
101    fn observe(&mut self, ack: StatusPublishAck) {
102        if ack.epoch > self.epoch
103            || (ack.epoch == self.epoch && ack.accepted_revision >= self.accepted_revision)
104        {
105            self.epoch = ack.epoch;
106            self.accepted_revision = ack.accepted_revision;
107        }
108    }
109}
110
111#[derive(Default)]
112struct ClientState {
113    last_publish_at: HashMap<String, Instant>,
114    publish_fence: PublishFence,
115    /// Per scope: whether the holder's most recent publish ack reported a read
116    /// of that scope within [`READER_FRESH_WINDOW_MS`] of the ack's arrival.
117    reader_fresh_by_scope: HashMap<String, bool>,
118}
119
120impl ClientState {
121    fn forget_route(&mut self) {
122        self.last_publish_at.clear();
123        self.reader_fresh_by_scope.clear();
124    }
125}
126
127fn status_scope(project_root: &Path) -> String {
128    format!("project:{}", project_root.to_string_lossy())
129}
130
131fn unix_now_ms() -> u64 {
132    SystemTime::now()
133        .duration_since(UNIX_EPOCH)
134        .map(|elapsed| elapsed.as_millis() as u64)
135        .unwrap_or_default()
136}
137
138/// Whether an ack received at `ack_at_ms` (AFT's clock) proves a live reader.
139/// A read stamped later than the ack (holder clock ahead of AFT's) counts as
140/// age zero rather than as stale.
141fn read_is_fresh(last_read_at_ms: Option<u64>, ack_at_ms: u64) -> bool {
142    last_read_at_ms
143        .is_some_and(|read_at| ack_at_ms.saturating_sub(read_at) <= READER_FRESH_WINDOW_MS)
144}
145
146struct FleetStatusInner {
147    wire_tx: Option<mpsc::Sender<StatusWireRequest>>,
148    route_live: AtomicBool,
149    state: parking_lot::Mutex<ClientState>,
150    next_revision: AtomicU64,
151    /// The holder routes the dial stopped reopening, oldest first and bounded by
152    /// [`MAX_STOPPED_ROUTES`]. The health report lists them (see
153    /// [`stopped_routes_snapshot`]).
154    stopped_routes: parking_lot::Mutex<Vec<StoppedRoute>>,
155}
156
157/// How many refused session routes one dial remembers. Each refused session is
158/// kept so another session's publish cannot make the dial forget it and open
159/// the refused route again; the bound keeps a long-lived daemon's memory flat.
160const MAX_STOPPED_ROUTES: usize = 64;
161
162impl FleetStatusInner {
163    fn new(wire_tx: Option<mpsc::Sender<StatusWireRequest>>, route_live: bool) -> Self {
164        Self {
165            wire_tx,
166            route_live: AtomicBool::new(route_live),
167            state: parking_lot::Mutex::new(ClientState::default()),
168            next_revision: AtomicU64::new(1),
169            stopped_routes: parking_lot::Mutex::new(Vec::new()),
170        }
171    }
172}
173
174test_support_visibility! {
175/// A holder route the status dial will not open again for one session,
176/// because the holder (or the daemon) refused the open with a code that
177/// subc-protocol classes as terminal: asking again gets the same answer.
178#[derive(Clone, Debug, PartialEq, Eq)]
179pub(crate) struct StoppedRoute {
180    target: String,
181    #[cfg(any(test, feature = "test-support"))]
182    pub session: String,
183    #[cfg(not(any(test, feature = "test-support")))]
184    session: String,
185    harness: String,
186    project_root: String,
187    code: String,
188    message: String,
189    stopped_at_unix_ms: u64,
190}
191}
192
193impl StoppedRoute {
194    fn to_value(&self) -> Value {
195        json!({
196            "component": "fleet_status",
197            "target": self.target,
198            "session": self.session,
199            "harness": self.harness,
200            "project_root": self.project_root,
201            "refusal": { "code": self.code, "message": self.message },
202            "stopped_at_unix_ms": self.stopped_at_unix_ms,
203        })
204    }
205}
206
207/// Every dialing status client in this process, so the health report can list
208/// the routes they stopped reopening. Production has one dial per daemon
209/// connection; dropped clients are pruned whenever the list is touched.
210static DIAL_CLIENTS: parking_lot::Mutex<Vec<Weak<FleetStatusInner>>> =
211    parking_lot::Mutex::new(Vec::new());
212
213fn register_dial_client(inner: &Arc<FleetStatusInner>) {
214    let mut clients = DIAL_CLIENTS.lock();
215    clients.retain(|client| client.strong_count() > 0);
216    clients.push(Arc::downgrade(inner));
217}
218
219/// The holder routes the status dials stopped reopening after a terminal
220/// refusal, one row per route, for the health report's `stopped_routes`.
221pub fn stopped_routes_snapshot() -> Value {
222    let mut clients = DIAL_CLIENTS.lock();
223    clients.retain(|client| client.strong_count() > 0);
224    Value::Array(
225        clients
226            .iter()
227            .filter_map(Weak::upgrade)
228            .flat_map(|client| {
229                client
230                    .stopped_routes
231                    .lock()
232                    .iter()
233                    .map(StoppedRoute::to_value)
234                    .collect::<Vec<_>>()
235            })
236            .collect(),
237    )
238}
239
240test_support_visibility! {
241/// Why opening the holder route failed, as far as retrying it goes.
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub(crate) enum RouteOpenFailure {
244    /// The holder or the daemon refused with a code subc-protocol classes as
245    /// terminal (`error_codes::is_retryable_route_open` is false for it), such
246    /// as a holder whose bind check rejects this session's project.
247    Refused { code: String, message: String },
248    /// A failure a later attempt can get past: a lost connection, a timeout,
249    /// or a holder that is restarting or warming up.
250    Transient(String),
251}
252}
253
254impl RouteOpenFailure {
255    fn from_call_error(error: &subc_client_rs::CallError) -> Self {
256        let refusal = match error {
257            subc_client_rs::CallError::Module(body) => Some(body),
258            other => other.route_open_refusal(),
259        };
260        match refusal {
261            Some(body) if !subc_protocol::error_codes::is_retryable_route_open(&body.code) => {
262                Self::Refused {
263                    code: body.code.clone(),
264                    message: body.message.clone(),
265                }
266            }
267            _ => Self::Transient(error.to_string()),
268        }
269    }
270}
271
272#[derive(Clone)]
273pub struct FleetStatusClient {
274    inner: Arc<FleetStatusInner>,
275}
276
277impl FleetStatusClient {
278    #[cfg(any(test, feature = "test-support"))]
279    pub fn channel(capacity: usize) -> (Self, mpsc::Receiver<StatusWireRequest>) {
280        Self::channel_with_liveness(capacity, true)
281    }
282
283    #[rustfmt::skip]
284    test_support_visibility! {
285
286    pub(crate) fn dial_channel(capacity: usize) -> (Self, mpsc::Receiver<StatusWireRequest>) {
287        Self::channel_with_liveness(capacity, false)
288    }
289    }
290
291    fn channel_with_liveness(
292        capacity: usize,
293        route_live: bool,
294    ) -> (Self, mpsc::Receiver<StatusWireRequest>) {
295        let (wire_tx, wire_rx) = mpsc::channel(capacity);
296        let inner = Arc::new(FleetStatusInner::new(Some(wire_tx), route_live));
297        register_dial_client(&inner);
298        (Self { inner }, wire_rx)
299    }
300
301    pub(crate) fn dormant() -> Self {
302        Self {
303            inner: Arc::new(FleetStatusInner::new(None, false)),
304        }
305    }
306
307    test_support_visibility! {
308    /// The status destination this client has stopped retrying, if one was recorded.
309        #[cfg(any(test, feature = "test-support"))]
310        /// The most recently stopped route.
311        #[cfg_attr(not(test), allow(dead_code))]
312        pub(crate) fn stopped_route(&self) -> Option<StoppedRoute> {
313            self.inner.stopped_routes.lock().last().cloned()
314        }
315    }
316
317    #[cfg(any(test, feature = "test-support"))]
318    #[cfg_attr(not(test), allow(dead_code))]
319    fn stopped_routes(&self) -> Vec<StoppedRoute> {
320        self.inner.stopped_routes.lock().clone()
321    }
322
323    fn record_stopped_route(&self, stopped: StoppedRoute) {
324        let mut routes = self.inner.stopped_routes.lock();
325        routes.retain(|route| {
326            (&route.session, &route.harness, &route.project_root)
327                != (&stopped.session, &stopped.harness, &stopped.project_root)
328        });
329        if routes.len() >= MAX_STOPPED_ROUTES {
330            routes.remove(0);
331        }
332        routes.push(stopped);
333    }
334
335    pub fn set_route_live(&self, route_live: bool) {
336        self.inner.route_live.store(route_live, Ordering::Release);
337        if !route_live {
338            self.inner.state.lock().forget_route();
339        }
340    }
341
342    /// Whether something is reading this project's fleet status line, so the
343    /// holder's composed line (not AFT's own bar) is what the agent sees.
344    ///
345    /// Evidence is the holder's most recent publish ack for the scope: it must
346    /// report a `status.line` read within [`READER_FRESH_WINDOW_MS`] of when AFT
347    /// received that ack. Freshness is judged at ack arrival, not at render
348    /// time, because acks only arrive after publishes and publishes only happen
349    /// on tool results: after any pause of more than the window between two
350    /// tool calls, a render-time age would call a steadily polling reader stale
351    /// and show a duplicate bar. The ack for this call's own publish arrives
352    /// after the decision, so a reader that stops is noticed one result late.
353    pub fn reader_present(&self, project_root: &Path) -> bool {
354        if !self.inner.route_live.load(Ordering::Acquire) {
355            return false;
356        }
357        let scope = status_scope(project_root);
358        self.inner
359            .state
360            .lock()
361            .reader_fresh_by_scope
362            .get(&scope)
363            .copied()
364            .unwrap_or(false)
365    }
366
367    /// Publish AFT's segment when the holder route is live. The return value
368    /// reports route liveness only; it says nothing about whether anything
369    /// reads the published scope (use [`Self::reader_present`] for that).
370    pub fn publish(
371        &self,
372        project_root: &Path,
373        harness: &str,
374        session: &str,
375        aft_text: &str,
376    ) -> bool {
377        let Some(wire_tx) = self.inner.wire_tx.as_ref() else {
378            return false;
379        };
380        crate::runner_status_state::publish(session, aft_text);
381        let route_live = self.inner.route_live.load(Ordering::Acquire);
382        let scope = status_scope(project_root);
383        let now = Instant::now();
384        let revision = {
385            let Some(mut state) = self.inner.state.try_lock() else {
386                return true;
387            };
388            if state
389                .last_publish_at
390                .get(&scope)
391                .is_some_and(|last| now.saturating_duration_since(*last) < STATUS_CADENCE)
392            {
393                return true;
394            }
395            state.last_publish_at.insert(scope.clone(), now);
396            self.inner.next_revision.fetch_add(1, Ordering::Relaxed)
397        };
398
399        let request = StatusWireRequest::publish(
400            Arc::downgrade(&self.inner),
401            project_root,
402            harness,
403            session,
404            &scope,
405            aft_text,
406            revision,
407        );
408        match wire_tx.try_send(request) {
409            Ok(()) => route_live,
410            Err(mpsc::error::TrySendError::Full(_)) => {
411                self.inner.state.lock().last_publish_at.remove(&scope);
412                route_live
413            }
414            Err(mpsc::error::TrySendError::Closed(request)) => {
415                request.complete_unavailable();
416                false
417            }
418        }
419    }
420
421    #[cfg(any(test, feature = "test-support"))]
422    #[cfg_attr(not(test), allow(dead_code))]
423    fn publish_fence(&self) -> PublishFence {
424        self.inner.state.lock().publish_fence
425    }
426}
427
428#[rustfmt::skip]
429test_support_visibility! {
430pub(crate) struct StatusWireRequest {
431    body: Value,
432    project_root: String,
433    harness: String,
434    session: String,
435    client: Weak<FleetStatusInner>,
436}
437}
438
439test_support_visibility! {
440#[derive(Clone, PartialEq, Eq)]
441struct FleetRouteIdentity {
442    project_root: String,
443    harness: String,
444    #[cfg(any(test, feature = "test-support"))]
445    pub session: String,
446    #[cfg(not(any(test, feature = "test-support")))]
447    session: String,
448}
449}
450
451impl StatusWireRequest {
452    fn publish(
453        client: Weak<FleetStatusInner>,
454        project_root: &Path,
455        harness: &str,
456        session: &str,
457        scope: &str,
458        text: &str,
459        revision: u64,
460    ) -> Self {
461        Self {
462            body: json!({
463                "op": "status.publish",
464                "module": STATUS_MODULE,
465                "scope": scope,
466                "text": text,
467                "ttl_ms": STATUS_PUBLISH_TTL_MS,
468                "revision": revision,
469            }),
470            project_root: project_root.to_string_lossy().into_owned(),
471            harness: harness.to_owned(),
472            session: session.to_owned(),
473            client,
474        }
475    }
476
477    pub(crate) fn project_root(&self) -> &str {
478        &self.project_root
479    }
480
481    pub(crate) fn harness(&self) -> &str {
482        &self.harness
483    }
484
485    test_support_visibility! {
486        pub(crate) fn session(&self) -> &str {
487            &self.session
488        }
489    }
490
491    #[rustfmt::skip]
492    test_support_visibility! {
493
494    pub(crate) fn body(&self) -> &Value {
495        &self.body
496    }
497    }
498
499    pub(crate) fn complete_response(self, body: &[u8]) -> bool {
500        let Some(ack) = StatusPublishAck::parse(body) else {
501            self.complete_unavailable();
502            return false;
503        };
504        let Some(client) = self.client.upgrade() else {
505            return true;
506        };
507        let reader_fresh = read_is_fresh(ack.last_read_at_ms, unix_now_ms());
508        let mut state = client.state.lock();
509        state.publish_fence.observe(ack);
510        if let Some(scope) = self.body["scope"].as_str() {
511            state
512                .reader_fresh_by_scope
513                .insert(scope.to_owned(), reader_fresh);
514        }
515        true
516    }
517
518    #[rustfmt::skip]
519    test_support_visibility! {
520
521    pub(crate) fn complete_unavailable(self) {
522        if let Some(client) = self.client.upgrade() {
523            client.route_live.store(false, Ordering::Release);
524            client.state.lock().forget_route();
525        }
526    }
527
528    }
529}
530
531impl From<&StatusWireRequest> for FleetRouteIdentity {
532    fn from(request: &StatusWireRequest) -> Self {
533        Self {
534            project_root: request.project_root().to_owned(),
535            harness: request.harness().to_owned(),
536            session: request.session().to_owned(),
537        }
538    }
539}
540
541/// Connect a management client using the daemon's authenticated subc dial path.
542/// Profile and the status publisher share this helper so there is one client
543/// implementation and one connection-file/authentication behavior.
544///
545/// `owner` is a fixed label naming the caller; it keys the live-connection
546/// gauge that AFT logs per owner.
547pub async fn connect_subc_consumer(
548    owner: &'static str,
549    connection_file: &Path,
550    options: ConsumerOptions,
551) -> Result<SubcConsumer, subc_client_rs::ConsumerError> {
552    crate::registration::connect_consumer(owner, connection_file, options).await
553}
554
555pub fn spawn_fleet_status_dial(
556    connection_file: &Path,
557    capacity: usize,
558) -> (FleetStatusClient, JoinHandle<()>) {
559    if !crate::registration::module_consumer_allowed() {
560        return (FleetStatusClient::dormant(), tokio::spawn(async {}));
561    }
562    let (client, wire_rx) = FleetStatusClient::dial_channel(capacity);
563    let task_client = client.clone();
564    let connection_file = connection_file.to_path_buf();
565    let task = tokio::spawn(async move {
566        run_fleet_status_dial(connection_file, task_client, wire_rx).await;
567    });
568    (client, task)
569}
570
571async fn run_fleet_status_dial(
572    connection_file: std::path::PathBuf,
573    client: FleetStatusClient,
574    mut wire_rx: mpsc::Receiver<StatusWireRequest>,
575) {
576    let Some(first_request) = wire_rx.recv().await else {
577        return;
578    };
579    let route_identity = FleetRouteIdentity::from(&first_request);
580    let mut pending_request = Some(first_request);
581    let mut connect_backoff = DISCOVERY_INITIAL_BACKOFF;
582    let consumer = loop {
583        let options = ConsumerOptions {
584            call_timeout: STATUS_CADENCE,
585            ..ConsumerOptions::default()
586        };
587        match connect_subc_consumer("fleet_status", &connection_file, options).await {
588            Ok(consumer) => break consumer,
589            Err(error) => {
590                client.set_route_live(false);
591                if let Some(request) = pending_request.take() {
592                    request.complete_unavailable();
593                }
594                log::debug!("fleet status dial: consumer connect unavailable: {error}");
595                tokio::time::sleep(connect_backoff).await;
596                connect_backoff = next_discovery_backoff(connect_backoff);
597            }
598        }
599    };
600
601    run_connected_status_dial(consumer, client, wire_rx, route_identity, pending_request).await;
602}
603
604// Keep the dial's discovery and publish loop identical for the real transport and
605// the clock-driven test consumer; the latter can return actual bind errors.
606test_support_visibility! {
607#[cfg_attr(any(test, feature = "test-support"), allow(async_fn_in_trait))]
608trait StatusConsumer {
609    type Route;
610    type CatalogWatch: StatusCatalogWatch;
611
612    fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static);
613    /// The daemon's route-lifecycle notifications, sent on the connection's
614    /// control channel (`route.closing`, `route.closed`, each with a reason).
615    fn control_pushes(&self) -> mpsc::Receiver<ControlPush>;
616    async fn catalog_list(&self) -> Result<CatalogList, String>;
617    async fn catalog_watch(&self) -> Result<Self::CatalogWatch, String>;
618    async fn open_route(
619        &self,
620        target: RouteTarget,
621        identity: BindIdentity,
622    ) -> Result<Self::Route, RouteOpenFailure>;
623    fn push_events(&self, route: &Self::Route) -> Result<mpsc::Receiver<PushEvent>, String>;
624    /// The channel this connection knows the route by, which the daemon's
625    /// route-close pushes name.
626    fn route_channel(&self, route: &Self::Route) -> u16;
627    async fn close_handle(&self, route: &Self::Route) -> Result<(), String>;
628    async fn request(&self, route: &Self::Route, body: Vec<u8>) -> Result<Vec<u8>, String>;
629}
630}
631
632test_support_visibility! {
633#[cfg_attr(any(test, feature = "test-support"), allow(async_fn_in_trait))]
634trait StatusCatalogWatch {
635    async fn next_generation(&mut self) -> Result<Option<u64>, String>;
636}
637}
638
639impl StatusCatalogWatch for subc_client_rs::CatalogSubscription {
640    async fn next_generation(&mut self) -> Result<Option<u64>, String> {
641        self.next()
642            .await
643            .map(|event| event.map(|event| event.generation))
644            .map_err(|error| error.to_string())
645    }
646}
647
648impl StatusConsumer for SubcConsumer {
649    type Route = RouteHandle;
650    type CatalogWatch = subc_client_rs::CatalogSubscription;
651
652    fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static) {
653        SubcConsumer::on_connection_state(self, cb);
654    }
655
656    fn control_pushes(&self) -> mpsc::Receiver<ControlPush> {
657        SubcConsumer::control_pushes(self, CONTROL_PUSH_CAPACITY)
658    }
659
660    async fn catalog_list(&self) -> Result<CatalogList, String> {
661        SubcConsumer::catalog_list(self)
662            .await
663            .map_err(|error| error.to_string())
664    }
665
666    async fn catalog_watch(&self) -> Result<Self::CatalogWatch, String> {
667        SubcConsumer::catalog_watch(self)
668            .await
669            .map_err(|error| error.to_string())
670    }
671
672    async fn open_route(
673        &self,
674        target: RouteTarget,
675        identity: BindIdentity,
676    ) -> Result<Self::Route, RouteOpenFailure> {
677        SubcConsumer::open_route(
678            self,
679            target,
680            identity,
681            CallOptions {
682                ..CallOptions::default()
683            },
684        )
685        .await
686        .map_err(|error| RouteOpenFailure::from_call_error(&error))
687    }
688
689    fn push_events(&self, route: &Self::Route) -> Result<mpsc::Receiver<PushEvent>, String> {
690        SubcConsumer::push_events(self, route).map_err(|error| error.to_string())
691    }
692
693    fn route_channel(&self, route: &Self::Route) -> u16 {
694        route.channel
695    }
696
697    async fn close_handle(&self, route: &Self::Route) -> Result<(), String> {
698        SubcConsumer::close_handle(self, route, CloseRouteOptions::default())
699            .await
700            .map_err(|error| error.to_string())
701    }
702
703    async fn request(&self, route: &Self::Route, body: Vec<u8>) -> Result<Vec<u8>, String> {
704        SubcConsumer::request(self, route, body, CallOptions::default())
705            .await
706            .map_err(|error| error.to_string())
707    }
708}
709
710test_support_visibility! {
711async fn run_connected_status_dial<C: StatusConsumer>(
712    consumer: C,
713    client: FleetStatusClient,
714    mut wire_rx: mpsc::Receiver<StatusWireRequest>,
715    mut route_identity: FleetRouteIdentity,
716    mut pending_request: Option<StatusWireRequest>,
717) {
718    let (connection_state_tx, mut connection_state_rx) = mpsc::unbounded_channel();
719    let connection_state_client = client.clone();
720    consumer.on_connection_state(move |state| {
721        connection_state_client.set_route_live(false);
722        let _ = connection_state_tx.send(state);
723    });
724    let mut control_pushes = Some(consumer.control_pushes());
725    // Set when the daemon closed the holder's routes for a reason that forbids
726    // reopening them (see `close_forbids_reopen`). Cleared when the connection
727    // is restored, since a new daemon connection starts a new route history.
728    let mut reopen_forbidden: Option<String> = None;
729    // The channel of the route the dial opened last. It outlives the route
730    // itself, because the daemon's close push can arrive after the dial has
731    // already let the route go, and is replaced only by the next open.
732    let mut last_route_channel: Option<u16> = None;
733    // Every identity the holder refused to open the route for with a terminal
734    // code, oldest first. The dial never opens a route for a listed identity
735    // again; a publish from an unlisted session, project or harness gets its
736    // own single attempt. Keeping the whole list (not only the last refusal)
737    // matters because all sessions share this dial: alternating publishes from
738    // two refused sessions must not take turns reopening each other's route.
739    // A daemon reconnect does not clear it: the holder, not the connection,
740    // made the decision.
741    let mut refused_identities: std::collections::VecDeque<FleetRouteIdentity> =
742        std::collections::VecDeque::new();
743
744    let mut route: Option<C::Route> = None;
745    let mut route_events = None;
746    let mut catalog_watch = None;
747    let mut catalog_generation = None;
748    let mut next_watch_at = tokio::time::Instant::now();
749    let mut next_discovery_at = tokio::time::Instant::now();
750    let mut discovery_backoff = DISCOVERY_INITIAL_BACKOFF;
751    loop {
752        if catalog_watch.is_none() && tokio::time::Instant::now() >= next_watch_at {
753            match consumer.catalog_watch().await {
754                Ok(watch) => {
755                    catalog_watch = Some(watch);
756                    // A replacement feed cannot account for generations missed
757                    // while it was down, even if its first generation is unchanged.
758                    next_discovery_at = tokio::time::Instant::now();
759                }
760                Err(error) => {
761                    log::debug!("fleet status dial: catalog watch unavailable: {error}");
762                    next_watch_at = tokio::time::Instant::now() + STATUS_CADENCE;
763                }
764            }
765        }
766        let discovery_cadence = if catalog_watch.is_some() {
767            CATALOG_BACKSTOP
768        } else {
769            STATUS_CADENCE
770        };
771        if tokio::time::Instant::now() >= next_discovery_at {
772            let catalog = consumer.catalog_list().await;
773            match catalog {
774                Ok(catalog) if status_holder(&catalog.modules).is_some() => {
775                    let holder = STATUS_HOLDER_MODULE;
776                    catalog_generation = Some(catalog.generation);
777                    if route.is_none()
778                        && reopen_forbidden.is_none()
779                        && !refused_identities.contains(&route_identity)
780                    {
781                        // `BindIdentity::new` leaves the registered project id
782                        // unset: the dial has no resolved id to send.
783                        let identity = BindIdentity::new(
784                            route_identity.harness.clone(),
785                            route_identity.session.clone(),
786                        );
787                        match consumer
788                            .open_route(
789                                RouteTarget::ManagementSurface {
790                                    module_id: holder.to_string(),
791                                },
792                                identity,
793                            )
794                            .await
795                        {
796                            Ok(opened_route) => match consumer.push_events(&opened_route) {
797                                Ok(events) => {
798                                    route_events = Some(events);
799                                    last_route_channel =
800                                        Some(consumer.route_channel(&opened_route));
801                                    route = Some(opened_route);
802                                    discovery_backoff = DISCOVERY_INITIAL_BACKOFF;
803                                }
804                                Err(error) => {
805                                    log::debug!(
806                                        "fleet status dial: route event registration unavailable: {error}"
807                                    );
808                                    client.set_route_live(false);
809                                }
810                            },
811                            Err(RouteOpenFailure::Refused { code, message }) => {
812                                log::warn!(
813                                    "fleet status dial: {holder} refused the status route for session {} (harness {}, project {}): {code}: {message}; not reopening it for this session",
814                                    route_identity.session,
815                                    route_identity.harness,
816                                    route_identity.project_root,
817                                );
818                                client.record_stopped_route(StoppedRoute {
819                                    target: holder.to_string(),
820                                    session: route_identity.session.clone(),
821                                    harness: route_identity.harness.clone(),
822                                    project_root: route_identity.project_root.clone(),
823                                    code,
824                                    message,
825                                    stopped_at_unix_ms: unix_now_ms(),
826                                });
827                                if refused_identities.len() >= MAX_STOPPED_ROUTES {
828                                    refused_identities.pop_front();
829                                }
830                                refused_identities.push_back(route_identity.clone());
831                                client.set_route_live(false);
832                            }
833                            Err(RouteOpenFailure::Transient(error)) => {
834                                // Log the first failure of a run at info so the
835                                // AFT log shows the route is down; the retries
836                                // after it log at debug.
837                                if discovery_backoff == DISCOVERY_INITIAL_BACKOFF {
838                                    log::info!(
839                                        "fleet status dial: {holder} route unavailable for session {}: {error}; retrying with backoff",
840                                        route_identity.session,
841                                    );
842                                } else {
843                                    log::debug!("fleet status dial: route unavailable: {error}");
844                                }
845                                client.set_route_live(false);
846                            }
847                        }
848                    }
849                    client.set_route_live(route.is_some());
850                    if route.is_some()
851                        || reopen_forbidden.is_some()
852                        || refused_identities.contains(&route_identity)
853                    {
854                        next_discovery_at = tokio::time::Instant::now() + discovery_cadence;
855                    } else {
856                        // A transient route-open failure keeps its existing retry
857                        // backoff even with a healthy watch: recovery need not
858                        // advance the catalog generation.
859                        next_discovery_at = tokio::time::Instant::now() + discovery_backoff;
860                        discovery_backoff = next_discovery_backoff(discovery_backoff);
861                    }
862                }
863                Ok(catalog) => {
864                    catalog_generation = Some(catalog.generation);
865                    if let Some(opened_route) = route.take() {
866                        let _ = consumer.close_handle(&opened_route).await;
867                    }
868                    route_events = None;
869                    client.set_route_live(false);
870                    discovery_backoff = DISCOVERY_INITIAL_BACKOFF;
871                    next_discovery_at = tokio::time::Instant::now() + discovery_cadence;
872                }
873                Err(error) => {
874                    route = None;
875                    route_events = None;
876                    client.set_route_live(false);
877                    log::debug!("fleet status dial: catalog unavailable: {error}");
878                    next_discovery_at = tokio::time::Instant::now() + discovery_backoff;
879                    discovery_backoff = next_discovery_backoff(discovery_backoff);
880                }
881            }
882        }
883
884        if let Some(request) = pending_request.take() {
885            if route.is_none() {
886                let requested = FleetRouteIdentity::from(&request);
887                if requested != route_identity
888                    && refused_identities.contains(&route_identity)
889                    && !refused_identities.contains(&requested)
890                {
891                    // The refusal was about the identity the route was opened
892                    // under, not about every session: open once for this one.
893                    // The earlier refusal stays listed and stays in force.
894                    route_identity = requested;
895                    discovery_backoff = DISCOVERY_INITIAL_BACKOFF;
896                    next_discovery_at = tokio::time::Instant::now();
897                    pending_request = Some(request);
898                    continue;
899                }
900            }
901            let Some(opened_route) = route.as_ref() else {
902                request.complete_unavailable();
903                continue;
904            };
905            let body = match encode_status_publish_call(request.body()) {
906                Some(body) => body,
907                None => {
908                    request.complete_unavailable();
909                    continue;
910                }
911            };
912            match consumer.request(opened_route, body).await {
913                Ok(response) => {
914                    if !complete_status_publish_call(request, &response) {
915                        route = None;
916                        route_events = None;
917                        client.set_route_live(false);
918                        next_discovery_at = tokio::time::Instant::now();
919                    }
920                }
921                Err(error) => {
922                    log::debug!("fleet status dial: publish unavailable: {error}");
923                    request.complete_unavailable();
924                    route = None;
925                    route_events = None;
926                    client.set_route_live(false);
927                    next_discovery_at = tokio::time::Instant::now();
928                }
929            }
930            continue;
931        }
932
933        let next_wake_at = if catalog_watch.is_some() {
934            next_discovery_at
935        } else {
936            next_discovery_at.min(next_watch_at)
937        };
938        tokio::select! {
939            maybe_request = wire_rx.recv() => {
940                let Some(request) = maybe_request else {
941                    client.set_route_live(false);
942                    return;
943                };
944                pending_request = Some(request);
945            }
946            maybe_state = connection_state_rx.recv() => {
947                match maybe_state {
948                    Some(state @ (ConnectionState::Dropped | ConnectionState::Restored { .. })) => {
949                        if matches!(state, ConnectionState::Restored { .. }) {
950                            reopen_forbidden = None;
951                        }
952                        // A new connection numbers its channels afresh.
953                        last_route_channel = None;
954                        route = None;
955                        route_events = None;
956                        catalog_watch = None;
957                        catalog_generation = None;
958                        next_watch_at = tokio::time::Instant::now();
959                        client.set_route_live(false);
960                        next_discovery_at = tokio::time::Instant::now();
961                    }
962                    None => {}
963                }
964            }
965            maybe_push = async {
966                control_pushes
967                    .as_mut()
968                    .expect("control push receiver guarded by select condition")
969                    .recv()
970                    .await
971            }, if control_pushes.is_some() => {
972                match maybe_push {
973                    Some(push) => {
974                        if record_forbidden_reopen(&push, last_route_channel, &mut reopen_forbidden) {
975                            route = None;
976                            route_events = None;
977                            client.set_route_live(false);
978                        }
979                    }
980                    None => control_pushes = None,
981                }
982            }
983            maybe_event = async {
984                route_events
985                    .as_mut()
986                    .expect("route event receiver guarded by select condition")
987                    .recv()
988                    .await
989            }, if route_events.is_some() => {
990                if maybe_event.is_none() {
991                    // The daemon sends `route.closed` before it ends the route,
992                    // so its reason is already queued: read it before deciding
993                    // whether the next discovery may reopen.
994                    if let Some(receiver) = control_pushes.as_mut() {
995                        while let Ok(push) = receiver.try_recv() {
996                            record_forbidden_reopen(&push, last_route_channel, &mut reopen_forbidden);
997                        }
998                    }
999                    route = None;
1000                    route_events = None;
1001                    client.set_route_live(false);
1002                    next_discovery_at = tokio::time::Instant::now();
1003                }
1004            }
1005            generation = async {
1006                catalog_watch.as_mut().expect("watch guarded by select condition")
1007                    .next_generation().await
1008            }, if catalog_watch.is_some() => {
1009                match generation {
1010                    Ok(Some(generation)) => {
1011                        if catalog_generation.is_none_or(|known| generation > known) {
1012                            next_discovery_at = tokio::time::Instant::now();
1013                        }
1014                    }
1015                    Ok(None) | Err(_) => {
1016                        catalog_watch = None;
1017                        next_watch_at = tokio::time::Instant::now() + STATUS_CADENCE;
1018                        next_discovery_at = next_discovery_at.min(next_watch_at);
1019                    }
1020                }
1021            }
1022            _ = tokio::time::sleep_until(next_wake_at) => {}
1023        }
1024    }
1025}
1026}
1027
1028fn encode_status_publish_call(body: &Value) -> Option<Vec<u8>> {
1029    let mut params = body.as_object()?.clone();
1030    let method = params.remove("op")?.as_str()?.to_owned();
1031    if method != "status.publish" {
1032        return None;
1033    }
1034    serde_json::to_vec(&json!({
1035        "method": method,
1036        "params": params,
1037    }))
1038    .ok()
1039}
1040
1041fn complete_status_publish_call(request: StatusWireRequest, body: &[u8]) -> bool {
1042    let result = serde_json::from_slice::<Value>(body)
1043        .ok()
1044        .and_then(|response| response.get("result").cloned())
1045        .and_then(|result| serde_json::to_vec(&result).ok());
1046    let Some(result) = result else {
1047        request.complete_unavailable();
1048        return false;
1049    };
1050    request.complete_response(&result)
1051}
1052
1053fn status_holder(entries: &[subc_client_rs::CatalogEntry]) -> Option<&'static str> {
1054    entries
1055        .iter()
1056        .any(|entry| {
1057            entry.module_id == STATUS_HOLDER_MODULE && entry.roles.iter().any(|role| {
1058            matches!(
1059                role,
1060                ProviderRole::ManagementSurface { operations, .. }
1061                    if operations.iter().any(|operation| operation.name == STATUS_LINE_OPERATION)
1062            )
1063        })
1064        })
1065        .then_some(STATUS_HOLDER_MODULE)
1066}
1067
1068/// Room for the daemon's control pushes between two turns of the dial loop.
1069/// They are rare (one per route close), and a full queue only drops advisory
1070/// pushes, so a small bound is enough.
1071const CONTROL_PUSH_CAPACITY: usize = 16;
1072
1073/// Whether a route-close reason forbids reopening the route. A scope close
1074/// (`scope_ended`, `scope_carrier_removed`, `scope_delegation_changed`,
1075/// `scope_parent_ended`) means the work the route belonged to is over, and a
1076/// reason this build does not know may mean the same, so neither may bring the
1077/// route back. The reasons the dial already handled (reload, restart, crash,
1078/// disable, capability_denied) keep their behaviour: the next discovery reopens
1079/// when the holder is advertised again.
1080fn close_forbids_reopen(reason: &str) -> bool {
1081    // Authority changes retire this route, not its scope: rediscovery may open
1082    // a fresh route under the daemon's current authority. Only a definite
1083    // scope.describe answer may end the scope itself.
1084    if matches!(
1085        RouteCloseReason::from_wire(reason),
1086        RouteCloseReason::AuthorityChanged
1087    ) {
1088        return false;
1089    }
1090    reason.starts_with("scope_")
1091        || matches!(
1092            RouteCloseReason::from_wire(reason),
1093            RouteCloseReason::Unknown(_)
1094        )
1095}
1096
1097/// Whether a route-close push is about the route the dial opened last.
1098///
1099/// A daemon on subc-control 0.27 or later names the client channels a close
1100/// covers, so a late push for a route the dial has since replaced cannot end
1101/// the new one. An older daemon names none; then the holder's module id alone
1102/// decides, as it always has.
1103fn push_names_dial_route(push: &ControlPush, last_route_channel: Option<u16>) -> bool {
1104    let channels: Vec<u64> = push
1105        .body
1106        .get("channels")
1107        .and_then(Value::as_array)
1108        .map(|channels| channels.iter().filter_map(Value::as_u64).collect())
1109        .unwrap_or_default();
1110    channels.is_empty()
1111        || last_route_channel.is_some_and(|channel| channels.contains(&u64::from(channel)))
1112}
1113
1114/// Note a `route.closed` / `route.closing` push for the status holder's route
1115/// whose reason forbids reopening. Returns true when it did.
1116fn record_forbidden_reopen(
1117    push: &ControlPush,
1118    last_route_channel: Option<u16>,
1119    reopen_forbidden: &mut Option<String>,
1120) -> bool {
1121    if !push
1122        .body
1123        .get("module_id")
1124        .and_then(Value::as_str)
1125        .is_some_and(crate::prefrontal::is_module)
1126    {
1127        return false;
1128    }
1129    if !push_names_dial_route(push, last_route_channel) {
1130        return false;
1131    }
1132    let Some(reason) = push
1133        .route_close_reason()
1134        .and_then(|_| push.body.get("reason").and_then(Value::as_str))
1135    else {
1136        return false;
1137    };
1138    if !close_forbids_reopen(reason) {
1139        return false;
1140    }
1141    log::info!("fleet status dial: holder route closed ({reason}); not reopening it");
1142    *reopen_forbidden = Some(reason.to_owned());
1143    true
1144}
1145
1146fn next_discovery_backoff(current: Duration) -> Duration {
1147    current
1148        .checked_mul(2)
1149        .unwrap_or(DISCOVERY_MAX_BACKOFF)
1150        .min(DISCOVERY_MAX_BACKOFF)
1151}
1152
1153#[cfg(any(test, feature = "test-support"))]
1154#[allow(dead_code, unused_imports)]
1155pub mod tests {
1156    use super::*;
1157    #[cfg(test)]
1158    use serde_json::Map;
1159    #[cfg(test)]
1160    use std::collections::HashSet;
1161    use subc_protocol::manifest::{ManagementOperation, ManagementOperationKind};
1162
1163    #[cfg(test)]
1164    const FIXTURES: &str =
1165        include_str!("../../aft/tests/fixtures/status_line/status-line-fixtures-2026-08-14.json");
1166    #[cfg(test)]
1167    const PUBLISH_ACK_FIXTURES: [&str; 9] = [
1168        "publish_aft",
1169        "supersede_r3",
1170        "supersede_r2_late",
1171        "ttl_publish",
1172        "quiet_publish_empty_text",
1173        "fat1",
1174        "fat2",
1175        "epoch_bump_republish_r1_new_conn",
1176        "publish_aft_project",
1177    ];
1178    #[cfg(test)]
1179    const LINE_REPLY_FIXTURES: [&str; 9] = [
1180        "line_foreign_present",
1181        "supersede_line_after_r3",
1182        "supersede_line_after_late_r2",
1183        "ttl_line_before",
1184        "ttl_line_after_expiry",
1185        "quiet_line",
1186        "line_cap_overflow",
1187        "epoch_bump_line_after",
1188        "line_aft_solo_scope",
1189    ];
1190
1191    #[cfg(test)]
1192    fn fixtures() -> Map<String, Value> {
1193        serde_json::from_str::<Value>(FIXTURES)
1194            .expect("producer fixture JSON")
1195            .as_object()
1196            .expect("producer fixture object")
1197            .clone()
1198    }
1199
1200    #[cfg(test)]
1201    fn parse_line(value: &Value) -> StatusLineSnapshot {
1202        StatusLineSnapshot::parse(&serde_json::to_vec(value).expect("fixture bytes"))
1203            .expect("status.line fixture")
1204    }
1205
1206    #[cfg(test)]
1207    fn parse_ack(value: &Value) -> StatusPublishAck {
1208        StatusPublishAck::parse(&serde_json::to_vec(value).expect("fixture bytes"))
1209            .expect("status.publish fixture")
1210    }
1211
1212    fn status_catalog_entry(module_id: &str, operation: &str) -> subc_client_rs::CatalogEntry {
1213        serde_json::from_value(json!({
1214            "module_id": module_id,
1215            "ready": true,
1216            "roles": [ProviderRole::ManagementSurface {
1217                operations: vec![ManagementOperation {
1218                    name: operation.to_string(),
1219                    kind: ManagementOperationKind::Query,
1220                    description: None,
1221                }],
1222                config_schema: Value::Null,
1223                observability: Vec::new(),
1224                identity_scope: Vec::new(),
1225                concurrency: Default::default(),
1226            }],
1227            "control_ops": [],
1228        }))
1229        .unwrap()
1230    }
1231
1232    #[derive(Default)]
1233    pub struct FakeCatalogWatch {
1234        available: std::sync::atomic::AtomicBool,
1235        legacy_only: std::sync::atomic::AtomicBool,
1236        targets: parking_lot::Mutex<Vec<String>>,
1237        generation: AtomicU64,
1238        sender: parking_lot::Mutex<Option<mpsc::Sender<u64>>>,
1239    }
1240
1241    impl StatusCatalogWatch for mpsc::Receiver<u64> {
1242        async fn next_generation(&mut self) -> Result<Option<u64>, String> {
1243            Ok(self.recv().await)
1244        }
1245    }
1246
1247    pub struct RejectingConsumer {
1248        pub attempts: Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
1249        pub advertises_status_line: bool,
1250        pub catalog_calls: Arc<AtomicU64>,
1251        pub publish_calls: Arc<AtomicU64>,
1252        pub succeeds_on: Option<usize>,
1253        pub failure: RouteOpenFailure,
1254        pub connection_callback:
1255            Arc<parking_lot::Mutex<Option<Box<dyn Fn(ConnectionState) + Send>>>>,
1256        pub push_sender: Arc<parking_lot::Mutex<Option<mpsc::Sender<PushEvent>>>>,
1257        pub control_sender: Arc<parking_lot::Mutex<Option<mpsc::Sender<ControlPush>>>>,
1258        pub watch: Arc<FakeCatalogWatch>,
1259    }
1260
1261    impl StatusConsumer for RejectingConsumer {
1262        type Route = usize;
1263        type CatalogWatch = mpsc::Receiver<u64>;
1264
1265        fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static) {
1266            *self.connection_callback.lock() = Some(Box::new(cb));
1267        }
1268
1269        fn control_pushes(&self) -> mpsc::Receiver<ControlPush> {
1270            let (tx, rx) = mpsc::channel(CONTROL_PUSH_CAPACITY);
1271            *self.control_sender.lock() = Some(tx);
1272            rx
1273        }
1274
1275        async fn catalog_list(&self) -> Result<CatalogList, String> {
1276            self.catalog_calls.fetch_add(1, Ordering::Relaxed);
1277            Ok(CatalogList {
1278                generation: self.watch.generation.load(Ordering::Relaxed).max(1),
1279                modules: if self.advertises_status_line {
1280                    vec![status_catalog_entry(
1281                        if self.watch.legacy_only.load(Ordering::Relaxed) {
1282                            "prefrontal-core"
1283                        } else {
1284                            STATUS_HOLDER_MODULE
1285                        },
1286                        STATUS_LINE_OPERATION,
1287                    )]
1288                } else {
1289                    Vec::new()
1290                },
1291                subc_ops: Vec::new(),
1292            })
1293        }
1294
1295        async fn catalog_watch(&self) -> Result<Self::CatalogWatch, String> {
1296            if !self.watch.available.load(Ordering::Relaxed) {
1297                return Err("catalog.watch unavailable".into());
1298            }
1299            let (tx, rx) = mpsc::channel(8);
1300            tx.try_send(self.watch.generation.load(Ordering::Relaxed).max(1))
1301                .unwrap();
1302            *self.watch.sender.lock() = Some(tx);
1303            Ok(rx)
1304        }
1305
1306        async fn open_route(
1307            &self,
1308            target: RouteTarget,
1309            _identity: BindIdentity,
1310        ) -> Result<usize, RouteOpenFailure> {
1311            let mut attempts = self.attempts.lock();
1312            if let RouteTarget::ManagementSurface { module_id } = target {
1313                self.watch.targets.lock().push(module_id);
1314            }
1315            attempts.push(tokio::time::Instant::now());
1316            if self.succeeds_on == Some(attempts.len()) {
1317                Ok(attempts.len())
1318            } else {
1319                Err(self.failure.clone())
1320            }
1321        }
1322
1323        fn push_events(&self, _route: &usize) -> Result<mpsc::Receiver<PushEvent>, String> {
1324            let (tx, rx) = mpsc::channel(1);
1325            *self.push_sender.lock() = Some(tx);
1326            Ok(rx)
1327        }
1328
1329        fn route_channel(&self, route: &usize) -> u16 {
1330            u16::try_from(*route).expect("test routes are small")
1331        }
1332
1333        async fn close_handle(&self, _route: &usize) -> Result<(), String> {
1334            Ok(())
1335        }
1336
1337        async fn request(&self, _route: &usize, _body: Vec<u8>) -> Result<Vec<u8>, String> {
1338            self.publish_calls.fetch_add(1, Ordering::Relaxed);
1339            Err("not used in discovery test".to_owned())
1340        }
1341    }
1342
1343    /// A failure the dial may retry: the holder is restarting.
1344    fn transient_failure() -> RouteOpenFailure {
1345        RouteOpenFailure::Transient("route.open refused: module_reloading".to_owned())
1346    }
1347
1348    async fn watch_dial(
1349        succeeds_on: usize,
1350    ) -> (
1351        tokio::task::JoinHandle<()>,
1352        Arc<AtomicU64>,
1353        Arc<FakeCatalogWatch>,
1354        Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
1355    ) {
1356        let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
1357        client.publish(Path::new("/tmp/project"), "opencode", "session", "local");
1358        let request = wire_rx.try_recv().unwrap();
1359        let identity = FleetRouteIdentity::from(&request);
1360        request.complete_unavailable();
1361        let catalog_calls = Arc::new(AtomicU64::new(0));
1362        let watch = Arc::new(FakeCatalogWatch::default());
1363        watch.available.store(true, Ordering::Relaxed);
1364        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
1365        let consumer = RejectingConsumer {
1366            attempts: attempts.clone(),
1367            succeeds_on: Some(succeeds_on),
1368            failure: transient_failure(),
1369            advertises_status_line: true,
1370            catalog_calls: catalog_calls.clone(),
1371            publish_calls: Arc::default(),
1372            connection_callback: Arc::default(),
1373            push_sender: Arc::default(),
1374            control_sender: Arc::default(),
1375            watch: watch.clone(),
1376        };
1377        let task = tokio::spawn(run_connected_status_dial(
1378            consumer, client, wire_rx, identity, None,
1379        ));
1380        settle_dial().await;
1381        assert_eq!(catalog_calls.load(Ordering::Relaxed), 1);
1382        (task, catalog_calls, watch, attempts)
1383    }
1384
1385    async fn settle_dial() {
1386        for _ in 0..8 {
1387            tokio::task::yield_now().await;
1388        }
1389    }
1390
1391    #[tokio::test(start_paused = true)]
1392    async fn status_dial_ignores_the_legacy_advertiser_on_catalog_change() {
1393        let (task, _, watch, _) = watch_dial(1).await;
1394        assert_eq!(*watch.targets.lock(), ["prefrontal"]);
1395        watch.legacy_only.store(true, Ordering::Relaxed);
1396        watch.generation.store(2, Ordering::Relaxed);
1397        watch.sender.lock().as_ref().unwrap().try_send(2).unwrap();
1398        settle_dial().await;
1399        assert_eq!(*watch.targets.lock(), ["prefrontal"]);
1400        task.abort();
1401        let _ = task.await;
1402    }
1403
1404    #[tokio::test(start_paused = true)]
1405    async fn initial_status_discovery_retains_the_queued_publish_cadence() {
1406        let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
1407        client.publish(
1408            Path::new("/queued-project"),
1409            "opencode",
1410            "session",
1411            "status",
1412        );
1413        let request = wire_rx.try_recv().unwrap();
1414        let identity = FleetRouteIdentity::from(&request);
1415        let queued = client.inner.state.lock().last_publish_at.clone();
1416        assert_eq!(queued.len(), 1);
1417        let watch = Arc::new(FakeCatalogWatch::default());
1418        watch.available.store(true, Ordering::Relaxed);
1419        let consumer = RejectingConsumer {
1420            attempts: Arc::default(),
1421            succeeds_on: Some(1),
1422            failure: transient_failure(),
1423            advertises_status_line: true,
1424            catalog_calls: Arc::default(),
1425            publish_calls: Arc::default(),
1426            connection_callback: Arc::default(),
1427            push_sender: Arc::default(),
1428            control_sender: Arc::default(),
1429            watch,
1430        };
1431        let task = tokio::spawn(run_connected_status_dial(
1432            consumer,
1433            client.clone(),
1434            wire_rx,
1435            identity,
1436            None,
1437        ));
1438        settle_dial().await;
1439        assert!(client.inner.route_live.load(Ordering::Acquire));
1440        assert_eq!(client.inner.state.lock().last_publish_at, queued);
1441        task.abort();
1442        let _ = task.await;
1443    }
1444
1445    #[test]
1446    fn status_discovery_and_close_push_accept_only_prefrontal() {
1447        for module in ["prefrontal", "prefrontal-core", "other"] {
1448            let accepted = module == "prefrontal";
1449            assert_eq!(
1450                status_holder(&[status_catalog_entry(module, STATUS_LINE_OPERATION)]),
1451                accepted.then_some(module)
1452            );
1453            let push = ControlPush {
1454                op: "route.closed".into(),
1455                body: json!({"op":"route.closed", "module_id":module, "reason":"scope_ended"}),
1456            };
1457            let mut forbidden = None;
1458            assert_eq!(
1459                record_forbidden_reopen(&push, None, &mut forbidden),
1460                accepted
1461            );
1462        }
1463    }
1464
1465    #[tokio::test(start_paused = true)]
1466    async fn catalog_watch_transient_open_failure_retries_before_backstop() {
1467        let (task, calls, watch, attempts) = watch_dial(2).await;
1468        assert!(watch.sender.lock().is_some());
1469        assert_eq!(attempts.lock().len(), 1);
1470        tokio::time::advance(DISCOVERY_INITIAL_BACKOFF).await;
1471        settle_dial().await;
1472        assert_eq!(attempts.lock().len(), 2, "route recovered on its retry");
1473        assert_eq!(calls.load(Ordering::Relaxed), 2);
1474        tokio::time::advance(Duration::from_secs(30)).await;
1475        settle_dial().await;
1476        assert_eq!(attempts.lock().len(), 2);
1477        assert_eq!(calls.load(Ordering::Relaxed), 2);
1478        task.abort();
1479    }
1480
1481    #[tokio::test(start_paused = true)]
1482    async fn catalog_watch_new_generation_rediscovers_without_waiting_for_a_poll() {
1483        let (task, calls, watch, _) = watch_dial(1).await;
1484        watch.generation.store(2, Ordering::Relaxed);
1485        watch.sender.lock().as_ref().unwrap().try_send(2).unwrap();
1486        settle_dial().await;
1487        assert_eq!(calls.load(Ordering::Relaxed), 2);
1488        task.abort();
1489    }
1490
1491    #[tokio::test(start_paused = true)]
1492    async fn catalog_watch_unchanged_generation_waits_for_five_minute_backstop() {
1493        let (task, calls, watch, _) = watch_dial(1).await;
1494        watch.sender.lock().as_ref().unwrap().try_send(1).unwrap();
1495        for _ in 0..12 {
1496            tokio::time::advance(STATUS_CADENCE).await;
1497            settle_dial().await;
1498        }
1499        assert_eq!(
1500            calls.load(Ordering::Relaxed),
1501            1,
1502            "no discovery in 30 seconds"
1503        );
1504        tokio::time::advance(CATALOG_BACKSTOP - Duration::from_secs(30)).await;
1505        settle_dial().await;
1506        assert_eq!(calls.load(Ordering::Relaxed), 2, "backstop still refreshes");
1507        task.abort();
1508    }
1509
1510    #[tokio::test(start_paused = true)]
1511    async fn catalog_watch_drop_falls_back_to_polling_and_recovers() {
1512        let (task, calls, watch, _) = watch_dial(1).await;
1513        watch.available.store(false, Ordering::Relaxed);
1514        watch.sender.lock().take();
1515        settle_dial().await;
1516        for expected in [2, 3] {
1517            tokio::time::advance(STATUS_CADENCE).await;
1518            settle_dial().await;
1519            assert_eq!(calls.load(Ordering::Relaxed), expected);
1520        }
1521        watch.available.store(true, Ordering::Relaxed);
1522        tokio::time::advance(STATUS_CADENCE).await;
1523        settle_dial().await;
1524        assert_eq!(calls.load(Ordering::Relaxed), 4, "recovery refreshes once");
1525        tokio::time::advance(Duration::from_secs(30)).await;
1526        settle_dial().await;
1527        assert_eq!(
1528            calls.load(Ordering::Relaxed),
1529            4,
1530            "recovered feed stops fast polling"
1531        );
1532        watch.generation.store(3, Ordering::Relaxed);
1533        watch.sender.lock().as_ref().unwrap().try_send(3).unwrap();
1534        settle_dial().await;
1535        assert_eq!(calls.load(Ordering::Relaxed), 5);
1536        task.abort();
1537    }
1538
1539    /// The terminal refusal seen live: prefrontal-core's bind check could not
1540    /// classify the session's project.
1541    fn terminal_refusal() -> RouteOpenFailure {
1542        RouteOpenFailure::Refused {
1543            code: "project_origin_unclassifiable".to_owned(),
1544            message: "the project origin could not be classified".to_owned(),
1545        }
1546    }
1547
1548    async fn dial_with_rejections(
1549        succeeds_on: Option<usize>,
1550    ) -> (
1551        tokio::task::JoinHandle<()>,
1552        Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
1553        Arc<parking_lot::Mutex<Option<Box<dyn Fn(ConnectionState) + Send>>>>,
1554    ) {
1555        let (task, attempts, callback, _client) =
1556            dial_failing_with(succeeds_on, transient_failure(), "session-1").await;
1557        (task, attempts, callback)
1558    }
1559
1560    /// Start a dial whose route opens fail with `failure` (except attempt
1561    /// `succeeds_on`), after a first publish from `session`. Returns the dial
1562    /// task, the open attempt times, the connection-state callback and the
1563    /// client the dial serves.
1564    async fn dial_failing_with(
1565        succeeds_on: Option<usize>,
1566        failure: RouteOpenFailure,
1567        session: &str,
1568    ) -> (
1569        tokio::task::JoinHandle<()>,
1570        Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
1571        Arc<parking_lot::Mutex<Option<Box<dyn Fn(ConnectionState) + Send>>>>,
1572        FleetStatusClient,
1573    ) {
1574        let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
1575        assert!(!client.publish(Path::new("/tmp/project"), "opencode", session, "local"));
1576        let first_request = wire_rx.try_recv().expect("first discovery request");
1577        let identity = FleetRouteIdentity::from(&first_request);
1578        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
1579        let callback = Arc::new(parking_lot::Mutex::new(None));
1580        let consumer = RejectingConsumer {
1581            attempts: attempts.clone(),
1582            advertises_status_line: true,
1583            catalog_calls: Arc::default(),
1584            publish_calls: Arc::default(),
1585            succeeds_on,
1586            failure,
1587            connection_callback: callback.clone(),
1588            push_sender: Arc::default(),
1589            control_sender: Arc::default(),
1590            watch: Arc::default(),
1591        };
1592        let task = tokio::spawn(run_connected_status_dial(
1593            consumer,
1594            client.clone(),
1595            wire_rx,
1596            identity,
1597            Some(first_request),
1598        ));
1599        tokio::task::yield_now().await;
1600        (task, attempts, callback, client)
1601    }
1602
1603    #[tokio::test]
1604    async fn subc_bridge_without_discovered_status_line_surface_emits_no_status_requests() {
1605        let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
1606        assert!(!client.publish(Path::new("/project"), "opencode", "session-1", "local"));
1607        let first_request = wire_rx.try_recv().expect("queued discovery publish");
1608        assert_eq!(first_request.body()["op"], "status.publish");
1609        assert_eq!(client.inner.state.lock().last_publish_at.len(), 1);
1610        let identity = FleetRouteIdentity::from(&first_request);
1611        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
1612        let catalog_calls = Arc::new(AtomicU64::new(0));
1613        let publish_calls = Arc::new(AtomicU64::new(0));
1614        let consumer = RejectingConsumer {
1615            attempts: attempts.clone(),
1616            advertises_status_line: false,
1617            catalog_calls: catalog_calls.clone(),
1618            publish_calls: publish_calls.clone(),
1619            succeeds_on: Some(1),
1620            failure: transient_failure(),
1621            connection_callback: Arc::default(),
1622            push_sender: Arc::default(),
1623            control_sender: Arc::default(),
1624            watch: Arc::default(),
1625        };
1626
1627        // Closing ingress lets the real dial finish after handling the queued
1628        // publish. Its return is a processing barrier, not a quiet-time guess.
1629        wire_rx.close();
1630        tokio::time::timeout(
1631            Duration::from_secs(5),
1632            run_connected_status_dial(
1633                consumer,
1634                client.clone(),
1635                wire_rx,
1636                identity,
1637                Some(first_request),
1638            ),
1639        )
1640        .await
1641        .expect("empty-catalog dial must finish processing the queued publish");
1642
1643        assert!(
1644            attempts.lock().is_empty(),
1645            "empty catalog must not open a holder route"
1646        );
1647        assert_eq!(
1648            publish_calls.load(Ordering::Relaxed),
1649            0,
1650            "empty catalog must not send status requests"
1651        );
1652        assert_eq!(
1653            catalog_calls.load(Ordering::Relaxed),
1654            1,
1655            "catalog gate was exercised"
1656        );
1657        assert!(!client.inner.route_live.load(Ordering::Acquire));
1658        assert!(
1659            client.inner.state.lock().last_publish_at.is_empty(),
1660            "unavailable publish must release its cadence reservation"
1661        );
1662    }
1663
1664    /// Opens the holder route, has the daemon close it for `reason` (the
1665    /// `route.closed` push, then the end of the route), lets several discovery
1666    /// cadences pass, and returns how many route opens the dial made.
1667    async fn route_opens_after_holder_close(reason: &str) -> usize {
1668        route_opens_after_holder_close_naming(reason, None).await
1669    }
1670
1671    /// [`route_opens_after_holder_close`] with a push that names the closed
1672    /// client `channels`, as a subc-control 0.27 daemon sends it. The test
1673    /// consumer's first route is channel 1.
1674    async fn route_opens_after_holder_close_naming(
1675        reason: &str,
1676        channels: Option<&[u16]>,
1677    ) -> usize {
1678        let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
1679        assert!(!client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
1680        let first_request = wire_rx.try_recv().expect("first discovery request");
1681        let identity = FleetRouteIdentity::from(&first_request);
1682        // Answered here rather than handed to the dial: the test consumer
1683        // fails every publish, and a failed publish drops the route itself.
1684        first_request.complete_unavailable();
1685        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
1686        let push_sender = Arc::new(parking_lot::Mutex::new(None));
1687        let control_sender = Arc::new(parking_lot::Mutex::new(None));
1688        let consumer = RejectingConsumer {
1689            attempts: attempts.clone(),
1690            succeeds_on: Some(1),
1691            failure: transient_failure(),
1692            advertises_status_line: true,
1693            catalog_calls: Arc::default(),
1694            publish_calls: Arc::default(),
1695            connection_callback: Arc::default(),
1696            push_sender: push_sender.clone(),
1697            control_sender: control_sender.clone(),
1698            watch: Arc::default(),
1699        };
1700        let task = tokio::spawn(run_connected_status_dial(
1701            consumer, client, wire_rx, identity, None,
1702        ));
1703        for _ in 0..4 {
1704            tokio::task::yield_now().await;
1705        }
1706        assert_eq!(attempts.lock().len(), 1, "the holder route opened");
1707
1708        let mut body = json!({
1709            "op": "route.closed",
1710            "module_id": STATUS_HOLDER_MODULE,
1711            "reason": reason,
1712        });
1713        if let Some(channels) = channels {
1714            body["channels"] = json!(channels);
1715        }
1716        let push = ControlPush {
1717            op: "route.closed".to_owned(),
1718            body,
1719        };
1720        control_sender
1721            .lock()
1722            .as_ref()
1723            .expect("dial registered for control pushes")
1724            .try_send(push)
1725            .expect("queue route.closed");
1726        push_sender.lock().take();
1727        for _ in 0..3 {
1728            tokio::time::advance(STATUS_CADENCE).await;
1729            for _ in 0..4 {
1730                tokio::task::yield_now().await;
1731            }
1732        }
1733        task.abort();
1734        let opens = attempts.lock().len();
1735        opens
1736    }
1737
1738    #[tokio::test(start_paused = true)]
1739    async fn scope_and_unknown_route_closes_never_reopen_the_holder_route() {
1740        for reason in [
1741            "scope_ended",
1742            "scope_carrier_removed",
1743            "scope_delegation_changed",
1744            "scope_parent_ended",
1745            "a_reason_from_a_newer_daemon",
1746        ] {
1747            assert_eq!(
1748                route_opens_after_holder_close(reason).await,
1749                1,
1750                "a {reason} close must not reopen the route"
1751            );
1752        }
1753        assert!(
1754            route_opens_after_holder_close("reload").await > 1,
1755            "a reload close still reopens on the next discovery"
1756        );
1757    }
1758
1759    #[tokio::test(start_paused = true)]
1760    async fn authority_changed_reopens_the_holder_route() {
1761        assert!(route_opens_after_holder_close("authority_changed").await > 1);
1762    }
1763
1764    #[tokio::test(start_paused = true)]
1765    async fn a_scope_close_naming_channels_applies_only_to_the_dial_route() {
1766        assert_eq!(
1767            route_opens_after_holder_close_naming("scope_ended", Some(&[1])).await,
1768            1,
1769            "a scope close naming the dial's channel must not reopen the route"
1770        );
1771        assert!(
1772            route_opens_after_holder_close_naming("scope_ended", Some(&[7, 9])).await > 1,
1773            "a scope close naming only other channels is not about the dial's route"
1774        );
1775    }
1776
1777    async fn advance_and_observe(
1778        attempts: &Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
1779        elapsed: Duration,
1780        expected: usize,
1781    ) {
1782        tokio::time::advance(elapsed).await;
1783        tokio::task::yield_now().await;
1784        assert_eq!(
1785            attempts.lock().len(),
1786            expected,
1787            "attempt count after {elapsed:?}"
1788        );
1789    }
1790
1791    /// Advance the paused clock by `total` in steps of the initial backoff, so
1792    /// every open the dial schedules runs at its exact deadline.
1793    async fn advance_in_steps(total: Duration) {
1794        let steps = total.as_millis() / DISCOVERY_INITIAL_BACKOFF.as_millis();
1795        for _ in 0..steps {
1796            tokio::time::advance(DISCOVERY_INITIAL_BACKOFF).await;
1797            tokio::task::yield_now().await;
1798        }
1799    }
1800
1801    #[tokio::test(start_paused = true)]
1802    async fn transient_open_failures_back_off_with_growing_gaps_to_a_bound() {
1803        let (task, attempts, _) = dial_with_rejections(None).await;
1804        advance_in_steps(Duration::from_secs(200)).await;
1805        let opened_at = attempts.lock().clone();
1806        task.abort();
1807        let gaps: Vec<_> = opened_at.windows(2).map(|pair| pair[1] - pair[0]).collect();
1808        assert_eq!(
1809            gaps,
1810            vec![
1811                Duration::from_millis(250),
1812                Duration::from_millis(500),
1813                Duration::from_secs(1),
1814                Duration::from_secs(2),
1815                Duration::from_secs(4),
1816                Duration::from_secs(8),
1817                Duration::from_secs(16),
1818                Duration::from_secs(32),
1819                DISCOVERY_MAX_BACKOFF,
1820                DISCOVERY_MAX_BACKOFF,
1821            ],
1822            "a restarting holder is retried with doubling gaps up to the bound"
1823        );
1824    }
1825
1826    #[tokio::test(start_paused = true)]
1827    async fn terminal_refusal_gets_one_open_attempt_per_session() {
1828        let session = "terminal-refusal-session-1";
1829        let (task, attempts, _, client) =
1830            dial_failing_with(None, terminal_refusal(), session).await;
1831        advance_in_steps(Duration::from_secs(600)).await;
1832        // Later publishes from the refused session do not bring the route back.
1833        for _ in 0..3 {
1834            client.publish(Path::new("/tmp/project"), "opencode", session, "local");
1835            advance_in_steps(Duration::from_secs(5)).await;
1836        }
1837        assert_eq!(
1838            attempts.lock().len(),
1839            1,
1840            "a terminal refusal ends the route opens for its session"
1841        );
1842        let stopped = client
1843            .stopped_route()
1844            .expect("the stopped route is recorded");
1845        assert_eq!(stopped.session, session);
1846        assert_eq!(stopped.target, STATUS_HOLDER_MODULE);
1847        assert_eq!(stopped.code, "project_origin_unclassifiable");
1848        let health = stopped_routes_snapshot();
1849        assert!(
1850            health
1851                .as_array()
1852                .expect("stopped routes are a list")
1853                .iter()
1854                .any(|row| {
1855                    row["session"] == session
1856                        && row["target"] == STATUS_HOLDER_MODULE
1857                        && row["refusal"]["code"] == "project_origin_unclassifiable"
1858                }),
1859            "the health report names the stopped route: {health}"
1860        );
1861
1862        // A publish from another session gets one attempt of its own, and its
1863        // refusal stops that session's route the same way.
1864        let other = "terminal-refusal-session-2";
1865        client.publish(Path::new("/tmp/other-project"), "opencode", other, "local");
1866        advance_in_steps(Duration::from_secs(600)).await;
1867        assert_eq!(attempts.lock().len(), 2, "one open for the second session");
1868        assert_eq!(
1869            client.stopped_route().map(|stopped| stopped.session),
1870            Some(other.to_owned())
1871        );
1872        // All sessions share this dial. Alternating publishes from the two
1873        // refused sessions must not make it forget one refusal and reopen
1874        // that session's route.
1875        for _ in 0..3 {
1876            client.publish(Path::new("/tmp/project"), "opencode", session, "local");
1877            advance_in_steps(Duration::from_secs(5)).await;
1878            client.publish(Path::new("/tmp/other-project"), "opencode", other, "local");
1879            advance_in_steps(Duration::from_secs(5)).await;
1880        }
1881        advance_in_steps(Duration::from_secs(600)).await;
1882        assert_eq!(
1883            attempts.lock().len(),
1884            2,
1885            "alternating refused sessions reopened a refused route"
1886        );
1887        let stopped: Vec<_> = client
1888            .stopped_routes()
1889            .into_iter()
1890            .map(|stopped| stopped.session)
1891            .collect();
1892        assert_eq!(stopped, vec![session.to_owned(), other.to_owned()]);
1893        task.abort();
1894    }
1895
1896    /// A subc daemon that answers HELLO and refuses every `route.open` with
1897    /// `code`, counting the opens it was sent. Returns the connection file to
1898    /// dial (inside the returned directory) and the open count.
1899    async fn refusing_daemon(
1900        code: &'static str,
1901    ) -> (tempfile::TempDir, std::path::PathBuf, Arc<AtomicU64>) {
1902        use subc_protocol::{
1903            Flags, Frame, FrameType, ModuleHelloAckBody, Priority, PROTOCOL_VERSION,
1904        };
1905        use subc_transport::connection_file::{self, ConnectionInfo, Endpoint, SCHEMA_VERSION};
1906
1907        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1908        let port = listener.local_addr().unwrap().port();
1909        let key = vec![0x42; subc_transport::KEY_LEN];
1910        let daemon_id = [0x24; subc_transport::DAEMON_ID_LEN];
1911        let opens = Arc::new(AtomicU64::new(0));
1912        let server_opens = Arc::clone(&opens);
1913        let server_key = key.clone();
1914        tokio::spawn(async move {
1915            let flags = Flags::new(false, Priority::Passive, false);
1916            while let Ok((mut stream, _)) = listener.accept().await {
1917                let key = server_key.clone();
1918                let opens = Arc::clone(&server_opens);
1919                tokio::spawn(async move {
1920                    if subc_transport::authenticate_server(
1921                        &mut stream,
1922                        &key,
1923                        &daemon_id,
1924                        "0.39.0",
1925                        Duration::from_secs(5),
1926                    )
1927                    .await
1928                    .is_err()
1929                    {
1930                        return;
1931                    }
1932                    while let Ok(Some(frame)) = crate::subc_fake::read_frame(&mut stream).await {
1933                        let header = frame.header;
1934                        let reply = match header.ty {
1935                            FrameType::Hello => Frame::build(
1936                                FrameType::HelloAck,
1937                                flags,
1938                                0,
1939                                0,
1940                                header.corr,
1941                                serde_json::to_vec(&ModuleHelloAckBody {
1942                                    negotiated_ver: PROTOCOL_VERSION,
1943                                    subc_ops: Vec::new(),
1944                                    subc_capabilities: Vec::new(),
1945                                    storage: None,
1946                                    machine_id: None,
1947                                })
1948                                .unwrap(),
1949                            )
1950                            .unwrap(),
1951                            FrameType::Request if header.channel == 0 => {
1952                                let body: Value =
1953                                    serde_json::from_slice(&frame.body).unwrap_or(Value::Null);
1954                                if body.get("op").and_then(Value::as_str) != Some("route.open") {
1955                                    continue;
1956                                }
1957                                opens.fetch_add(1, Ordering::Relaxed);
1958                                Frame::build(
1959                                    FrameType::Error,
1960                                    flags,
1961                                    0,
1962                                    0,
1963                                    header.corr,
1964                                    serde_json::to_vec(&subc_protocol::ErrorBody::new(
1965                                        code,
1966                                        "refused by the fake daemon",
1967                                    ))
1968                                    .unwrap(),
1969                                )
1970                                .unwrap()
1971                            }
1972                            _ => continue,
1973                        };
1974                        if subc_transport::write_frame(&mut stream, &reply)
1975                            .await
1976                            .is_err()
1977                        {
1978                            return;
1979                        }
1980                    }
1981                });
1982            }
1983        });
1984
1985        let dir = tempfile::tempdir().unwrap();
1986        let file = dir.path().join("connection.json");
1987        connection_file::write_atomic(
1988            &file,
1989            &ConnectionInfo {
1990                schema: SCHEMA_VERSION,
1991                wire_version: Some(PROTOCOL_VERSION),
1992                endpoints: vec![Endpoint {
1993                    host: "127.0.0.1".to_string(),
1994                    port,
1995                }],
1996                key,
1997                daemon_id,
1998                pid: std::process::id(),
1999                // Reach the scripted refusal instead of the SDK's old-daemon guard.
2000                daemon_ver: "0.39.0".to_string(),
2001            },
2002        )
2003        .unwrap();
2004        (dir, file, opens)
2005    }
2006
2007    async fn connect_to(file: &Path) -> SubcConsumer {
2008        SubcConsumer::connect(
2009            file,
2010            ConsumerOptions {
2011                call_timeout: Duration::from_secs(5),
2012                ..ConsumerOptions::default()
2013            },
2014        )
2015        .await
2016        .expect("the fake daemon accepts the connection")
2017    }
2018
2019    fn holder_target() -> RouteTarget {
2020        RouteTarget::ManagementSurface {
2021            module_id: STATUS_HOLDER_MODULE.to_string(),
2022        }
2023    }
2024
2025    /// The production open path, through the real subc client: a holder's
2026    /// terminal refusal reaches the daemon once (the client does not retry it
2027    /// either) and the dial sees it as terminal.
2028    #[tokio::test]
2029    async fn a_holder_refusal_through_the_subc_client_is_terminal_and_sent_once() {
2030        let (_dir, file, opens) = refusing_daemon("project_origin_unclassifiable").await;
2031        let consumer = connect_to(&file).await;
2032        let failure = StatusConsumer::open_route(
2033            &consumer,
2034            holder_target(),
2035            BindIdentity::new("runner", "session-1"),
2036        )
2037        .await
2038        .expect_err("the fake daemon refuses every open");
2039        assert_eq!(
2040            failure,
2041            RouteOpenFailure::Refused {
2042                code: "project_origin_unclassifiable".to_owned(),
2043                message: "refused by the fake daemon".to_owned(),
2044            }
2045        );
2046        assert_eq!(opens.load(Ordering::Relaxed), 1);
2047    }
2048
2049    /// A refusal subc-protocol classes as retryable (the holder is reloading)
2050    /// stays transient even after the client's own retries run out.
2051    #[tokio::test]
2052    async fn a_reloading_holder_through_the_subc_client_is_transient() {
2053        let (_dir, file, opens) = refusing_daemon("module_reloading").await;
2054        let consumer = connect_to(&file).await;
2055        let error = SubcConsumer::open_route(
2056            &consumer,
2057            holder_target(),
2058            BindIdentity::new("runner", "session-1"),
2059            CallOptions {
2060                timeout: Duration::from_millis(400),
2061                route_retry_deadline: Duration::from_millis(400),
2062                ..CallOptions::default()
2063            },
2064        )
2065        .await
2066        .expect_err("the fake daemon refuses every open");
2067        assert!(
2068            matches!(
2069                RouteOpenFailure::from_call_error(&error),
2070                RouteOpenFailure::Transient(_)
2071            ),
2072            "{error}"
2073        );
2074        assert!(opens.load(Ordering::Relaxed) >= 1);
2075    }
2076
2077    #[tokio::test(start_paused = true)]
2078    async fn successful_bind_resets_rejection_backoff() {
2079        let (task, attempts, callback) = dial_with_rejections(Some(4)).await;
2080        for (elapsed, expected) in [
2081            (Duration::from_millis(250), 2),
2082            (Duration::from_millis(500), 3),
2083            (Duration::from_secs(1), 4),
2084        ] {
2085            advance_and_observe(&attempts, elapsed, expected).await;
2086        }
2087        callback.lock().as_ref().expect("connection callback")(ConnectionState::Dropped);
2088        tokio::task::yield_now().await;
2089        assert_eq!(attempts.lock().len(), 5, "drop rediscovers immediately");
2090        let fifth = attempts.lock()[4];
2091        advance_and_observe(&attempts, Duration::from_millis(250), 6).await;
2092        assert_eq!(attempts.lock()[5] - fifth, DISCOVERY_INITIAL_BACKOFF);
2093        task.abort();
2094    }
2095
2096    #[test]
2097    fn publish_ack_tolerates_fields_a_newer_holder_adds() {
2098        // The status holder is a separately released module, and its publish
2099        // ack is on every response's hot path. A newer holder adds fields (first
2100        // `last_read_at_ms`, so aft can tell whether anything reads a scope);
2101        // an ack decoder that refused unknown keys would turn that addition into
2102        // a failed publish on every call. Pin that unknown keys are ignored.
2103        let ack = StatusPublishAck::parse(
2104            br#"{"epoch":3,"accepted_revision":7,"last_read_at_ms":1790115735811,"future_field":{"nested":true}}"#,
2105        )
2106        .expect("an ack carrying unknown keys still parses");
2107        assert_eq!(
2108            ack,
2109            StatusPublishAck {
2110                epoch: 3,
2111                accepted_revision: 7,
2112                last_read_at_ms: Some(1790115735811),
2113            }
2114        );
2115        let null_read =
2116            StatusPublishAck::parse(br#"{"epoch":3,"accepted_revision":7,"last_read_at_ms":null}"#);
2117        assert_eq!(
2118            null_read
2119                .expect("a null last_read_at_ms still parses")
2120                .last_read_at_ms,
2121            None
2122        );
2123    }
2124
2125    #[test]
2126    fn publish_ack_fixtures_drive_runtime_fencing() {
2127        let fixtures = fixtures();
2128        assert_eq!(fixtures.len(), 18, "fixture probe entry count changed");
2129        let mut fence = PublishFence::default();
2130        for name in PUBLISH_ACK_FIXTURES {
2131            fence.observe(parse_ack(&fixtures[name]));
2132        }
2133        assert_eq!(
2134            fence,
2135            PublishFence {
2136                epoch: 4,
2137                accepted_revision: 1
2138            }
2139        );
2140    }
2141
2142    #[test]
2143    fn line_reply_fixtures_remain_wire_shape_documentation() {
2144        let fixtures = fixtures();
2145        let documented = PUBLISH_ACK_FIXTURES
2146            .into_iter()
2147            .chain(LINE_REPLY_FIXTURES)
2148            .collect::<HashSet<_>>();
2149        assert_eq!(documented.len(), fixtures.len());
2150        assert!(fixtures
2151            .keys()
2152            .all(|name| documented.contains(name.as_str())));
2153
2154        let lines = LINE_REPLY_FIXTURES
2155            .into_iter()
2156            .map(|name| (name, parse_line(&fixtures[name])))
2157            .collect::<HashMap<_, _>>();
2158        assert_eq!(
2159            lines["line_foreign_present"].line,
2160            "aft E0 W0 idx fresh | pfc 1567 events (777 gaps)"
2161        );
2162        assert!(lines["line_foreign_present"].has_foreign_segment());
2163        assert_eq!(
2164            lines["supersede_line_after_r3"],
2165            lines["supersede_line_after_late_r2"]
2166        );
2167        assert!(lines["supersede_line_after_late_r2"]
2168            .line
2169            .contains("revision three"));
2170        assert_eq!(lines["ttl_line_before"].segments.len(), 4);
2171        assert_eq!(lines["ttl_line_after_expiry"].segments.len(), 3);
2172        assert_eq!(
2173            lines["quiet_line"]
2174                .segments
2175                .last()
2176                .map(|segment| segment.text.as_str()),
2177            Some("")
2178        );
2179        assert!(!lines["quiet_line"].line.contains("ttlfx"));
2180
2181        let capped = &lines["line_cap_overflow"];
2182        assert!(capped.line.chars().count() <= 200);
2183        assert_eq!(
2184            capped.segments.len(),
2185            6,
2186            "the cap must not truncate segments[]"
2187        );
2188        assert!(
2189            !capped.line.contains("fat2"),
2190            "whole tail segments are dropped"
2191        );
2192        assert_eq!(
2193            lines["epoch_bump_line_after"].segments[3].text,
2194            "fresh epoch revision one"
2195        );
2196        assert!(!lines["line_aft_solo_scope"].has_foreign_segment());
2197    }
2198
2199    #[test]
2200    fn publication_fence_drops_regressions_but_new_epoch_wins() {
2201        let fixtures = fixtures();
2202        let mut fence = PublishFence::default();
2203        fence.observe(parse_ack(&fixtures["supersede_r3"]));
2204        fence.observe(StatusPublishAck {
2205            epoch: 3,
2206            accepted_revision: 2,
2207            last_read_at_ms: None,
2208        });
2209        assert_eq!(
2210            fence,
2211            PublishFence {
2212                epoch: 3,
2213                accepted_revision: 3
2214            }
2215        );
2216
2217        fence.observe(parse_ack(&fixtures["epoch_bump_republish_r1_new_conn"]));
2218        assert_eq!(
2219            fence,
2220            PublishFence {
2221                epoch: 4,
2222                accepted_revision: 1
2223            }
2224        );
2225    }
2226
2227    #[test]
2228    fn catalog_gate_requires_matching_module_management_role_and_exact_operation() {
2229        assert!(status_holder(&[status_catalog_entry(
2230            STATUS_HOLDER_MODULE,
2231            STATUS_LINE_OPERATION,
2232        )])
2233        .is_some());
2234        assert!(
2235            status_holder(&[status_catalog_entry("other-module", STATUS_LINE_OPERATION,)])
2236                .is_none()
2237        );
2238        assert!(
2239            status_holder(&[status_catalog_entry(STATUS_HOLDER_MODULE, "status.lines",)]).is_none()
2240        );
2241    }
2242
2243    #[test]
2244    fn dial_channel_queues_discovery_without_claiming_the_status_bar() {
2245        let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
2246
2247        assert!(!client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
2248        let request = wire_rx.try_recv().expect("discovery request");
2249        assert_eq!(request.project_root(), "/tmp/project");
2250        assert_eq!(request.harness(), "opencode");
2251        assert_eq!(request.session(), "session-1");
2252        request.complete_unavailable();
2253    }
2254
2255    #[test]
2256    fn closed_dial_channel_falls_back_to_the_solo_status_bar() {
2257        let (client, wire_rx) = FleetStatusClient::channel(1);
2258        drop(wire_rx);
2259
2260        assert!(!client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
2261        assert!(!client.inner.route_live.load(Ordering::Acquire));
2262    }
2263
2264    #[test]
2265    fn dormant_client_falls_back_without_publishing() {
2266        let client = FleetStatusClient::dormant();
2267
2268        assert!(!client.publish(
2269            Path::new("/tmp/project"),
2270            "opencode",
2271            "session-1",
2272            "E0 W0 | T0"
2273        ));
2274        let state = client.inner.state.lock();
2275        assert!(state.last_publish_at.is_empty());
2276        assert_eq!(client.inner.next_revision.load(Ordering::Relaxed), 1);
2277    }
2278
2279    #[test]
2280    fn empty_local_status_publishes_alive_quiet() {
2281        let (client, mut wire_rx) = FleetStatusClient::channel(4);
2282
2283        assert!(client.publish(Path::new("/tmp/project"), "opencode", "session-1", ""));
2284        let publish = wire_rx.try_recv().expect("publish request");
2285        assert_eq!(publish.body()["op"], "status.publish");
2286        assert_eq!(publish.body()["text"], "");
2287        assert_eq!(publish.body()["ttl_ms"], STATUS_PUBLISH_TTL_MS);
2288        assert!(
2289            wire_rx.try_recv().is_err(),
2290            "publisher emitted a pull request"
2291        );
2292    }
2293
2294    #[test]
2295    fn cadence_suppresses_duplicate_publishes_and_ack_updates_fence() {
2296        let (client, mut wire_rx) = FleetStatusClient::channel(4);
2297        let fixtures = fixtures();
2298        let publish_fixture =
2299            serde_json::to_vec(&fixtures["publish_aft"]).expect("publish fixture bytes");
2300
2301        assert!(client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
2302        let publish = wire_rx.try_recv().expect("first publish request");
2303        assert_eq!(publish.body()["revision"], 1);
2304        assert!(publish.complete_response(&publish_fixture));
2305
2306        assert!(client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
2307        assert!(
2308            wire_rx.try_recv().is_err(),
2309            "publish cadence issued another request"
2310        );
2311        assert_eq!(
2312            client.publish_fence(),
2313            PublishFence {
2314                epoch: 3,
2315                accepted_revision: 1
2316            }
2317        );
2318    }
2319
2320    fn ack_with_read(revision: u64, last_read_at_ms: Option<u64>) -> Vec<u8> {
2321        serde_json::to_vec(&json!({
2322            "epoch": 1,
2323            "accepted_revision": revision,
2324            "last_read_at_ms": last_read_at_ms,
2325        }))
2326        .expect("ack bytes")
2327    }
2328
2329    #[test]
2330    fn read_freshness_is_bounded_by_the_window_and_tolerates_a_holder_clock_ahead() {
2331        let ack_at = 1_000_000;
2332        assert!(read_is_fresh(Some(ack_at - READER_FRESH_WINDOW_MS), ack_at));
2333        assert!(!read_is_fresh(
2334            Some(ack_at - READER_FRESH_WINDOW_MS - 1),
2335            ack_at
2336        ));
2337        assert!(read_is_fresh(Some(ack_at + 5_000), ack_at));
2338        assert!(!read_is_fresh(None, ack_at));
2339    }
2340
2341    #[test]
2342    fn reader_presence_is_per_scope_and_follows_the_latest_ack() {
2343        let (client, mut wire_rx) = FleetStatusClient::channel(4);
2344        let read = Path::new("/tmp/read");
2345        let unread = Path::new("/tmp/unread");
2346        assert!(!client.reader_present(read), "no ack yet is no evidence");
2347
2348        assert!(client.publish(read, "opencode", "session", "text"));
2349        assert!(wire_rx
2350            .try_recv()
2351            .unwrap()
2352            .complete_response(&ack_with_read(1, Some(unix_now_ms() - 2_000))));
2353        assert!(client.publish(unread, "opencode", "session", "text"));
2354        assert!(wire_rx
2355            .try_recv()
2356            .unwrap()
2357            .complete_response(&ack_with_read(2, None)));
2358        assert!(client.reader_present(read));
2359        assert!(!client.reader_present(unread));
2360
2361        // The reader stops: the next ack reports a read older than the window.
2362        client.inner.state.lock().last_publish_at.clear();
2363        assert!(client.publish(read, "opencode", "session", "text"));
2364        assert!(wire_rx
2365            .try_recv()
2366            .unwrap()
2367            .complete_response(&ack_with_read(
2368                3,
2369                Some(unix_now_ms() - READER_FRESH_WINDOW_MS - 5_000)
2370            )));
2371        assert!(!client.reader_present(read));
2372    }
2373
2374    #[test]
2375    fn holder_without_read_field_or_dropped_route_is_no_reader() {
2376        let (client, mut wire_rx) = FleetStatusClient::channel(4);
2377        let root = Path::new("/tmp/project");
2378        assert!(client.publish(root, "opencode", "session", "text"));
2379        assert!(wire_rx
2380            .try_recv()
2381            .unwrap()
2382            .complete_response(br#"{"epoch":1,"accepted_revision":1}"#));
2383        assert!(
2384            !client.reader_present(root),
2385            "an older holder proves no reader"
2386        );
2387
2388        client.inner.state.lock().last_publish_at.clear();
2389        assert!(client.publish(root, "opencode", "session", "text"));
2390        assert!(wire_rx
2391            .try_recv()
2392            .unwrap()
2393            .complete_response(&ack_with_read(2, Some(unix_now_ms()))));
2394        assert!(client.reader_present(root));
2395        client.set_route_live(false);
2396        assert!(
2397            !client.reader_present(root),
2398            "a dropped route has no reader"
2399        );
2400        client.set_route_live(true);
2401        assert!(
2402            !client.reader_present(root),
2403            "evidence from the dropped route does not survive a rebind"
2404        );
2405    }
2406}