use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Weak};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde::Deserialize;
use serde_json::{json, Value};
use subc_client_rs::{
CallOptions, CatalogList, CloseRouteOptions, ConnectionState, ConsumerOptions, ControlPush,
PushEvent, RouteCloseReason, RouteHandle, SubcConsumer,
};
use subc_protocol::manifest::ProviderRole;
use subc_protocol::{BindIdentity, RouteTarget};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
const STATUS_CADENCE: Duration = Duration::from_millis(2_500);
const CATALOG_BACKSTOP: Duration = Duration::from_secs(5 * 60);
const READER_FRESH_WINDOW_MS: u64 = 10_000;
const DISCOVERY_INITIAL_BACKOFF: Duration = Duration::from_millis(250);
const DISCOVERY_MAX_BACKOFF: Duration = Duration::from_secs(60);
const STATUS_PUBLISH_TTL_MS: u64 = 7_500;
const STATUS_MODULE: &str = "aft";
const STATUS_HOLDER_MODULE: &str = crate::prefrontal::MODULE_ID;
const STATUS_LINE_OPERATION: &str = "status.line";
#[cfg(any(test, feature = "test-support"))]
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) struct StatusLineSegment {
pub(crate) module: String,
pub(crate) scope: String,
pub(crate) text: String,
}
#[cfg(any(test, feature = "test-support"))]
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) struct StatusLineSnapshot {
pub(crate) line: String,
pub(crate) segments: Vec<StatusLineSegment>,
}
#[cfg(any(test, feature = "test-support"))]
impl StatusLineSnapshot {
#[cfg_attr(not(test), allow(dead_code))]
fn parse(body: &[u8]) -> Option<Self> {
serde_json::from_slice(body).ok()
}
#[cfg_attr(not(test), allow(dead_code))]
fn has_foreign_segment(&self) -> bool {
self.segments
.iter()
.any(|segment| segment.module != STATUS_MODULE && !segment.text.is_empty())
}
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
pub(crate) struct StatusPublishAck {
pub(crate) epoch: u64,
pub(crate) accepted_revision: u64,
#[serde(default)]
pub(crate) last_read_at_ms: Option<u64>,
}
impl StatusPublishAck {
fn parse(body: &[u8]) -> Option<Self> {
serde_json::from_slice(body).ok()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct PublishFence {
epoch: u64,
accepted_revision: u64,
}
impl PublishFence {
fn observe(&mut self, ack: StatusPublishAck) {
if ack.epoch > self.epoch
|| (ack.epoch == self.epoch && ack.accepted_revision >= self.accepted_revision)
{
self.epoch = ack.epoch;
self.accepted_revision = ack.accepted_revision;
}
}
}
#[derive(Default)]
struct ClientState {
last_publish_at: HashMap<String, Instant>,
publish_fence: PublishFence,
reader_fresh_by_scope: HashMap<String, bool>,
}
impl ClientState {
fn forget_route(&mut self) {
self.last_publish_at.clear();
self.reader_fresh_by_scope.clear();
}
}
fn status_scope(project_root: &Path) -> String {
format!("project:{}", project_root.to_string_lossy())
}
fn unix_now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_millis() as u64)
.unwrap_or_default()
}
fn read_is_fresh(last_read_at_ms: Option<u64>, ack_at_ms: u64) -> bool {
last_read_at_ms
.is_some_and(|read_at| ack_at_ms.saturating_sub(read_at) <= READER_FRESH_WINDOW_MS)
}
struct FleetStatusInner {
wire_tx: Option<mpsc::Sender<StatusWireRequest>>,
route_live: AtomicBool,
state: parking_lot::Mutex<ClientState>,
next_revision: AtomicU64,
stopped_routes: parking_lot::Mutex<Vec<StoppedRoute>>,
}
const MAX_STOPPED_ROUTES: usize = 64;
impl FleetStatusInner {
fn new(wire_tx: Option<mpsc::Sender<StatusWireRequest>>, route_live: bool) -> Self {
Self {
wire_tx,
route_live: AtomicBool::new(route_live),
state: parking_lot::Mutex::new(ClientState::default()),
next_revision: AtomicU64::new(1),
stopped_routes: parking_lot::Mutex::new(Vec::new()),
}
}
}
test_support_visibility! {
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StoppedRoute {
target: String,
#[cfg(any(test, feature = "test-support"))]
pub session: String,
#[cfg(not(any(test, feature = "test-support")))]
session: String,
harness: String,
project_root: String,
code: String,
message: String,
stopped_at_unix_ms: u64,
}
}
impl StoppedRoute {
fn to_value(&self) -> Value {
json!({
"component": "fleet_status",
"target": self.target,
"session": self.session,
"harness": self.harness,
"project_root": self.project_root,
"refusal": { "code": self.code, "message": self.message },
"stopped_at_unix_ms": self.stopped_at_unix_ms,
})
}
}
static DIAL_CLIENTS: parking_lot::Mutex<Vec<Weak<FleetStatusInner>>> =
parking_lot::Mutex::new(Vec::new());
fn register_dial_client(inner: &Arc<FleetStatusInner>) {
let mut clients = DIAL_CLIENTS.lock();
clients.retain(|client| client.strong_count() > 0);
clients.push(Arc::downgrade(inner));
}
pub fn stopped_routes_snapshot() -> Value {
let mut clients = DIAL_CLIENTS.lock();
clients.retain(|client| client.strong_count() > 0);
Value::Array(
clients
.iter()
.filter_map(Weak::upgrade)
.flat_map(|client| {
client
.stopped_routes
.lock()
.iter()
.map(StoppedRoute::to_value)
.collect::<Vec<_>>()
})
.collect(),
)
}
test_support_visibility! {
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum RouteOpenFailure {
Refused { code: String, message: String },
Transient(String),
}
}
impl RouteOpenFailure {
fn from_call_error(error: &subc_client_rs::CallError) -> Self {
let refusal = match error {
subc_client_rs::CallError::Module(body) => Some(body),
other => other.route_open_refusal(),
};
match refusal {
Some(body) if !subc_protocol::error_codes::is_retryable_route_open(&body.code) => {
Self::Refused {
code: body.code.clone(),
message: body.message.clone(),
}
}
_ => Self::Transient(error.to_string()),
}
}
}
#[derive(Clone)]
pub struct FleetStatusClient {
inner: Arc<FleetStatusInner>,
}
impl FleetStatusClient {
#[cfg(any(test, feature = "test-support"))]
pub fn channel(capacity: usize) -> (Self, mpsc::Receiver<StatusWireRequest>) {
Self::channel_with_liveness(capacity, true)
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn dial_channel(capacity: usize) -> (Self, mpsc::Receiver<StatusWireRequest>) {
Self::channel_with_liveness(capacity, false)
}
}
fn channel_with_liveness(
capacity: usize,
route_live: bool,
) -> (Self, mpsc::Receiver<StatusWireRequest>) {
let (wire_tx, wire_rx) = mpsc::channel(capacity);
let inner = Arc::new(FleetStatusInner::new(Some(wire_tx), route_live));
register_dial_client(&inner);
(Self { inner }, wire_rx)
}
pub(crate) fn dormant() -> Self {
Self {
inner: Arc::new(FleetStatusInner::new(None, false)),
}
}
test_support_visibility! {
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn stopped_route(&self) -> Option<StoppedRoute> {
self.inner.stopped_routes.lock().last().cloned()
}
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
fn stopped_routes(&self) -> Vec<StoppedRoute> {
self.inner.stopped_routes.lock().clone()
}
fn record_stopped_route(&self, stopped: StoppedRoute) {
let mut routes = self.inner.stopped_routes.lock();
routes.retain(|route| {
(&route.session, &route.harness, &route.project_root)
!= (&stopped.session, &stopped.harness, &stopped.project_root)
});
if routes.len() >= MAX_STOPPED_ROUTES {
routes.remove(0);
}
routes.push(stopped);
}
pub fn set_route_live(&self, route_live: bool) {
self.inner.route_live.store(route_live, Ordering::Release);
if !route_live {
self.inner.state.lock().forget_route();
}
}
pub fn reader_present(&self, project_root: &Path) -> bool {
if !self.inner.route_live.load(Ordering::Acquire) {
return false;
}
let scope = status_scope(project_root);
self.inner
.state
.lock()
.reader_fresh_by_scope
.get(&scope)
.copied()
.unwrap_or(false)
}
pub fn publish(
&self,
project_root: &Path,
harness: &str,
session: &str,
aft_text: &str,
) -> bool {
let Some(wire_tx) = self.inner.wire_tx.as_ref() else {
return false;
};
crate::runner_status_state::publish(session, aft_text);
let route_live = self.inner.route_live.load(Ordering::Acquire);
let scope = status_scope(project_root);
let now = Instant::now();
let revision = {
let Some(mut state) = self.inner.state.try_lock() else {
return true;
};
if state
.last_publish_at
.get(&scope)
.is_some_and(|last| now.saturating_duration_since(*last) < STATUS_CADENCE)
{
return true;
}
state.last_publish_at.insert(scope.clone(), now);
self.inner.next_revision.fetch_add(1, Ordering::Relaxed)
};
let request = StatusWireRequest::publish(
Arc::downgrade(&self.inner),
project_root,
harness,
session,
&scope,
aft_text,
revision,
);
match wire_tx.try_send(request) {
Ok(()) => route_live,
Err(mpsc::error::TrySendError::Full(_)) => {
self.inner.state.lock().last_publish_at.remove(&scope);
route_live
}
Err(mpsc::error::TrySendError::Closed(request)) => {
request.complete_unavailable();
false
}
}
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
fn publish_fence(&self) -> PublishFence {
self.inner.state.lock().publish_fence
}
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) struct StatusWireRequest {
body: Value,
project_root: String,
harness: String,
session: String,
client: Weak<FleetStatusInner>,
}
}
test_support_visibility! {
#[derive(Clone, PartialEq, Eq)]
struct FleetRouteIdentity {
project_root: String,
harness: String,
#[cfg(any(test, feature = "test-support"))]
pub session: String,
#[cfg(not(any(test, feature = "test-support")))]
session: String,
}
}
impl StatusWireRequest {
fn publish(
client: Weak<FleetStatusInner>,
project_root: &Path,
harness: &str,
session: &str,
scope: &str,
text: &str,
revision: u64,
) -> Self {
Self {
body: json!({
"op": "status.publish",
"module": STATUS_MODULE,
"scope": scope,
"text": text,
"ttl_ms": STATUS_PUBLISH_TTL_MS,
"revision": revision,
}),
project_root: project_root.to_string_lossy().into_owned(),
harness: harness.to_owned(),
session: session.to_owned(),
client,
}
}
pub(crate) fn project_root(&self) -> &str {
&self.project_root
}
pub(crate) fn harness(&self) -> &str {
&self.harness
}
test_support_visibility! {
pub(crate) fn session(&self) -> &str {
&self.session
}
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn body(&self) -> &Value {
&self.body
}
}
pub(crate) fn complete_response(self, body: &[u8]) -> bool {
let Some(ack) = StatusPublishAck::parse(body) else {
self.complete_unavailable();
return false;
};
let Some(client) = self.client.upgrade() else {
return true;
};
let reader_fresh = read_is_fresh(ack.last_read_at_ms, unix_now_ms());
let mut state = client.state.lock();
state.publish_fence.observe(ack);
if let Some(scope) = self.body["scope"].as_str() {
state
.reader_fresh_by_scope
.insert(scope.to_owned(), reader_fresh);
}
true
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn complete_unavailable(self) {
if let Some(client) = self.client.upgrade() {
client.route_live.store(false, Ordering::Release);
client.state.lock().forget_route();
}
}
}
}
impl From<&StatusWireRequest> for FleetRouteIdentity {
fn from(request: &StatusWireRequest) -> Self {
Self {
project_root: request.project_root().to_owned(),
harness: request.harness().to_owned(),
session: request.session().to_owned(),
}
}
}
pub async fn connect_subc_consumer(
owner: &'static str,
connection_file: &Path,
options: ConsumerOptions,
) -> Result<SubcConsumer, subc_client_rs::ConsumerError> {
crate::registration::connect_consumer(owner, connection_file, options).await
}
pub fn spawn_fleet_status_dial(
connection_file: &Path,
capacity: usize,
) -> (FleetStatusClient, JoinHandle<()>) {
if !crate::registration::module_consumer_allowed() {
return (FleetStatusClient::dormant(), tokio::spawn(async {}));
}
let (client, wire_rx) = FleetStatusClient::dial_channel(capacity);
let task_client = client.clone();
let connection_file = connection_file.to_path_buf();
let task = tokio::spawn(async move {
run_fleet_status_dial(connection_file, task_client, wire_rx).await;
});
(client, task)
}
async fn run_fleet_status_dial(
connection_file: std::path::PathBuf,
client: FleetStatusClient,
mut wire_rx: mpsc::Receiver<StatusWireRequest>,
) {
let Some(first_request) = wire_rx.recv().await else {
return;
};
let route_identity = FleetRouteIdentity::from(&first_request);
let mut pending_request = Some(first_request);
let mut connect_backoff = DISCOVERY_INITIAL_BACKOFF;
let consumer = loop {
let options = ConsumerOptions {
call_timeout: STATUS_CADENCE,
..ConsumerOptions::default()
};
match connect_subc_consumer("fleet_status", &connection_file, options).await {
Ok(consumer) => break consumer,
Err(error) => {
client.set_route_live(false);
if let Some(request) = pending_request.take() {
request.complete_unavailable();
}
log::debug!("fleet status dial: consumer connect unavailable: {error}");
tokio::time::sleep(connect_backoff).await;
connect_backoff = next_discovery_backoff(connect_backoff);
}
}
};
run_connected_status_dial(consumer, client, wire_rx, route_identity, pending_request).await;
}
test_support_visibility! {
#[cfg_attr(any(test, feature = "test-support"), allow(async_fn_in_trait))]
trait StatusConsumer {
type Route;
type CatalogWatch: StatusCatalogWatch;
fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static);
fn control_pushes(&self) -> mpsc::Receiver<ControlPush>;
async fn catalog_list(&self) -> Result<CatalogList, String>;
async fn catalog_watch(&self) -> Result<Self::CatalogWatch, String>;
async fn open_route(
&self,
target: RouteTarget,
identity: BindIdentity,
) -> Result<Self::Route, RouteOpenFailure>;
fn push_events(&self, route: &Self::Route) -> Result<mpsc::Receiver<PushEvent>, String>;
fn route_channel(&self, route: &Self::Route) -> u16;
async fn close_handle(&self, route: &Self::Route) -> Result<(), String>;
async fn request(&self, route: &Self::Route, body: Vec<u8>) -> Result<Vec<u8>, String>;
}
}
test_support_visibility! {
#[cfg_attr(any(test, feature = "test-support"), allow(async_fn_in_trait))]
trait StatusCatalogWatch {
async fn next_generation(&mut self) -> Result<Option<u64>, String>;
}
}
impl StatusCatalogWatch for subc_client_rs::CatalogSubscription {
async fn next_generation(&mut self) -> Result<Option<u64>, String> {
self.next()
.await
.map(|event| event.map(|event| event.generation))
.map_err(|error| error.to_string())
}
}
impl StatusConsumer for SubcConsumer {
type Route = RouteHandle;
type CatalogWatch = subc_client_rs::CatalogSubscription;
fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static) {
SubcConsumer::on_connection_state(self, cb);
}
fn control_pushes(&self) -> mpsc::Receiver<ControlPush> {
SubcConsumer::control_pushes(self, CONTROL_PUSH_CAPACITY)
}
async fn catalog_list(&self) -> Result<CatalogList, String> {
SubcConsumer::catalog_list(self)
.await
.map_err(|error| error.to_string())
}
async fn catalog_watch(&self) -> Result<Self::CatalogWatch, String> {
SubcConsumer::catalog_watch(self)
.await
.map_err(|error| error.to_string())
}
async fn open_route(
&self,
target: RouteTarget,
identity: BindIdentity,
) -> Result<Self::Route, RouteOpenFailure> {
SubcConsumer::open_route(
self,
target,
identity,
CallOptions {
..CallOptions::default()
},
)
.await
.map_err(|error| RouteOpenFailure::from_call_error(&error))
}
fn push_events(&self, route: &Self::Route) -> Result<mpsc::Receiver<PushEvent>, String> {
SubcConsumer::push_events(self, route).map_err(|error| error.to_string())
}
fn route_channel(&self, route: &Self::Route) -> u16 {
route.channel
}
async fn close_handle(&self, route: &Self::Route) -> Result<(), String> {
SubcConsumer::close_handle(self, route, CloseRouteOptions::default())
.await
.map_err(|error| error.to_string())
}
async fn request(&self, route: &Self::Route, body: Vec<u8>) -> Result<Vec<u8>, String> {
SubcConsumer::request(self, route, body, CallOptions::default())
.await
.map_err(|error| error.to_string())
}
}
test_support_visibility! {
async fn run_connected_status_dial<C: StatusConsumer>(
consumer: C,
client: FleetStatusClient,
mut wire_rx: mpsc::Receiver<StatusWireRequest>,
mut route_identity: FleetRouteIdentity,
mut pending_request: Option<StatusWireRequest>,
) {
let (connection_state_tx, mut connection_state_rx) = mpsc::unbounded_channel();
let connection_state_client = client.clone();
consumer.on_connection_state(move |state| {
connection_state_client.set_route_live(false);
let _ = connection_state_tx.send(state);
});
let mut control_pushes = Some(consumer.control_pushes());
let mut reopen_forbidden: Option<String> = None;
let mut last_route_channel: Option<u16> = None;
let mut refused_identities: std::collections::VecDeque<FleetRouteIdentity> =
std::collections::VecDeque::new();
let mut route: Option<C::Route> = None;
let mut route_events = None;
let mut catalog_watch = None;
let mut catalog_generation = None;
let mut next_watch_at = tokio::time::Instant::now();
let mut next_discovery_at = tokio::time::Instant::now();
let mut discovery_backoff = DISCOVERY_INITIAL_BACKOFF;
loop {
if catalog_watch.is_none() && tokio::time::Instant::now() >= next_watch_at {
match consumer.catalog_watch().await {
Ok(watch) => {
catalog_watch = Some(watch);
next_discovery_at = tokio::time::Instant::now();
}
Err(error) => {
log::debug!("fleet status dial: catalog watch unavailable: {error}");
next_watch_at = tokio::time::Instant::now() + STATUS_CADENCE;
}
}
}
let discovery_cadence = if catalog_watch.is_some() {
CATALOG_BACKSTOP
} else {
STATUS_CADENCE
};
if tokio::time::Instant::now() >= next_discovery_at {
let catalog = consumer.catalog_list().await;
match catalog {
Ok(catalog) if status_holder(&catalog.modules).is_some() => {
let holder = STATUS_HOLDER_MODULE;
catalog_generation = Some(catalog.generation);
if route.is_none()
&& reopen_forbidden.is_none()
&& !refused_identities.contains(&route_identity)
{
let identity = BindIdentity::new(
route_identity.harness.clone(),
route_identity.session.clone(),
);
match consumer
.open_route(
RouteTarget::ManagementSurface {
module_id: holder.to_string(),
},
identity,
)
.await
{
Ok(opened_route) => match consumer.push_events(&opened_route) {
Ok(events) => {
route_events = Some(events);
last_route_channel =
Some(consumer.route_channel(&opened_route));
route = Some(opened_route);
discovery_backoff = DISCOVERY_INITIAL_BACKOFF;
}
Err(error) => {
log::debug!(
"fleet status dial: route event registration unavailable: {error}"
);
client.set_route_live(false);
}
},
Err(RouteOpenFailure::Refused { code, message }) => {
log::warn!(
"fleet status dial: {holder} refused the status route for session {} (harness {}, project {}): {code}: {message}; not reopening it for this session",
route_identity.session,
route_identity.harness,
route_identity.project_root,
);
client.record_stopped_route(StoppedRoute {
target: holder.to_string(),
session: route_identity.session.clone(),
harness: route_identity.harness.clone(),
project_root: route_identity.project_root.clone(),
code,
message,
stopped_at_unix_ms: unix_now_ms(),
});
if refused_identities.len() >= MAX_STOPPED_ROUTES {
refused_identities.pop_front();
}
refused_identities.push_back(route_identity.clone());
client.set_route_live(false);
}
Err(RouteOpenFailure::Transient(error)) => {
if discovery_backoff == DISCOVERY_INITIAL_BACKOFF {
log::info!(
"fleet status dial: {holder} route unavailable for session {}: {error}; retrying with backoff",
route_identity.session,
);
} else {
log::debug!("fleet status dial: route unavailable: {error}");
}
client.set_route_live(false);
}
}
}
client.set_route_live(route.is_some());
if route.is_some()
|| reopen_forbidden.is_some()
|| refused_identities.contains(&route_identity)
{
next_discovery_at = tokio::time::Instant::now() + discovery_cadence;
} else {
next_discovery_at = tokio::time::Instant::now() + discovery_backoff;
discovery_backoff = next_discovery_backoff(discovery_backoff);
}
}
Ok(catalog) => {
catalog_generation = Some(catalog.generation);
if let Some(opened_route) = route.take() {
let _ = consumer.close_handle(&opened_route).await;
}
route_events = None;
client.set_route_live(false);
discovery_backoff = DISCOVERY_INITIAL_BACKOFF;
next_discovery_at = tokio::time::Instant::now() + discovery_cadence;
}
Err(error) => {
route = None;
route_events = None;
client.set_route_live(false);
log::debug!("fleet status dial: catalog unavailable: {error}");
next_discovery_at = tokio::time::Instant::now() + discovery_backoff;
discovery_backoff = next_discovery_backoff(discovery_backoff);
}
}
}
if let Some(request) = pending_request.take() {
if route.is_none() {
let requested = FleetRouteIdentity::from(&request);
if requested != route_identity
&& refused_identities.contains(&route_identity)
&& !refused_identities.contains(&requested)
{
route_identity = requested;
discovery_backoff = DISCOVERY_INITIAL_BACKOFF;
next_discovery_at = tokio::time::Instant::now();
pending_request = Some(request);
continue;
}
}
let Some(opened_route) = route.as_ref() else {
request.complete_unavailable();
continue;
};
let body = match encode_status_publish_call(request.body()) {
Some(body) => body,
None => {
request.complete_unavailable();
continue;
}
};
match consumer.request(opened_route, body).await {
Ok(response) => {
if !complete_status_publish_call(request, &response) {
route = None;
route_events = None;
client.set_route_live(false);
next_discovery_at = tokio::time::Instant::now();
}
}
Err(error) => {
log::debug!("fleet status dial: publish unavailable: {error}");
request.complete_unavailable();
route = None;
route_events = None;
client.set_route_live(false);
next_discovery_at = tokio::time::Instant::now();
}
}
continue;
}
let next_wake_at = if catalog_watch.is_some() {
next_discovery_at
} else {
next_discovery_at.min(next_watch_at)
};
tokio::select! {
maybe_request = wire_rx.recv() => {
let Some(request) = maybe_request else {
client.set_route_live(false);
return;
};
pending_request = Some(request);
}
maybe_state = connection_state_rx.recv() => {
match maybe_state {
Some(state @ (ConnectionState::Dropped | ConnectionState::Restored { .. })) => {
if matches!(state, ConnectionState::Restored { .. }) {
reopen_forbidden = None;
}
last_route_channel = None;
route = None;
route_events = None;
catalog_watch = None;
catalog_generation = None;
next_watch_at = tokio::time::Instant::now();
client.set_route_live(false);
next_discovery_at = tokio::time::Instant::now();
}
None => {}
}
}
maybe_push = async {
control_pushes
.as_mut()
.expect("control push receiver guarded by select condition")
.recv()
.await
}, if control_pushes.is_some() => {
match maybe_push {
Some(push) => {
if record_forbidden_reopen(&push, last_route_channel, &mut reopen_forbidden) {
route = None;
route_events = None;
client.set_route_live(false);
}
}
None => control_pushes = None,
}
}
maybe_event = async {
route_events
.as_mut()
.expect("route event receiver guarded by select condition")
.recv()
.await
}, if route_events.is_some() => {
if maybe_event.is_none() {
if let Some(receiver) = control_pushes.as_mut() {
while let Ok(push) = receiver.try_recv() {
record_forbidden_reopen(&push, last_route_channel, &mut reopen_forbidden);
}
}
route = None;
route_events = None;
client.set_route_live(false);
next_discovery_at = tokio::time::Instant::now();
}
}
generation = async {
catalog_watch.as_mut().expect("watch guarded by select condition")
.next_generation().await
}, if catalog_watch.is_some() => {
match generation {
Ok(Some(generation)) => {
if catalog_generation.is_none_or(|known| generation > known) {
next_discovery_at = tokio::time::Instant::now();
}
}
Ok(None) | Err(_) => {
catalog_watch = None;
next_watch_at = tokio::time::Instant::now() + STATUS_CADENCE;
next_discovery_at = next_discovery_at.min(next_watch_at);
}
}
}
_ = tokio::time::sleep_until(next_wake_at) => {}
}
}
}
}
fn encode_status_publish_call(body: &Value) -> Option<Vec<u8>> {
let mut params = body.as_object()?.clone();
let method = params.remove("op")?.as_str()?.to_owned();
if method != "status.publish" {
return None;
}
serde_json::to_vec(&json!({
"method": method,
"params": params,
}))
.ok()
}
fn complete_status_publish_call(request: StatusWireRequest, body: &[u8]) -> bool {
let result = serde_json::from_slice::<Value>(body)
.ok()
.and_then(|response| response.get("result").cloned())
.and_then(|result| serde_json::to_vec(&result).ok());
let Some(result) = result else {
request.complete_unavailable();
return false;
};
request.complete_response(&result)
}
fn status_holder(entries: &[subc_client_rs::CatalogEntry]) -> Option<&'static str> {
entries
.iter()
.any(|entry| {
entry.module_id == STATUS_HOLDER_MODULE && entry.roles.iter().any(|role| {
matches!(
role,
ProviderRole::ManagementSurface { operations, .. }
if operations.iter().any(|operation| operation.name == STATUS_LINE_OPERATION)
)
})
})
.then_some(STATUS_HOLDER_MODULE)
}
const CONTROL_PUSH_CAPACITY: usize = 16;
fn close_forbids_reopen(reason: &str) -> bool {
if matches!(
RouteCloseReason::from_wire(reason),
RouteCloseReason::AuthorityChanged
) {
return false;
}
reason.starts_with("scope_")
|| matches!(
RouteCloseReason::from_wire(reason),
RouteCloseReason::Unknown(_)
)
}
fn push_names_dial_route(push: &ControlPush, last_route_channel: Option<u16>) -> bool {
let channels: Vec<u64> = push
.body
.get("channels")
.and_then(Value::as_array)
.map(|channels| channels.iter().filter_map(Value::as_u64).collect())
.unwrap_or_default();
channels.is_empty()
|| last_route_channel.is_some_and(|channel| channels.contains(&u64::from(channel)))
}
fn record_forbidden_reopen(
push: &ControlPush,
last_route_channel: Option<u16>,
reopen_forbidden: &mut Option<String>,
) -> bool {
if !push
.body
.get("module_id")
.and_then(Value::as_str)
.is_some_and(crate::prefrontal::is_module)
{
return false;
}
if !push_names_dial_route(push, last_route_channel) {
return false;
}
let Some(reason) = push
.route_close_reason()
.and_then(|_| push.body.get("reason").and_then(Value::as_str))
else {
return false;
};
if !close_forbids_reopen(reason) {
return false;
}
log::info!("fleet status dial: holder route closed ({reason}); not reopening it");
*reopen_forbidden = Some(reason.to_owned());
true
}
fn next_discovery_backoff(current: Duration) -> Duration {
current
.checked_mul(2)
.unwrap_or(DISCOVERY_MAX_BACKOFF)
.min(DISCOVERY_MAX_BACKOFF)
}
#[cfg(any(test, feature = "test-support"))]
#[allow(dead_code, unused_imports)]
pub mod tests {
use super::*;
#[cfg(test)]
use serde_json::Map;
#[cfg(test)]
use std::collections::HashSet;
use subc_protocol::manifest::{ManagementOperation, ManagementOperationKind};
#[cfg(test)]
const FIXTURES: &str =
include_str!("../../aft/tests/fixtures/status_line/status-line-fixtures-2026-08-14.json");
#[cfg(test)]
const PUBLISH_ACK_FIXTURES: [&str; 9] = [
"publish_aft",
"supersede_r3",
"supersede_r2_late",
"ttl_publish",
"quiet_publish_empty_text",
"fat1",
"fat2",
"epoch_bump_republish_r1_new_conn",
"publish_aft_project",
];
#[cfg(test)]
const LINE_REPLY_FIXTURES: [&str; 9] = [
"line_foreign_present",
"supersede_line_after_r3",
"supersede_line_after_late_r2",
"ttl_line_before",
"ttl_line_after_expiry",
"quiet_line",
"line_cap_overflow",
"epoch_bump_line_after",
"line_aft_solo_scope",
];
#[cfg(test)]
fn fixtures() -> Map<String, Value> {
serde_json::from_str::<Value>(FIXTURES)
.expect("producer fixture JSON")
.as_object()
.expect("producer fixture object")
.clone()
}
#[cfg(test)]
fn parse_line(value: &Value) -> StatusLineSnapshot {
StatusLineSnapshot::parse(&serde_json::to_vec(value).expect("fixture bytes"))
.expect("status.line fixture")
}
#[cfg(test)]
fn parse_ack(value: &Value) -> StatusPublishAck {
StatusPublishAck::parse(&serde_json::to_vec(value).expect("fixture bytes"))
.expect("status.publish fixture")
}
fn status_catalog_entry(module_id: &str, operation: &str) -> subc_client_rs::CatalogEntry {
serde_json::from_value(json!({
"module_id": module_id,
"ready": true,
"roles": [ProviderRole::ManagementSurface {
operations: vec![ManagementOperation {
name: operation.to_string(),
kind: ManagementOperationKind::Query,
description: None,
}],
config_schema: Value::Null,
observability: Vec::new(),
identity_scope: Vec::new(),
concurrency: Default::default(),
}],
"control_ops": [],
}))
.unwrap()
}
#[derive(Default)]
pub struct FakeCatalogWatch {
available: std::sync::atomic::AtomicBool,
legacy_only: std::sync::atomic::AtomicBool,
targets: parking_lot::Mutex<Vec<String>>,
generation: AtomicU64,
sender: parking_lot::Mutex<Option<mpsc::Sender<u64>>>,
}
impl StatusCatalogWatch for mpsc::Receiver<u64> {
async fn next_generation(&mut self) -> Result<Option<u64>, String> {
Ok(self.recv().await)
}
}
pub struct RejectingConsumer {
pub attempts: Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
pub advertises_status_line: bool,
pub catalog_calls: Arc<AtomicU64>,
pub publish_calls: Arc<AtomicU64>,
pub succeeds_on: Option<usize>,
pub failure: RouteOpenFailure,
pub connection_callback:
Arc<parking_lot::Mutex<Option<Box<dyn Fn(ConnectionState) + Send>>>>,
pub push_sender: Arc<parking_lot::Mutex<Option<mpsc::Sender<PushEvent>>>>,
pub control_sender: Arc<parking_lot::Mutex<Option<mpsc::Sender<ControlPush>>>>,
pub watch: Arc<FakeCatalogWatch>,
}
impl StatusConsumer for RejectingConsumer {
type Route = usize;
type CatalogWatch = mpsc::Receiver<u64>;
fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static) {
*self.connection_callback.lock() = Some(Box::new(cb));
}
fn control_pushes(&self) -> mpsc::Receiver<ControlPush> {
let (tx, rx) = mpsc::channel(CONTROL_PUSH_CAPACITY);
*self.control_sender.lock() = Some(tx);
rx
}
async fn catalog_list(&self) -> Result<CatalogList, String> {
self.catalog_calls.fetch_add(1, Ordering::Relaxed);
Ok(CatalogList {
generation: self.watch.generation.load(Ordering::Relaxed).max(1),
modules: if self.advertises_status_line {
vec![status_catalog_entry(
if self.watch.legacy_only.load(Ordering::Relaxed) {
"prefrontal-core"
} else {
STATUS_HOLDER_MODULE
},
STATUS_LINE_OPERATION,
)]
} else {
Vec::new()
},
subc_ops: Vec::new(),
})
}
async fn catalog_watch(&self) -> Result<Self::CatalogWatch, String> {
if !self.watch.available.load(Ordering::Relaxed) {
return Err("catalog.watch unavailable".into());
}
let (tx, rx) = mpsc::channel(8);
tx.try_send(self.watch.generation.load(Ordering::Relaxed).max(1))
.unwrap();
*self.watch.sender.lock() = Some(tx);
Ok(rx)
}
async fn open_route(
&self,
target: RouteTarget,
_identity: BindIdentity,
) -> Result<usize, RouteOpenFailure> {
let mut attempts = self.attempts.lock();
if let RouteTarget::ManagementSurface { module_id } = target {
self.watch.targets.lock().push(module_id);
}
attempts.push(tokio::time::Instant::now());
if self.succeeds_on == Some(attempts.len()) {
Ok(attempts.len())
} else {
Err(self.failure.clone())
}
}
fn push_events(&self, _route: &usize) -> Result<mpsc::Receiver<PushEvent>, String> {
let (tx, rx) = mpsc::channel(1);
*self.push_sender.lock() = Some(tx);
Ok(rx)
}
fn route_channel(&self, route: &usize) -> u16 {
u16::try_from(*route).expect("test routes are small")
}
async fn close_handle(&self, _route: &usize) -> Result<(), String> {
Ok(())
}
async fn request(&self, _route: &usize, _body: Vec<u8>) -> Result<Vec<u8>, String> {
self.publish_calls.fetch_add(1, Ordering::Relaxed);
Err("not used in discovery test".to_owned())
}
}
fn transient_failure() -> RouteOpenFailure {
RouteOpenFailure::Transient("route.open refused: module_reloading".to_owned())
}
async fn watch_dial(
succeeds_on: usize,
) -> (
tokio::task::JoinHandle<()>,
Arc<AtomicU64>,
Arc<FakeCatalogWatch>,
Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
) {
let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
client.publish(Path::new("/tmp/project"), "opencode", "session", "local");
let request = wire_rx.try_recv().unwrap();
let identity = FleetRouteIdentity::from(&request);
request.complete_unavailable();
let catalog_calls = Arc::new(AtomicU64::new(0));
let watch = Arc::new(FakeCatalogWatch::default());
watch.available.store(true, Ordering::Relaxed);
let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
let consumer = RejectingConsumer {
attempts: attempts.clone(),
succeeds_on: Some(succeeds_on),
failure: transient_failure(),
advertises_status_line: true,
catalog_calls: catalog_calls.clone(),
publish_calls: Arc::default(),
connection_callback: Arc::default(),
push_sender: Arc::default(),
control_sender: Arc::default(),
watch: watch.clone(),
};
let task = tokio::spawn(run_connected_status_dial(
consumer, client, wire_rx, identity, None,
));
settle_dial().await;
assert_eq!(catalog_calls.load(Ordering::Relaxed), 1);
(task, catalog_calls, watch, attempts)
}
async fn settle_dial() {
for _ in 0..8 {
tokio::task::yield_now().await;
}
}
#[tokio::test(start_paused = true)]
async fn status_dial_ignores_the_legacy_advertiser_on_catalog_change() {
let (task, _, watch, _) = watch_dial(1).await;
assert_eq!(*watch.targets.lock(), ["prefrontal"]);
watch.legacy_only.store(true, Ordering::Relaxed);
watch.generation.store(2, Ordering::Relaxed);
watch.sender.lock().as_ref().unwrap().try_send(2).unwrap();
settle_dial().await;
assert_eq!(*watch.targets.lock(), ["prefrontal"]);
task.abort();
let _ = task.await;
}
#[tokio::test(start_paused = true)]
async fn initial_status_discovery_retains_the_queued_publish_cadence() {
let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
client.publish(
Path::new("/queued-project"),
"opencode",
"session",
"status",
);
let request = wire_rx.try_recv().unwrap();
let identity = FleetRouteIdentity::from(&request);
let queued = client.inner.state.lock().last_publish_at.clone();
assert_eq!(queued.len(), 1);
let watch = Arc::new(FakeCatalogWatch::default());
watch.available.store(true, Ordering::Relaxed);
let consumer = RejectingConsumer {
attempts: Arc::default(),
succeeds_on: Some(1),
failure: transient_failure(),
advertises_status_line: true,
catalog_calls: Arc::default(),
publish_calls: Arc::default(),
connection_callback: Arc::default(),
push_sender: Arc::default(),
control_sender: Arc::default(),
watch,
};
let task = tokio::spawn(run_connected_status_dial(
consumer,
client.clone(),
wire_rx,
identity,
None,
));
settle_dial().await;
assert!(client.inner.route_live.load(Ordering::Acquire));
assert_eq!(client.inner.state.lock().last_publish_at, queued);
task.abort();
let _ = task.await;
}
#[test]
fn status_discovery_and_close_push_accept_only_prefrontal() {
for module in ["prefrontal", "prefrontal-core", "other"] {
let accepted = module == "prefrontal";
assert_eq!(
status_holder(&[status_catalog_entry(module, STATUS_LINE_OPERATION)]),
accepted.then_some(module)
);
let push = ControlPush {
op: "route.closed".into(),
body: json!({"op":"route.closed", "module_id":module, "reason":"scope_ended"}),
};
let mut forbidden = None;
assert_eq!(
record_forbidden_reopen(&push, None, &mut forbidden),
accepted
);
}
}
#[tokio::test(start_paused = true)]
async fn catalog_watch_transient_open_failure_retries_before_backstop() {
let (task, calls, watch, attempts) = watch_dial(2).await;
assert!(watch.sender.lock().is_some());
assert_eq!(attempts.lock().len(), 1);
tokio::time::advance(DISCOVERY_INITIAL_BACKOFF).await;
settle_dial().await;
assert_eq!(attempts.lock().len(), 2, "route recovered on its retry");
assert_eq!(calls.load(Ordering::Relaxed), 2);
tokio::time::advance(Duration::from_secs(30)).await;
settle_dial().await;
assert_eq!(attempts.lock().len(), 2);
assert_eq!(calls.load(Ordering::Relaxed), 2);
task.abort();
}
#[tokio::test(start_paused = true)]
async fn catalog_watch_new_generation_rediscovers_without_waiting_for_a_poll() {
let (task, calls, watch, _) = watch_dial(1).await;
watch.generation.store(2, Ordering::Relaxed);
watch.sender.lock().as_ref().unwrap().try_send(2).unwrap();
settle_dial().await;
assert_eq!(calls.load(Ordering::Relaxed), 2);
task.abort();
}
#[tokio::test(start_paused = true)]
async fn catalog_watch_unchanged_generation_waits_for_five_minute_backstop() {
let (task, calls, watch, _) = watch_dial(1).await;
watch.sender.lock().as_ref().unwrap().try_send(1).unwrap();
for _ in 0..12 {
tokio::time::advance(STATUS_CADENCE).await;
settle_dial().await;
}
assert_eq!(
calls.load(Ordering::Relaxed),
1,
"no discovery in 30 seconds"
);
tokio::time::advance(CATALOG_BACKSTOP - Duration::from_secs(30)).await;
settle_dial().await;
assert_eq!(calls.load(Ordering::Relaxed), 2, "backstop still refreshes");
task.abort();
}
#[tokio::test(start_paused = true)]
async fn catalog_watch_drop_falls_back_to_polling_and_recovers() {
let (task, calls, watch, _) = watch_dial(1).await;
watch.available.store(false, Ordering::Relaxed);
watch.sender.lock().take();
settle_dial().await;
for expected in [2, 3] {
tokio::time::advance(STATUS_CADENCE).await;
settle_dial().await;
assert_eq!(calls.load(Ordering::Relaxed), expected);
}
watch.available.store(true, Ordering::Relaxed);
tokio::time::advance(STATUS_CADENCE).await;
settle_dial().await;
assert_eq!(calls.load(Ordering::Relaxed), 4, "recovery refreshes once");
tokio::time::advance(Duration::from_secs(30)).await;
settle_dial().await;
assert_eq!(
calls.load(Ordering::Relaxed),
4,
"recovered feed stops fast polling"
);
watch.generation.store(3, Ordering::Relaxed);
watch.sender.lock().as_ref().unwrap().try_send(3).unwrap();
settle_dial().await;
assert_eq!(calls.load(Ordering::Relaxed), 5);
task.abort();
}
fn terminal_refusal() -> RouteOpenFailure {
RouteOpenFailure::Refused {
code: "project_origin_unclassifiable".to_owned(),
message: "the project origin could not be classified".to_owned(),
}
}
async fn dial_with_rejections(
succeeds_on: Option<usize>,
) -> (
tokio::task::JoinHandle<()>,
Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
Arc<parking_lot::Mutex<Option<Box<dyn Fn(ConnectionState) + Send>>>>,
) {
let (task, attempts, callback, _client) =
dial_failing_with(succeeds_on, transient_failure(), "session-1").await;
(task, attempts, callback)
}
async fn dial_failing_with(
succeeds_on: Option<usize>,
failure: RouteOpenFailure,
session: &str,
) -> (
tokio::task::JoinHandle<()>,
Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
Arc<parking_lot::Mutex<Option<Box<dyn Fn(ConnectionState) + Send>>>>,
FleetStatusClient,
) {
let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
assert!(!client.publish(Path::new("/tmp/project"), "opencode", session, "local"));
let first_request = wire_rx.try_recv().expect("first discovery request");
let identity = FleetRouteIdentity::from(&first_request);
let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
let callback = Arc::new(parking_lot::Mutex::new(None));
let consumer = RejectingConsumer {
attempts: attempts.clone(),
advertises_status_line: true,
catalog_calls: Arc::default(),
publish_calls: Arc::default(),
succeeds_on,
failure,
connection_callback: callback.clone(),
push_sender: Arc::default(),
control_sender: Arc::default(),
watch: Arc::default(),
};
let task = tokio::spawn(run_connected_status_dial(
consumer,
client.clone(),
wire_rx,
identity,
Some(first_request),
));
tokio::task::yield_now().await;
(task, attempts, callback, client)
}
#[tokio::test]
async fn subc_bridge_without_discovered_status_line_surface_emits_no_status_requests() {
let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
assert!(!client.publish(Path::new("/project"), "opencode", "session-1", "local"));
let first_request = wire_rx.try_recv().expect("queued discovery publish");
assert_eq!(first_request.body()["op"], "status.publish");
assert_eq!(client.inner.state.lock().last_publish_at.len(), 1);
let identity = FleetRouteIdentity::from(&first_request);
let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
let catalog_calls = Arc::new(AtomicU64::new(0));
let publish_calls = Arc::new(AtomicU64::new(0));
let consumer = RejectingConsumer {
attempts: attempts.clone(),
advertises_status_line: false,
catalog_calls: catalog_calls.clone(),
publish_calls: publish_calls.clone(),
succeeds_on: Some(1),
failure: transient_failure(),
connection_callback: Arc::default(),
push_sender: Arc::default(),
control_sender: Arc::default(),
watch: Arc::default(),
};
wire_rx.close();
tokio::time::timeout(
Duration::from_secs(5),
run_connected_status_dial(
consumer,
client.clone(),
wire_rx,
identity,
Some(first_request),
),
)
.await
.expect("empty-catalog dial must finish processing the queued publish");
assert!(
attempts.lock().is_empty(),
"empty catalog must not open a holder route"
);
assert_eq!(
publish_calls.load(Ordering::Relaxed),
0,
"empty catalog must not send status requests"
);
assert_eq!(
catalog_calls.load(Ordering::Relaxed),
1,
"catalog gate was exercised"
);
assert!(!client.inner.route_live.load(Ordering::Acquire));
assert!(
client.inner.state.lock().last_publish_at.is_empty(),
"unavailable publish must release its cadence reservation"
);
}
async fn route_opens_after_holder_close(reason: &str) -> usize {
route_opens_after_holder_close_naming(reason, None).await
}
async fn route_opens_after_holder_close_naming(
reason: &str,
channels: Option<&[u16]>,
) -> usize {
let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
assert!(!client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
let first_request = wire_rx.try_recv().expect("first discovery request");
let identity = FleetRouteIdentity::from(&first_request);
first_request.complete_unavailable();
let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
let push_sender = Arc::new(parking_lot::Mutex::new(None));
let control_sender = Arc::new(parking_lot::Mutex::new(None));
let consumer = RejectingConsumer {
attempts: attempts.clone(),
succeeds_on: Some(1),
failure: transient_failure(),
advertises_status_line: true,
catalog_calls: Arc::default(),
publish_calls: Arc::default(),
connection_callback: Arc::default(),
push_sender: push_sender.clone(),
control_sender: control_sender.clone(),
watch: Arc::default(),
};
let task = tokio::spawn(run_connected_status_dial(
consumer, client, wire_rx, identity, None,
));
for _ in 0..4 {
tokio::task::yield_now().await;
}
assert_eq!(attempts.lock().len(), 1, "the holder route opened");
let mut body = json!({
"op": "route.closed",
"module_id": STATUS_HOLDER_MODULE,
"reason": reason,
});
if let Some(channels) = channels {
body["channels"] = json!(channels);
}
let push = ControlPush {
op: "route.closed".to_owned(),
body,
};
control_sender
.lock()
.as_ref()
.expect("dial registered for control pushes")
.try_send(push)
.expect("queue route.closed");
push_sender.lock().take();
for _ in 0..3 {
tokio::time::advance(STATUS_CADENCE).await;
for _ in 0..4 {
tokio::task::yield_now().await;
}
}
task.abort();
let opens = attempts.lock().len();
opens
}
#[tokio::test(start_paused = true)]
async fn scope_and_unknown_route_closes_never_reopen_the_holder_route() {
for reason in [
"scope_ended",
"scope_carrier_removed",
"scope_delegation_changed",
"scope_parent_ended",
"a_reason_from_a_newer_daemon",
] {
assert_eq!(
route_opens_after_holder_close(reason).await,
1,
"a {reason} close must not reopen the route"
);
}
assert!(
route_opens_after_holder_close("reload").await > 1,
"a reload close still reopens on the next discovery"
);
}
#[tokio::test(start_paused = true)]
async fn authority_changed_reopens_the_holder_route() {
assert!(route_opens_after_holder_close("authority_changed").await > 1);
}
#[tokio::test(start_paused = true)]
async fn a_scope_close_naming_channels_applies_only_to_the_dial_route() {
assert_eq!(
route_opens_after_holder_close_naming("scope_ended", Some(&[1])).await,
1,
"a scope close naming the dial's channel must not reopen the route"
);
assert!(
route_opens_after_holder_close_naming("scope_ended", Some(&[7, 9])).await > 1,
"a scope close naming only other channels is not about the dial's route"
);
}
async fn advance_and_observe(
attempts: &Arc<parking_lot::Mutex<Vec<tokio::time::Instant>>>,
elapsed: Duration,
expected: usize,
) {
tokio::time::advance(elapsed).await;
tokio::task::yield_now().await;
assert_eq!(
attempts.lock().len(),
expected,
"attempt count after {elapsed:?}"
);
}
async fn advance_in_steps(total: Duration) {
let steps = total.as_millis() / DISCOVERY_INITIAL_BACKOFF.as_millis();
for _ in 0..steps {
tokio::time::advance(DISCOVERY_INITIAL_BACKOFF).await;
tokio::task::yield_now().await;
}
}
#[tokio::test(start_paused = true)]
async fn transient_open_failures_back_off_with_growing_gaps_to_a_bound() {
let (task, attempts, _) = dial_with_rejections(None).await;
advance_in_steps(Duration::from_secs(200)).await;
let opened_at = attempts.lock().clone();
task.abort();
let gaps: Vec<_> = opened_at.windows(2).map(|pair| pair[1] - pair[0]).collect();
assert_eq!(
gaps,
vec![
Duration::from_millis(250),
Duration::from_millis(500),
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(4),
Duration::from_secs(8),
Duration::from_secs(16),
Duration::from_secs(32),
DISCOVERY_MAX_BACKOFF,
DISCOVERY_MAX_BACKOFF,
],
"a restarting holder is retried with doubling gaps up to the bound"
);
}
#[tokio::test(start_paused = true)]
async fn terminal_refusal_gets_one_open_attempt_per_session() {
let session = "terminal-refusal-session-1";
let (task, attempts, _, client) =
dial_failing_with(None, terminal_refusal(), session).await;
advance_in_steps(Duration::from_secs(600)).await;
for _ in 0..3 {
client.publish(Path::new("/tmp/project"), "opencode", session, "local");
advance_in_steps(Duration::from_secs(5)).await;
}
assert_eq!(
attempts.lock().len(),
1,
"a terminal refusal ends the route opens for its session"
);
let stopped = client
.stopped_route()
.expect("the stopped route is recorded");
assert_eq!(stopped.session, session);
assert_eq!(stopped.target, STATUS_HOLDER_MODULE);
assert_eq!(stopped.code, "project_origin_unclassifiable");
let health = stopped_routes_snapshot();
assert!(
health
.as_array()
.expect("stopped routes are a list")
.iter()
.any(|row| {
row["session"] == session
&& row["target"] == STATUS_HOLDER_MODULE
&& row["refusal"]["code"] == "project_origin_unclassifiable"
}),
"the health report names the stopped route: {health}"
);
let other = "terminal-refusal-session-2";
client.publish(Path::new("/tmp/other-project"), "opencode", other, "local");
advance_in_steps(Duration::from_secs(600)).await;
assert_eq!(attempts.lock().len(), 2, "one open for the second session");
assert_eq!(
client.stopped_route().map(|stopped| stopped.session),
Some(other.to_owned())
);
for _ in 0..3 {
client.publish(Path::new("/tmp/project"), "opencode", session, "local");
advance_in_steps(Duration::from_secs(5)).await;
client.publish(Path::new("/tmp/other-project"), "opencode", other, "local");
advance_in_steps(Duration::from_secs(5)).await;
}
advance_in_steps(Duration::from_secs(600)).await;
assert_eq!(
attempts.lock().len(),
2,
"alternating refused sessions reopened a refused route"
);
let stopped: Vec<_> = client
.stopped_routes()
.into_iter()
.map(|stopped| stopped.session)
.collect();
assert_eq!(stopped, vec![session.to_owned(), other.to_owned()]);
task.abort();
}
async fn refusing_daemon(
code: &'static str,
) -> (tempfile::TempDir, std::path::PathBuf, Arc<AtomicU64>) {
use subc_protocol::{
Flags, Frame, FrameType, ModuleHelloAckBody, Priority, PROTOCOL_VERSION,
};
use subc_transport::connection_file::{self, ConnectionInfo, Endpoint, SCHEMA_VERSION};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let key = vec![0x42; subc_transport::KEY_LEN];
let daemon_id = [0x24; subc_transport::DAEMON_ID_LEN];
let opens = Arc::new(AtomicU64::new(0));
let server_opens = Arc::clone(&opens);
let server_key = key.clone();
tokio::spawn(async move {
let flags = Flags::new(false, Priority::Passive, false);
while let Ok((mut stream, _)) = listener.accept().await {
let key = server_key.clone();
let opens = Arc::clone(&server_opens);
tokio::spawn(async move {
if subc_transport::authenticate_server(
&mut stream,
&key,
&daemon_id,
"0.39.0",
Duration::from_secs(5),
)
.await
.is_err()
{
return;
}
while let Ok(Some(frame)) = crate::subc_fake::read_frame(&mut stream).await {
let header = frame.header;
let reply = match header.ty {
FrameType::Hello => Frame::build(
FrameType::HelloAck,
flags,
0,
0,
header.corr,
serde_json::to_vec(&ModuleHelloAckBody {
negotiated_ver: PROTOCOL_VERSION,
subc_ops: Vec::new(),
subc_capabilities: Vec::new(),
storage: None,
machine_id: None,
})
.unwrap(),
)
.unwrap(),
FrameType::Request if header.channel == 0 => {
let body: Value =
serde_json::from_slice(&frame.body).unwrap_or(Value::Null);
if body.get("op").and_then(Value::as_str) != Some("route.open") {
continue;
}
opens.fetch_add(1, Ordering::Relaxed);
Frame::build(
FrameType::Error,
flags,
0,
0,
header.corr,
serde_json::to_vec(&subc_protocol::ErrorBody::new(
code,
"refused by the fake daemon",
))
.unwrap(),
)
.unwrap()
}
_ => continue,
};
if subc_transport::write_frame(&mut stream, &reply)
.await
.is_err()
{
return;
}
}
});
}
});
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("connection.json");
connection_file::write_atomic(
&file,
&ConnectionInfo {
schema: SCHEMA_VERSION,
wire_version: Some(PROTOCOL_VERSION),
endpoints: vec![Endpoint {
host: "127.0.0.1".to_string(),
port,
}],
key,
daemon_id,
pid: std::process::id(),
daemon_ver: "0.39.0".to_string(),
},
)
.unwrap();
(dir, file, opens)
}
async fn connect_to(file: &Path) -> SubcConsumer {
SubcConsumer::connect(
file,
ConsumerOptions {
call_timeout: Duration::from_secs(5),
..ConsumerOptions::default()
},
)
.await
.expect("the fake daemon accepts the connection")
}
fn holder_target() -> RouteTarget {
RouteTarget::ManagementSurface {
module_id: STATUS_HOLDER_MODULE.to_string(),
}
}
#[tokio::test]
async fn a_holder_refusal_through_the_subc_client_is_terminal_and_sent_once() {
let (_dir, file, opens) = refusing_daemon("project_origin_unclassifiable").await;
let consumer = connect_to(&file).await;
let failure = StatusConsumer::open_route(
&consumer,
holder_target(),
BindIdentity::new("runner", "session-1"),
)
.await
.expect_err("the fake daemon refuses every open");
assert_eq!(
failure,
RouteOpenFailure::Refused {
code: "project_origin_unclassifiable".to_owned(),
message: "refused by the fake daemon".to_owned(),
}
);
assert_eq!(opens.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn a_reloading_holder_through_the_subc_client_is_transient() {
let (_dir, file, opens) = refusing_daemon("module_reloading").await;
let consumer = connect_to(&file).await;
let error = SubcConsumer::open_route(
&consumer,
holder_target(),
BindIdentity::new("runner", "session-1"),
CallOptions {
timeout: Duration::from_millis(400),
route_retry_deadline: Duration::from_millis(400),
..CallOptions::default()
},
)
.await
.expect_err("the fake daemon refuses every open");
assert!(
matches!(
RouteOpenFailure::from_call_error(&error),
RouteOpenFailure::Transient(_)
),
"{error}"
);
assert!(opens.load(Ordering::Relaxed) >= 1);
}
#[tokio::test(start_paused = true)]
async fn successful_bind_resets_rejection_backoff() {
let (task, attempts, callback) = dial_with_rejections(Some(4)).await;
for (elapsed, expected) in [
(Duration::from_millis(250), 2),
(Duration::from_millis(500), 3),
(Duration::from_secs(1), 4),
] {
advance_and_observe(&attempts, elapsed, expected).await;
}
callback.lock().as_ref().expect("connection callback")(ConnectionState::Dropped);
tokio::task::yield_now().await;
assert_eq!(attempts.lock().len(), 5, "drop rediscovers immediately");
let fifth = attempts.lock()[4];
advance_and_observe(&attempts, Duration::from_millis(250), 6).await;
assert_eq!(attempts.lock()[5] - fifth, DISCOVERY_INITIAL_BACKOFF);
task.abort();
}
#[test]
fn publish_ack_tolerates_fields_a_newer_holder_adds() {
let ack = StatusPublishAck::parse(
br#"{"epoch":3,"accepted_revision":7,"last_read_at_ms":1790115735811,"future_field":{"nested":true}}"#,
)
.expect("an ack carrying unknown keys still parses");
assert_eq!(
ack,
StatusPublishAck {
epoch: 3,
accepted_revision: 7,
last_read_at_ms: Some(1790115735811),
}
);
let null_read =
StatusPublishAck::parse(br#"{"epoch":3,"accepted_revision":7,"last_read_at_ms":null}"#);
assert_eq!(
null_read
.expect("a null last_read_at_ms still parses")
.last_read_at_ms,
None
);
}
#[test]
fn publish_ack_fixtures_drive_runtime_fencing() {
let fixtures = fixtures();
assert_eq!(fixtures.len(), 18, "fixture probe entry count changed");
let mut fence = PublishFence::default();
for name in PUBLISH_ACK_FIXTURES {
fence.observe(parse_ack(&fixtures[name]));
}
assert_eq!(
fence,
PublishFence {
epoch: 4,
accepted_revision: 1
}
);
}
#[test]
fn line_reply_fixtures_remain_wire_shape_documentation() {
let fixtures = fixtures();
let documented = PUBLISH_ACK_FIXTURES
.into_iter()
.chain(LINE_REPLY_FIXTURES)
.collect::<HashSet<_>>();
assert_eq!(documented.len(), fixtures.len());
assert!(fixtures
.keys()
.all(|name| documented.contains(name.as_str())));
let lines = LINE_REPLY_FIXTURES
.into_iter()
.map(|name| (name, parse_line(&fixtures[name])))
.collect::<HashMap<_, _>>();
assert_eq!(
lines["line_foreign_present"].line,
"aft E0 W0 idx fresh | pfc 1567 events (777 gaps)"
);
assert!(lines["line_foreign_present"].has_foreign_segment());
assert_eq!(
lines["supersede_line_after_r3"],
lines["supersede_line_after_late_r2"]
);
assert!(lines["supersede_line_after_late_r2"]
.line
.contains("revision three"));
assert_eq!(lines["ttl_line_before"].segments.len(), 4);
assert_eq!(lines["ttl_line_after_expiry"].segments.len(), 3);
assert_eq!(
lines["quiet_line"]
.segments
.last()
.map(|segment| segment.text.as_str()),
Some("")
);
assert!(!lines["quiet_line"].line.contains("ttlfx"));
let capped = &lines["line_cap_overflow"];
assert!(capped.line.chars().count() <= 200);
assert_eq!(
capped.segments.len(),
6,
"the cap must not truncate segments[]"
);
assert!(
!capped.line.contains("fat2"),
"whole tail segments are dropped"
);
assert_eq!(
lines["epoch_bump_line_after"].segments[3].text,
"fresh epoch revision one"
);
assert!(!lines["line_aft_solo_scope"].has_foreign_segment());
}
#[test]
fn publication_fence_drops_regressions_but_new_epoch_wins() {
let fixtures = fixtures();
let mut fence = PublishFence::default();
fence.observe(parse_ack(&fixtures["supersede_r3"]));
fence.observe(StatusPublishAck {
epoch: 3,
accepted_revision: 2,
last_read_at_ms: None,
});
assert_eq!(
fence,
PublishFence {
epoch: 3,
accepted_revision: 3
}
);
fence.observe(parse_ack(&fixtures["epoch_bump_republish_r1_new_conn"]));
assert_eq!(
fence,
PublishFence {
epoch: 4,
accepted_revision: 1
}
);
}
#[test]
fn catalog_gate_requires_matching_module_management_role_and_exact_operation() {
assert!(status_holder(&[status_catalog_entry(
STATUS_HOLDER_MODULE,
STATUS_LINE_OPERATION,
)])
.is_some());
assert!(
status_holder(&[status_catalog_entry("other-module", STATUS_LINE_OPERATION,)])
.is_none()
);
assert!(
status_holder(&[status_catalog_entry(STATUS_HOLDER_MODULE, "status.lines",)]).is_none()
);
}
#[test]
fn dial_channel_queues_discovery_without_claiming_the_status_bar() {
let (client, mut wire_rx) = FleetStatusClient::dial_channel(1);
assert!(!client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
let request = wire_rx.try_recv().expect("discovery request");
assert_eq!(request.project_root(), "/tmp/project");
assert_eq!(request.harness(), "opencode");
assert_eq!(request.session(), "session-1");
request.complete_unavailable();
}
#[test]
fn closed_dial_channel_falls_back_to_the_solo_status_bar() {
let (client, wire_rx) = FleetStatusClient::channel(1);
drop(wire_rx);
assert!(!client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
assert!(!client.inner.route_live.load(Ordering::Acquire));
}
#[test]
fn dormant_client_falls_back_without_publishing() {
let client = FleetStatusClient::dormant();
assert!(!client.publish(
Path::new("/tmp/project"),
"opencode",
"session-1",
"E0 W0 | T0"
));
let state = client.inner.state.lock();
assert!(state.last_publish_at.is_empty());
assert_eq!(client.inner.next_revision.load(Ordering::Relaxed), 1);
}
#[test]
fn empty_local_status_publishes_alive_quiet() {
let (client, mut wire_rx) = FleetStatusClient::channel(4);
assert!(client.publish(Path::new("/tmp/project"), "opencode", "session-1", ""));
let publish = wire_rx.try_recv().expect("publish request");
assert_eq!(publish.body()["op"], "status.publish");
assert_eq!(publish.body()["text"], "");
assert_eq!(publish.body()["ttl_ms"], STATUS_PUBLISH_TTL_MS);
assert!(
wire_rx.try_recv().is_err(),
"publisher emitted a pull request"
);
}
#[test]
fn cadence_suppresses_duplicate_publishes_and_ack_updates_fence() {
let (client, mut wire_rx) = FleetStatusClient::channel(4);
let fixtures = fixtures();
let publish_fixture =
serde_json::to_vec(&fixtures["publish_aft"]).expect("publish fixture bytes");
assert!(client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
let publish = wire_rx.try_recv().expect("first publish request");
assert_eq!(publish.body()["revision"], 1);
assert!(publish.complete_response(&publish_fixture));
assert!(client.publish(Path::new("/tmp/project"), "opencode", "session-1", "local"));
assert!(
wire_rx.try_recv().is_err(),
"publish cadence issued another request"
);
assert_eq!(
client.publish_fence(),
PublishFence {
epoch: 3,
accepted_revision: 1
}
);
}
fn ack_with_read(revision: u64, last_read_at_ms: Option<u64>) -> Vec<u8> {
serde_json::to_vec(&json!({
"epoch": 1,
"accepted_revision": revision,
"last_read_at_ms": last_read_at_ms,
}))
.expect("ack bytes")
}
#[test]
fn read_freshness_is_bounded_by_the_window_and_tolerates_a_holder_clock_ahead() {
let ack_at = 1_000_000;
assert!(read_is_fresh(Some(ack_at - READER_FRESH_WINDOW_MS), ack_at));
assert!(!read_is_fresh(
Some(ack_at - READER_FRESH_WINDOW_MS - 1),
ack_at
));
assert!(read_is_fresh(Some(ack_at + 5_000), ack_at));
assert!(!read_is_fresh(None, ack_at));
}
#[test]
fn reader_presence_is_per_scope_and_follows_the_latest_ack() {
let (client, mut wire_rx) = FleetStatusClient::channel(4);
let read = Path::new("/tmp/read");
let unread = Path::new("/tmp/unread");
assert!(!client.reader_present(read), "no ack yet is no evidence");
assert!(client.publish(read, "opencode", "session", "text"));
assert!(wire_rx
.try_recv()
.unwrap()
.complete_response(&ack_with_read(1, Some(unix_now_ms() - 2_000))));
assert!(client.publish(unread, "opencode", "session", "text"));
assert!(wire_rx
.try_recv()
.unwrap()
.complete_response(&ack_with_read(2, None)));
assert!(client.reader_present(read));
assert!(!client.reader_present(unread));
client.inner.state.lock().last_publish_at.clear();
assert!(client.publish(read, "opencode", "session", "text"));
assert!(wire_rx
.try_recv()
.unwrap()
.complete_response(&ack_with_read(
3,
Some(unix_now_ms() - READER_FRESH_WINDOW_MS - 5_000)
)));
assert!(!client.reader_present(read));
}
#[test]
fn holder_without_read_field_or_dropped_route_is_no_reader() {
let (client, mut wire_rx) = FleetStatusClient::channel(4);
let root = Path::new("/tmp/project");
assert!(client.publish(root, "opencode", "session", "text"));
assert!(wire_rx
.try_recv()
.unwrap()
.complete_response(br#"{"epoch":1,"accepted_revision":1}"#));
assert!(
!client.reader_present(root),
"an older holder proves no reader"
);
client.inner.state.lock().last_publish_at.clear();
assert!(client.publish(root, "opencode", "session", "text"));
assert!(wire_rx
.try_recv()
.unwrap()
.complete_response(&ack_with_read(2, Some(unix_now_ms()))));
assert!(client.reader_present(root));
client.set_route_live(false);
assert!(
!client.reader_present(root),
"a dropped route has no reader"
);
client.set_route_live(true);
assert!(
!client.reader_present(root),
"evidence from the dropped route does not survive a rebind"
);
}
}