feat(node): recover gRPC connections and expose node state (STRA-59)
This commit is contained in:
@@ -32,3 +32,5 @@ jobs:
|
||||
run: dotnet build desktop/Strata.Desktop.csproj --no-restore
|
||||
- name: Desktop gRPC node integration (headless, no inference)
|
||||
run: dotnet desktop/bin/Debug/net10.0/Strata.Desktop.dll --self-check
|
||||
- name: Desktop gRPC restart recovery (isolated node)
|
||||
run: python desktop/tests/reconnect.py
|
||||
|
||||
+45
-2
@@ -72,8 +72,8 @@ Real loopback HTTP/2 tests include auth/version/limits, independent control duri
|
||||
streaming, new epoch snapshots, byte-identical tool-call SSE, incomplete terminal
|
||||
failure and quarantine, client disconnect, and HTTP→gRPC→HTTP adapter path.
|
||||
C# headless app self-check runs the actual Rust executable and generated client.
|
||||
No real model requests are sent by these tests. Agent automatic reconnect policy,
|
||||
durable lifecycle and remote install remain unqualified and unadvertised.
|
||||
No real model requests are sent by these tests. Durable lifecycle and remote install remain unqualified and unadvertised.
|
||||
The transport reconnect implementation is described below.
|
||||
|
||||
Verified on 2026-10-04, macOS Apple Silicon: all 33 Rust tests passed; strict
|
||||
Clippy and RustSec audit passed. .NET locked restore/build and C# self-check
|
||||
@@ -82,3 +82,46 @@ app exit left that node alive. Wrong credentials were rejected. Test node was
|
||||
removed afterward. NuGet reported no known vulnerable direct/transitive packages.
|
||||
Hosted CI, Windows/Linux native execution and real-model transport are not yet
|
||||
verified. Active user RTX5090 runtime was untouched.
|
||||
|
||||
## Recovery requirements (STRA-59)
|
||||
|
||||
Each node has an independent owned connection monitor. States: connecting,
|
||||
ready, disconnected, auth_error, protocol_error. `ready` means a fresh node
|
||||
connection, not proof of model readiness. New proxy admission requires a snapshot
|
||||
heard within 15 seconds and the advertised Responses capability. A 5-second
|
||||
heartbeat, with a 5-second RPC deadline, detects an idle broken connection.
|
||||
Reconnect uses capped 200ms→10s exponential backoff with jitter. Invalid auth or
|
||||
protocol/sequence state stops retries until configuration changes. State events
|
||||
replace snapshots; epoch changes reset the cursor, same-epoch regressions fail.
|
||||
Observer loss never releases backend slots or reissues an inference request.
|
||||
|
||||
The proxy exposes authenticated `/node/status` with connection state and numeric
|
||||
snapshot only. In-flight failures retain their explicit interruption behavior.
|
||||
The desktop displays connection status separately from hardware/model status,
|
||||
observes snapshot changes and reconnects independently of UI actions. Dropping
|
||||
its observation cancels that monitor, not the external agent. Restarting the
|
||||
owned inventory-only child is allowed; restarting external workers is not.
|
||||
|
||||
Acceptance: same-port agent crash/restart recovers with a fresh epoch, offline
|
||||
requests are rejected before inference dispatch, wrong credentials do not spin,
|
||||
one failed node does not block another, monitor drop ends its tasks/subscription,
|
||||
and existing streaming/tool integrity tests remain passing.
|
||||
|
||||
Recovery implementation verified 2026-10-04: Rust `Connection` and the desktop
|
||||
observer automatically reconnect with bounded backoff/jitter and heartbeat.
|
||||
The proxy's authenticated `/node/status` reports freshness, epoch, sequence,
|
||||
transport request count and capabilities, never request bodies. It refuses new
|
||||
work when the node state is stale/disconnected. Inference calls are never
|
||||
application-retried. Subscription snapshots replace state, not durable job logs.
|
||||
|
||||
36 Rust tests passed, including actual child process kill/restart on the same
|
||||
port, independent nodes, terminal auth errors, offline startup and releasing
|
||||
20 successive observer subscriptions. C# recovered from an actual isolated node
|
||||
restart; the repeatable CI fault test is `python desktop/tests/reconnect.py`.
|
||||
Python is only a test orchestrator and is not part of serving or deployment.
|
||||
|
||||
Remaining switch gates: managed model/process lifecycle, durable operation
|
||||
reconciliation, verifying backend readiness after node restart (node connectivity
|
||||
alone is insufficient), real-model harness test, platform qualification and
|
||||
managed SSH tunnel recreation. An existing tunnel can recover and the gRPC
|
||||
client reconnects, but this slice does not create/restart SSH processes.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
pub mod gateway;
|
||||
pub mod hardware;
|
||||
pub mod node;
|
||||
pub mod node_connection;
|
||||
pub mod node_proxy;
|
||||
pub mod planner;
|
||||
pub mod pool;
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Independently owned node observer. Reconnects state, never inference.
|
||||
use crate::node::{
|
||||
self,
|
||||
proto::{self, node_client::NodeClient},
|
||||
};
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::{sync::watch, task::JoinHandle};
|
||||
use tonic::{Code, Status, transport::Channel};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Phase {
|
||||
Connecting,
|
||||
Ready,
|
||||
Disconnected,
|
||||
AuthError,
|
||||
ProtocolError,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct State {
|
||||
phase: Phase,
|
||||
snapshot: Option<proto::Snapshot>,
|
||||
heard: Option<Instant>,
|
||||
client: Option<NodeClient<Channel>>,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct StatusView {
|
||||
pub phase: Phase,
|
||||
pub fresh: bool,
|
||||
pub agent_epoch: Option<String>,
|
||||
pub sequence: Option<u64>,
|
||||
pub active_responses: Option<u32>,
|
||||
pub capabilities: Vec<String>,
|
||||
}
|
||||
struct Owner {
|
||||
state: watch::Receiver<State>,
|
||||
task: JoinHandle<()>,
|
||||
freshness: Duration,
|
||||
}
|
||||
impl Drop for Owner {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort()
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Connection(Arc<Owner>);
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Timing {
|
||||
pub heartbeat: Duration,
|
||||
pub deadline: Duration,
|
||||
pub freshness: Duration,
|
||||
pub retry_min: Duration,
|
||||
pub retry_max: Duration,
|
||||
}
|
||||
impl Default for Timing {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
heartbeat: Duration::from_secs(5),
|
||||
deadline: Duration::from_secs(5),
|
||||
freshness: Duration::from_secs(15),
|
||||
retry_min: Duration::from_millis(200),
|
||||
retry_max: Duration::from_secs(10),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Connection {
|
||||
pub fn start(address: SocketAddr, token: String) -> Result<Self, String> {
|
||||
Self::with_timing(address, token, Timing::default())
|
||||
}
|
||||
pub fn with_timing(address: SocketAddr, token: String, timing: Timing) -> Result<Self, String> {
|
||||
if !address.ip().is_loopback()
|
||||
|| token.len() < 32
|
||||
|| token.len() > 4096
|
||||
|| !token.bytes().all(|b| b.is_ascii_graphic())
|
||||
{
|
||||
return Err("invalid node address or credential".into());
|
||||
}
|
||||
if timing.heartbeat.is_zero()
|
||||
|| timing.deadline.is_zero()
|
||||
|| timing.retry_min.is_zero()
|
||||
|| timing.retry_max < timing.retry_min
|
||||
|| timing.freshness < timing.heartbeat + timing.deadline
|
||||
{
|
||||
return Err("invalid observer timing".into());
|
||||
}
|
||||
let (tx, state) = watch::channel(State {
|
||||
phase: Phase::Connecting,
|
||||
snapshot: None,
|
||||
heard: None,
|
||||
client: None,
|
||||
});
|
||||
let task = tokio::spawn(observe(address, token, timing, tx));
|
||||
Ok(Self(Arc::new(Owner {
|
||||
state,
|
||||
task,
|
||||
freshness: timing.freshness,
|
||||
})))
|
||||
}
|
||||
pub fn status(&self) -> StatusView {
|
||||
let s = self.0.state.borrow();
|
||||
let snapshot = s.snapshot.as_ref();
|
||||
let fresh =
|
||||
s.phase == Phase::Ready && s.heard.is_some_and(|h| h.elapsed() < self.0.freshness);
|
||||
StatusView {
|
||||
phase: if s.phase == Phase::Ready && !fresh {
|
||||
Phase::Disconnected
|
||||
} else {
|
||||
s.phase
|
||||
},
|
||||
fresh,
|
||||
agent_epoch: snapshot.map(|s| s.agent_epoch.clone()),
|
||||
sequence: snapshot.map(|s| s.sequence),
|
||||
active_responses: snapshot.map(|s| s.active_responses),
|
||||
capabilities: snapshot.map(|s| s.capabilities.clone()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
pub fn client(&self, capability: &str) -> Result<NodeClient<Channel>, Status> {
|
||||
let s = self.0.state.borrow();
|
||||
if s.phase != Phase::Ready || !s.heard.is_some_and(|h| h.elapsed() < self.0.freshness) {
|
||||
return Err(Status::unavailable("node state is not fresh"));
|
||||
}
|
||||
if !s
|
||||
.snapshot
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.capabilities.iter().any(|c| c == capability))
|
||||
{
|
||||
return Err(Status::failed_precondition("node capability unavailable"));
|
||||
}
|
||||
s.client
|
||||
.clone()
|
||||
.ok_or_else(|| Status::unavailable("node disconnected"))
|
||||
}
|
||||
pub async fn wait_ready(&self, timeout: Duration) -> Result<(), Status> {
|
||||
let mut state = self.0.state.clone();
|
||||
tokio::time::timeout(timeout, async {
|
||||
loop {
|
||||
match state.borrow().phase {
|
||||
Phase::Ready => return Ok(()),
|
||||
Phase::AuthError => {
|
||||
return Err(Status::unauthenticated("node authentication failed"));
|
||||
}
|
||||
Phase::ProtocolError => {
|
||||
return Err(Status::failed_precondition("node protocol incompatible"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
state
|
||||
.changed()
|
||||
.await
|
||||
.map_err(|_| Status::unavailable("node observer stopped"))?;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| Status::deadline_exceeded("node connect timeout"))?
|
||||
}
|
||||
}
|
||||
fn terminal(code: Code) -> Option<Phase> {
|
||||
match code {
|
||||
Code::Unauthenticated | Code::PermissionDenied => Some(Phase::AuthError),
|
||||
Code::FailedPrecondition | Code::Unimplemented | Code::InvalidArgument => {
|
||||
Some(Phase::ProtocolError)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn validate(s: &proto::Snapshot, old: Option<&proto::Snapshot>) -> Result<(), Status> {
|
||||
if s.protocol_version != 1
|
||||
|| s.agent_epoch.is_empty()
|
||||
|| s.agent_epoch.len() > 128
|
||||
|| s.sequence == 0
|
||||
|| !s.full_snapshot
|
||||
|| s.capabilities.len() > 64
|
||||
|| s.capabilities.iter().any(|s| s.len() > 128)
|
||||
{
|
||||
return Err(Status::failed_precondition("invalid node snapshot"));
|
||||
}
|
||||
if old.is_some_and(|o| o.agent_epoch == s.agent_epoch && o.sequence > s.sequence) {
|
||||
return Err(Status::failed_precondition("node sequence regressed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn hello(
|
||||
client: &mut NodeClient<Channel>,
|
||||
token: &str,
|
||||
timing: Timing,
|
||||
) -> Result<proto::Snapshot, Status> {
|
||||
let mut r = node::authorized(
|
||||
proto::Hello {
|
||||
protocol_version: 1,
|
||||
},
|
||||
token,
|
||||
)?;
|
||||
r.set_timeout(timing.deadline);
|
||||
tokio::time::timeout(timing.deadline, client.handshake(r))
|
||||
.await
|
||||
.map_err(|_| Status::deadline_exceeded("node heartbeat deadline"))?
|
||||
.map(|s| s.into_inner())
|
||||
}
|
||||
async fn session(
|
||||
address: SocketAddr,
|
||||
token: &str,
|
||||
timing: Timing,
|
||||
tx: &watch::Sender<State>,
|
||||
) -> Result<(), Status> {
|
||||
let mut client = tokio::time::timeout(timing.deadline, node::connect(address))
|
||||
.await
|
||||
.map_err(|_| Status::unavailable("node connect timeout"))?
|
||||
.map_err(|_| Status::unavailable("node unavailable"))?;
|
||||
let first = hello(&mut client, token, timing).await?;
|
||||
let previous = tx.borrow().snapshot.clone();
|
||||
validate(&first, previous.as_ref())?;
|
||||
let cursor = proto::Cursor {
|
||||
agent_epoch: first.agent_epoch.clone(),
|
||||
sequence: first.sequence,
|
||||
};
|
||||
let r = node::authorized(cursor, token)?;
|
||||
let mut stream = tokio::time::timeout(timing.deadline, client.watch(r))
|
||||
.await
|
||||
.map_err(|_| Status::deadline_exceeded("node subscription timeout"))??
|
||||
.into_inner();
|
||||
// Do not open admission until the subscription itself supplies a full snapshot.
|
||||
let mut current = tokio::time::timeout(timing.deadline, stream.message())
|
||||
.await
|
||||
.map_err(|_| Status::deadline_exceeded("node snapshot timeout"))??
|
||||
.ok_or_else(|| Status::unavailable("node subscription closed"))?;
|
||||
validate(¤t, Some(&first))?;
|
||||
tx.send_replace(State {
|
||||
phase: Phase::Ready,
|
||||
snapshot: Some(current.clone()),
|
||||
heard: Some(Instant::now()),
|
||||
client: Some(client.clone()),
|
||||
});
|
||||
let mut heartbeat = tokio::time::interval(timing.heartbeat);
|
||||
heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
heartbeat.tick().await;
|
||||
loop {
|
||||
let (next, from_watch) = tokio::select! {
|
||||
event=stream.message()=> (event?.ok_or_else(||Status::unavailable("node subscription closed"))?,true),
|
||||
_=heartbeat.tick()=> (hello(&mut client,token,timing).await?,false),
|
||||
};
|
||||
// A handshake can overtake a buffered watch event. Ignore old buffered state;
|
||||
// the independent handshake must itself never go backwards in an epoch.
|
||||
if from_watch && next.agent_epoch == current.agent_epoch && next.sequence < current.sequence
|
||||
{
|
||||
continue;
|
||||
}
|
||||
validate(&next, Some(¤t))?;
|
||||
if next.agent_epoch != current.agent_epoch {
|
||||
return Err(Status::unavailable("node epoch changed; resubscribe"));
|
||||
}
|
||||
current = next;
|
||||
tx.send_replace(State {
|
||||
phase: Phase::Ready,
|
||||
snapshot: Some(current.clone()),
|
||||
heard: Some(Instant::now()),
|
||||
client: Some(client.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
async fn observe(address: SocketAddr, token: String, timing: Timing, tx: watch::Sender<State>) {
|
||||
let mut retry = timing.retry_min;
|
||||
loop {
|
||||
let started = Instant::now();
|
||||
let error = session(address, &token, timing, &tx)
|
||||
.await
|
||||
.expect_err("subscriptions end with status");
|
||||
let phase = terminal(error.code()).unwrap_or(Phase::Disconnected);
|
||||
tx.send_modify(|s| {
|
||||
s.phase = phase;
|
||||
s.client = None;
|
||||
s.heard = None;
|
||||
});
|
||||
if matches!(phase, Phase::AuthError | Phase::ProtocolError) {
|
||||
return;
|
||||
}
|
||||
if started.elapsed() >= timing.heartbeat {
|
||||
retry = timing.retry_min;
|
||||
}
|
||||
let jitter = Duration::from_millis((uuid::Uuid::new_v4().as_u128() % 101) as u64);
|
||||
tokio::time::sleep((retry + jitter).min(timing.retry_max)).await;
|
||||
retry = (retry * 2).min(timing.retry_max);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ use crate::node::{
|
||||
self,
|
||||
proto::{self, response_frame::Payload},
|
||||
};
|
||||
use crate::node_connection::Connection;
|
||||
use axum::{
|
||||
Router,
|
||||
body::{Body, Bytes},
|
||||
@@ -13,10 +14,9 @@ use axum::{
|
||||
};
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
use subtle::ConstantTimeEq;
|
||||
use tonic::transport::Channel;
|
||||
#[derive(Clone)]
|
||||
pub struct Proxy {
|
||||
client: proto::node_client::NodeClient<Channel>,
|
||||
connection: Connection,
|
||||
token: String,
|
||||
}
|
||||
impl Proxy {
|
||||
@@ -27,28 +27,15 @@ impl Proxy {
|
||||
if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) {
|
||||
return Err("invalid node credential".into());
|
||||
}
|
||||
let mut client = node::connect(address).await?;
|
||||
let mut request = node::authorized(
|
||||
proto::Hello {
|
||||
protocol_version: 1,
|
||||
},
|
||||
&token,
|
||||
)?;
|
||||
request.set_timeout(Duration::from_secs(5));
|
||||
let hello = client.handshake(request).await?.into_inner();
|
||||
if hello.protocol_version != 1
|
||||
|| !hello
|
||||
.capabilities
|
||||
.iter()
|
||||
.any(|c| c == "responses.gateway.v1")
|
||||
{
|
||||
return Err("node lacks Responses capability".into());
|
||||
}
|
||||
Ok(Self { client, token })
|
||||
let connection = Connection::start(address, token.clone())?;
|
||||
connection.wait_ready(Duration::from_secs(6)).await?;
|
||||
connection.client("responses.gateway.v1")?;
|
||||
Ok(Self { connection, token })
|
||||
}
|
||||
pub fn router(self) -> Router {
|
||||
Router::new()
|
||||
.route("/v1/models", get(models))
|
||||
.route("/node/status", get(connection_status))
|
||||
.route("/v1/responses", post(respond))
|
||||
.layer(DefaultBodyLimit::max(2 * 1024 * 1024))
|
||||
.with_state(self)
|
||||
@@ -67,21 +54,27 @@ fn failure(status: StatusCode, kind: &str) -> Response {
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
async fn models(State(mut p): State<Proxy>, h: HeaderMap) -> Response {
|
||||
async fn models(State(p): State<Proxy>, h: HeaderMap) -> Response {
|
||||
if !p.auth(&h) {
|
||||
return failure(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
let Ok(mut client) = p.connection.client("responses.gateway.v1") else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "node_not_ready");
|
||||
};
|
||||
let mut r = node::authorized(proto::Empty {}, &p.token).expect("validated credential");
|
||||
r.set_timeout(Duration::from_secs(5));
|
||||
match p.client.models(r).await {
|
||||
match client.models(r).await {
|
||||
Ok(v) => ([("content-type", "application/json")], v.into_inner().json).into_response(),
|
||||
Err(_) => failure(StatusCode::BAD_GATEWAY, "node_unavailable"),
|
||||
}
|
||||
}
|
||||
async fn respond(State(mut p): State<Proxy>, h: HeaderMap, body: Bytes) -> Response {
|
||||
async fn respond(State(p): State<Proxy>, h: HeaderMap, body: Bytes) -> Response {
|
||||
if !p.auth(&h) {
|
||||
return failure(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
let Ok(mut client) = p.connection.client("responses.gateway.v1") else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "node_not_ready");
|
||||
};
|
||||
let mut request = node::authorized(
|
||||
proto::ResponseRequest {
|
||||
json: body.to_vec(),
|
||||
@@ -90,7 +83,7 @@ async fn respond(State(mut p): State<Proxy>, h: HeaderMap, body: Bytes) -> Respo
|
||||
)
|
||||
.expect("validated credential");
|
||||
request.set_timeout(Duration::from_secs(86400));
|
||||
let mut stream = match p.client.respond(request).await {
|
||||
let mut stream = match client.respond(request).await {
|
||||
Ok(r) => r.into_inner(),
|
||||
Err(e) => {
|
||||
return failure(
|
||||
@@ -141,3 +134,10 @@ async fn respond(State(mut p): State<Proxy>, h: HeaderMap, body: Bytes) -> Respo
|
||||
>))
|
||||
.unwrap_or_else(|_| failure(StatusCode::BAD_GATEWAY, "invalid_node_headers"))
|
||||
}
|
||||
|
||||
async fn connection_status(State(p): State<Proxy>, h: HeaderMap) -> Response {
|
||||
if !p.auth(&h) {
|
||||
return failure(StatusCode::UNAUTHORIZED, "unauthorized");
|
||||
}
|
||||
axum::Json(p.connection.status()).into_response()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
use std::{net::SocketAddr, process::Stdio, time::Duration};
|
||||
use strata_desktop_core::node_connection::{Connection, Phase, Timing};
|
||||
use tokio::{
|
||||
io::{AsyncBufReadExt, BufReader},
|
||||
process::{Child, Command},
|
||||
};
|
||||
const TOKEN: &str = "test-only-reconnect-node-credential-123456";
|
||||
fn timing() -> Timing {
|
||||
Timing {
|
||||
heartbeat: Duration::from_millis(50),
|
||||
deadline: Duration::from_millis(300),
|
||||
freshness: Duration::from_millis(500),
|
||||
retry_min: Duration::from_millis(20),
|
||||
retry_max: Duration::from_millis(100),
|
||||
}
|
||||
}
|
||||
async fn launch(address: SocketAddr) -> (Child, SocketAddr) {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_strata-desktop"))
|
||||
.args([
|
||||
"node",
|
||||
"--listen",
|
||||
&address.to_string(),
|
||||
"--token-env",
|
||||
"STRATA_TEST_NODE_TOKEN",
|
||||
])
|
||||
.env("STRATA_TEST_NODE_TOKEN", TOKEN)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut line = String::new();
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
BufReader::new(child.stdout.take().unwrap()).read_line(&mut line),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&line).unwrap();
|
||||
(
|
||||
child,
|
||||
v["endpoint"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.strip_prefix("http://")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
async fn wait_phase(c: &Connection, p: Phase) {
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
while c.status().phase != p {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn killed_process_recovers_same_port_new_epoch_and_nodes_are_independent() {
|
||||
let (mut process, address) = launch("127.0.0.1:0".parse().unwrap()).await;
|
||||
let (mut other_process, other_address) = launch("127.0.0.1:0".parse().unwrap()).await;
|
||||
let c = Connection::with_timing(address, TOKEN.into(), timing()).unwrap();
|
||||
let other = Connection::with_timing(other_address, TOKEN.into(), timing()).unwrap();
|
||||
c.wait_ready(Duration::from_secs(2)).await.unwrap();
|
||||
other.wait_ready(Duration::from_secs(2)).await.unwrap();
|
||||
let epoch = c.status().agent_epoch.unwrap();
|
||||
process.kill().await.unwrap();
|
||||
process.wait().await.unwrap();
|
||||
wait_phase(&c, Phase::Disconnected).await;
|
||||
assert!(c.client("hardware.v1").is_err());
|
||||
assert!(other.client("hardware.v1").is_ok());
|
||||
let (mut replacement, _) = launch(address).await;
|
||||
c.wait_ready(Duration::from_secs(3)).await.unwrap();
|
||||
assert_ne!(c.status().agent_epoch.unwrap(), epoch);
|
||||
assert_eq!(c.status().active_responses, Some(0));
|
||||
assert!(c.client("hardware.v1").is_ok());
|
||||
drop(c);
|
||||
drop(other);
|
||||
replacement.kill().await.unwrap();
|
||||
replacement.wait().await.unwrap();
|
||||
other_process.kill().await.unwrap();
|
||||
other_process.wait().await.unwrap();
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn invalid_auth_stays_terminal_across_server_restart() {
|
||||
let (mut process, address) = launch("127.0.0.1:0".parse().unwrap()).await;
|
||||
let c = Connection::with_timing(
|
||||
address,
|
||||
"incorrect-test-credential-32bytes-long".into(),
|
||||
timing(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
c.wait_ready(Duration::from_secs(2))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
tonic::Code::Unauthenticated
|
||||
);
|
||||
process.kill().await.unwrap();
|
||||
process.wait().await.unwrap();
|
||||
let (mut replacement, _) = launch(address).await;
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(c.status().phase, Phase::AuthError);
|
||||
assert!(!c.status().fresh);
|
||||
drop(c);
|
||||
replacement.kill().await.unwrap();
|
||||
replacement.wait().await.unwrap();
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn startup_offline_recovers_and_drop_releases_subscription() {
|
||||
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = l.local_addr().unwrap();
|
||||
drop(l);
|
||||
let c = Connection::with_timing(address, TOKEN.into(), timing()).unwrap();
|
||||
wait_phase(&c, Phase::Disconnected).await;
|
||||
let (mut process, _) = launch(address).await;
|
||||
c.wait_ready(Duration::from_secs(3)).await.unwrap();
|
||||
drop(c);
|
||||
// More than the server's 16 observer limit; dropping each owner must release it.
|
||||
for _ in 0..20 {
|
||||
let c = Connection::with_timing(address, TOKEN.into(), timing()).unwrap();
|
||||
c.wait_ready(Duration::from_secs(2)).await.unwrap();
|
||||
drop(c);
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
process.kill().await.unwrap();
|
||||
process.wait().await.unwrap();
|
||||
}
|
||||
@@ -76,6 +76,77 @@ internal static class CoreClient
|
||||
finally { Gate.Release(); }
|
||||
}
|
||||
|
||||
internal sealed record ConnectionState(string Phase, string? Epoch = null, ulong Sequence = 0, uint ActiveResponses = 0);
|
||||
|
||||
public static async Task Observe(Action<ConnectionState> publish, CancellationToken token)
|
||||
{
|
||||
var delay = 200;
|
||||
Snapshot? last = null;
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
publish(new("connecting"));
|
||||
using var startup = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
startup.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
var c = await Connect(startup.Token);
|
||||
var hello = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(),
|
||||
deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token);
|
||||
ValidateSnapshot(hello, last);
|
||||
using var call = c.Watch(new Cursor { AgentEpoch = hello.AgentEpoch, Sequence = hello.Sequence }, Headers(), cancellationToken: token);
|
||||
var pending = call.ResponseStream.MoveNext(token);
|
||||
var initial = true;
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
Snapshot next;
|
||||
using var tick = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
var timer = Task.Delay(TimeSpan.FromSeconds(5), tick.Token);
|
||||
if (await Task.WhenAny(pending, timer) == pending)
|
||||
{
|
||||
tick.Cancel();
|
||||
if (!await pending) throw new RpcException(new Status(StatusCode.Unavailable, "Node subscription ended"));
|
||||
next = call.ResponseStream.Current;
|
||||
// Heartbeat may have overtaken an already buffered state event.
|
||||
if (last != null && next.AgentEpoch == last.AgentEpoch && next.Sequence < last.Sequence)
|
||||
{ pending = call.ResponseStream.MoveNext(token); continue; }
|
||||
pending = call.ResponseStream.MoveNext(token);
|
||||
}
|
||||
else
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (initial) throw new RpcException(new Status(StatusCode.DeadlineExceeded, "Node snapshot timeout"));
|
||||
next = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(),
|
||||
deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token);
|
||||
}
|
||||
ValidateSnapshot(next, last);
|
||||
if (!initial && last != null && next.AgentEpoch != last.AgentEpoch)
|
||||
throw new RpcException(new Status(StatusCode.Unavailable, "Node epoch changed"));
|
||||
last = next; initial = false; delay = 200;
|
||||
publish(new("ready", next.AgentEpoch, next.Sequence, next.ActiveResponses));
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { break; }
|
||||
catch (RpcException) when (token.IsCancellationRequested) { break; }
|
||||
catch (RpcException e) when (e.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied)
|
||||
{ publish(new("auth_error")); return; }
|
||||
catch (RpcException e) when (e.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented or StatusCode.InvalidArgument)
|
||||
{ publish(new("protocol_error")); return; }
|
||||
catch (InvalidOperationException) { publish(new("configuration_error")); return; }
|
||||
catch (Exception e) when (e is RpcException or IOException or OperationCanceledException)
|
||||
{ publish(new("disconnected")); }
|
||||
try { await Task.Delay(Math.Min(10000, delay + Random.Shared.Next(0, 101)), token); }
|
||||
catch (OperationCanceledException) { break; }
|
||||
delay = Math.Min(10000, delay * 2);
|
||||
}
|
||||
}
|
||||
private static void ValidateSnapshot(Snapshot next, Snapshot? previous)
|
||||
{
|
||||
if (next.ProtocolVersion != 1 || !next.FullSnapshot || next.AgentEpoch.Length is 0 or > 128
|
||||
|| next.Sequence == 0 || next.Capabilities.Count > 64 || next.Capabilities.Any(c => c.Length > 128)
|
||||
|| (previous != null && previous.AgentEpoch == next.AgentEpoch && previous.Sequence > next.Sequence))
|
||||
throw new RpcException(new Status(StatusCode.FailedPrecondition, "Invalid node snapshot"));
|
||||
}
|
||||
|
||||
public static async Task<JsonObject> Run(CancellationToken cancellationToken, params string[] args)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
@@ -127,6 +198,24 @@ internal static class CoreClient
|
||||
finally { process.Dispose(); }
|
||||
}
|
||||
}
|
||||
public static async Task ReconnectSelfCheck()
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT") == null)
|
||||
throw new InvalidOperationException("Reconnect check requires an isolated external test node.");
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25));
|
||||
string? firstEpoch = null; bool disconnected = false; bool recovered = false;
|
||||
await Observe(state => {
|
||||
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(state));
|
||||
if (state.Phase == "ready") {
|
||||
firstEpoch ??= state.Epoch;
|
||||
if (disconnected && state.Epoch != firstEpoch) {recovered = true; timeout.Cancel();}
|
||||
}
|
||||
if (state.Phase == "disconnected") disconnected = true;
|
||||
}, timeout.Token);
|
||||
if (!recovered) throw new InvalidOperationException("No observed recovery to a new epoch.");
|
||||
Console.WriteLine("PASS: C# observer recovered after isolated node restart; no inference replay.");
|
||||
}
|
||||
|
||||
public static async Task SelfCheck()
|
||||
{
|
||||
var h = await Run(CancellationToken.None, "hardware");
|
||||
|
||||
+16
-1
@@ -14,6 +14,7 @@ public sealed class MainWindow : Window
|
||||
private readonly StackPanel hardwareCards = new() { Spacing = 12 };
|
||||
private readonly StackPanel planCards = new() { Spacing = 12 };
|
||||
private readonly TextBlock status = Text("Підключення до gRPC-вузла…", 13, Muted);
|
||||
private readonly TextBlock connectionStatus = Text("Вузол: підключення…", 13, Muted);
|
||||
private readonly TextBlock details = Text("", 13, Muted);
|
||||
private readonly Button refresh = Action("Оновити обладнання");
|
||||
private readonly Button import = Action("Відкрити профіль…");
|
||||
@@ -44,6 +45,7 @@ public sealed class MainWindow : Window
|
||||
toolbar.Children.Add(refresh); toolbar.Children.Add(import); toolbar.Children.Add(example);
|
||||
page.Children.Add(toolbar);
|
||||
page.Children.Add(status);
|
||||
page.Children.Add(connectionStatus);
|
||||
var columns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,24,*") };
|
||||
var left = new StackPanel { Spacing = 14 };
|
||||
left.Children.Add(Text("ОБЛАДНАННЯ", 11, Accent, FontWeight.SemiBold));
|
||||
@@ -60,7 +62,20 @@ public sealed class MainWindow : Window
|
||||
refresh.Click += async (_, _) => await Busy(RefreshHardware);
|
||||
import.Click += async (_, _) => await PickProfile();
|
||||
example.Click += async (_, _) => await Busy(() => LoadPlan(Path.Combine(AppContext.BaseDirectory, "example-requirements.json")));
|
||||
Opened += async (_, _) => await Busy(RefreshHardware);
|
||||
Opened += async (_, _) => {
|
||||
await Busy(RefreshHardware);
|
||||
_ = Task.Run(() => CoreClient.Observe(state => Avalonia.Threading.Dispatcher.UIThread.Post(() => {
|
||||
connectionStatus.Text = state.Phase switch {
|
||||
"ready" => $"Вузол підключений · активних запитів: {state.ActiveResponses}",
|
||||
"auth_error" => "Вузол: перевірте credential підключення",
|
||||
"protocol_error" => "Вузол: несумісний протокол",
|
||||
"configuration_error" => "Вузол: перевірте налаштування підключення",
|
||||
"connecting" => "Вузол: підключення…",
|
||||
_ => "Зв’язок із вузлом втрачено · відновлення…"
|
||||
};
|
||||
connectionStatus.Foreground = state.Phase == "ready" ? Accent : Muted;
|
||||
}), lifetime.Token));
|
||||
};
|
||||
Closed += (_, _) => lifetime.Cancel();
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,11 @@ internal static class Program
|
||||
{
|
||||
try
|
||||
{
|
||||
if (args is ["--self-check-reconnect"])
|
||||
{
|
||||
try { CoreClient.ReconnectSelfCheck().GetAwaiter().GetResult(); return 0; }
|
||||
catch (Exception e) { Console.Error.WriteLine(e.Message); return 1; }
|
||||
}
|
||||
if (args is ["--self-check"])
|
||||
{
|
||||
try { CoreClient.SelfCheck().GetAwaiter().GetResult(); return 0; }
|
||||
|
||||
@@ -89,3 +89,10 @@ On macOS the C#→gRPC→Rust self-check passed. Rust integration tests also cov
|
||||
harness HTTP→gRPC→worker streaming with synthetic responses, auth, versioning,
|
||||
observer limits, reconnect snapshots and interrupted-stream quarantine.
|
||||
This is transport evidence, not Metal inference or Windows/Linux qualification.
|
||||
|
||||
Connection recovery: the window displays node connection separately from the
|
||||
hardware query result. The observer reconnects after transport failure, replaces
|
||||
state on agent epoch changes and stops automatic retries for auth/protocol errors.
|
||||
Run `python desktop/tests/reconnect.py` after building to test C# recovery against
|
||||
an isolated node restart. This test creates and cleans its own local processes;
|
||||
it never sends model requests or contacts the user's remote endpoint.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Offline CI fault test: C# observer + isolated Rust node; no inference or SSH."""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
|
||||
async def main():
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
binary = root / "desktop-core/target/debug" / ("strata-desktop.exe" if os.name == "nt" else "strata-desktop")
|
||||
dll = root / "desktop/bin/Debug/net10.0/Strata.Desktop.dll"
|
||||
env = os.environ.copy()
|
||||
env.pop("STRATA_NODE_ENDPOINT", None)
|
||||
env["STRATA_NODE_TOKEN"] = secrets.token_hex(32)
|
||||
nodes = []
|
||||
app = None
|
||||
|
||||
async def launch(address):
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
str(binary), "node", "--listen", address, "--token-env", "STRATA_NODE_TOKEN",
|
||||
env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
nodes.append(process)
|
||||
descriptor = json.loads(await asyncio.wait_for(process.stdout.readline(), 5))
|
||||
return process, descriptor["endpoint"]
|
||||
|
||||
try:
|
||||
node, endpoint = await launch("127.0.0.1:0")
|
||||
env["STRATA_NODE_ENDPOINT"] = endpoint
|
||||
app = await asyncio.create_subprocess_exec(
|
||||
"dotnet", str(dll), "--self-check-reconnect", env=env,
|
||||
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
killed = restarted = False
|
||||
while True:
|
||||
line = await asyncio.wait_for(app.stdout.readline(), 28)
|
||||
if not line:
|
||||
break
|
||||
message = line.decode().strip()
|
||||
print(message, flush=True)
|
||||
if message.startswith("{"):
|
||||
phase = json.loads(message)["Phase"]
|
||||
if phase == "ready" and not killed:
|
||||
node.kill()
|
||||
await node.wait()
|
||||
killed = True
|
||||
elif phase == "disconnected" and killed and not restarted:
|
||||
await launch(endpoint.removeprefix("http://"))
|
||||
restarted = True
|
||||
code = await asyncio.wait_for(app.wait(), 5)
|
||||
if code != 0 or not restarted:
|
||||
raise RuntimeError("C# reconnect check failed")
|
||||
finally:
|
||||
for process in nodes + ([app] if app else []):
|
||||
if process.returncode is None:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user