diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 39d2f6b01e..be18eb90d8 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -273,6 +273,30 @@ impl OpenShell for TestOpenShell { Err(Status::unimplemented("not used by this test server")) } + async fn peer_publish_sandbox_events( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + + async fn peer_get_sandbox_logs( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + + type PeerWatchSandboxStream = + tokio_stream::wrappers::ReceiverStream>; + + async fn peer_watch_sandbox( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn peer_notify_config_update( &self, _request: tonic::Request, diff --git a/crates/openshell-server/src/auth/method_authz.rs b/crates/openshell-server/src/auth/method_authz.rs index fcdc1e25df..3c5056e7f7 100644 --- a/crates/openshell-server/src/auth/method_authz.rs +++ b/crates/openshell-server/src/auth/method_authz.rs @@ -186,6 +186,9 @@ mod tests { "/openshell.v1.OpenShell/PeerReportEndpointStatus", "/openshell.v1.OpenShell/PeerGetSandboxProviderStatus", "/openshell.v1.OpenShell/PeerNotifyConfigUpdate", + "/openshell.v1.OpenShell/PeerPublishSandboxEvents", + "/openshell.v1.OpenShell/PeerGetSandboxLogs", + "/openshell.v1.OpenShell/PeerWatchSandbox", ] { assert!(!is_user_callable(path)); assert!(is_peer_callable(path)); diff --git a/crates/openshell-server/src/auth/peer.rs b/crates/openshell-server/src/auth/peer.rs index 7ee198e775..2d95cf97a5 100644 --- a/crates/openshell-server/src/auth/peer.rs +++ b/crates/openshell-server/src/auth/peer.rs @@ -847,6 +847,9 @@ mod tests { "/openshell.v1.OpenShell/PeerReportEndpointStatus", "/openshell.v1.OpenShell/PeerGetSandboxProviderStatus", "/openshell.v1.OpenShell/PeerNotifyConfigUpdate", + "/openshell.v1.OpenShell/PeerPublishSandboxEvents", + "/openshell.v1.OpenShell/PeerGetSandboxLogs", + "/openshell.v1.OpenShell/PeerWatchSandbox", ] { assert!(matches!( auth.authenticate(&headers, path).await.unwrap(), @@ -860,7 +863,7 @@ mod tests { .principal() .is_none() ); - assert_eq!(resolver.seen_tokens.lock().unwrap().len(), 5); + assert_eq!(resolver.seen_tokens.lock().unwrap().len(), 8); } fn identity() -> ResolvedGatewayPeerIdentity { diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 8b2adb5570..18752eacea 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -6986,6 +6986,9 @@ impl ComputeRuntime { ) .await .map_err(|e| format!("delete sandbox settings: {e}"))?; + crate::log_routing::delete_home(&self.store, sandbox.object_id()) + .await + .map_err(|e| format!("delete sandbox log home: {e}"))?; for (object_type, label) in [ (POLICY_OBJECT_TYPE, "policy revisions"), diff --git a/crates/openshell-server/src/gateway_metrics.rs b/crates/openshell-server/src/gateway_metrics.rs index c8005a0392..ec1ab07d42 100644 --- a/crates/openshell-server/src/gateway_metrics.rs +++ b/crates/openshell-server/src/gateway_metrics.rs @@ -43,6 +43,8 @@ pub const MUTATION_LOCK_TIMEOUTS_TOTAL: &str = "openshell_server_mutation_lock_t pub const MUTATION_LOCK_ERRORS_TOTAL: &str = "openshell_server_mutation_lock_errors_total"; pub const PROVISIONING_DEADLINE_SKIPS_TOTAL: &str = "openshell_server_provisioning_deadline_skips_total"; +pub const SANDBOX_LOG_EVENTS_DROPPED_TOTAL: &str = + "openshell_server_sandbox_log_events_dropped_total"; // Histograms (explicit buckets, see BUCKETED_HISTOGRAMS) pub const RELAY_CLAIM_DURATION_SECONDS: &str = "openshell_server_relay_claim_duration_seconds"; pub const PEER_REQUEST_DURATION_SECONDS: &str = "openshell_server_peer_request_duration_seconds"; @@ -133,6 +135,24 @@ impl RelayRejection { } } +/// Why a sandbox log line or platform event bound for its log home was dropped. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LogEventDrop { + QueueFull, + ForwardFailed, +} + +impl LogEventDrop { + pub const ALL: [Self; 2] = [Self::QueueFull, Self::ForwardFailed]; + + pub const fn label(self) -> &'static str { + match self { + Self::QueueFull => "queue_full", + Self::ForwardFailed => "forward_failed", + } + } +} + /// Routed operation. For a peer request, the owning replica records the matching gRPC method in /// `openshell_server_grpc_requests_total`, for example `PeerRelay` for `relay`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -346,6 +366,11 @@ pub fn describe_and_initialize(relay: RelayCapacity, mutation_lock_connections: Unit::Count, "Times the provisioning deadline scan skipped a sandbox because its local mutation locks were busy." ); + describe_counter!( + SANDBOX_LOG_EVENTS_DROPPED_TOTAL, + Unit::Count, + "Sandbox log lines and platform events this replica dropped instead of buffering them on the sandbox's log home replica." + ); describe_histogram!( RELAY_CLAIM_DURATION_SECONDS, Unit::Seconds, @@ -400,6 +425,9 @@ pub fn describe_and_initialize(relay: RelayCapacity, mutation_lock_connections: counter!(RELAY_REJECTED_TOTAL, LABEL_REASON => reason.label()).increment(0); } counter!(RELAY_EXPIRED_TOTAL).increment(0); + for reason in LogEventDrop::ALL { + counter!(SANDBOX_LOG_EVENTS_DROPPED_TOTAL, LABEL_REASON => reason.label()).increment(0); + } for scope in LockScope::ALL { counter!(MUTATION_LOCK_TIMEOUTS_TOTAL, LABEL_SCOPE => scope.label()).increment(0); counter!(MUTATION_LOCK_ERRORS_TOTAL, LABEL_SCOPE => scope.label()).increment(0); @@ -495,6 +523,13 @@ pub fn record_relay_expired(count: usize) { } } +pub fn record_log_events_dropped(reason: LogEventDrop, count: usize) { + if count > 0 { + counter!(SANDBOX_LOG_EVENTS_DROPPED_TOTAL, LABEL_REASON => reason.label()) + .increment(count as u64); + } +} + pub fn record_relay_claimed(waited: Duration) { histogram!(RELAY_CLAIM_DURATION_SECONDS).record(waited); } diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 5bfb592196..1d4dd1712d 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -57,10 +57,11 @@ use openshell_core::proto::{ ListSandboxesRequest, ListSandboxesResponse, ListServicesRequest, ListServicesResponse, ListWorkspaceMembersRequest, ListWorkspaceMembersResponse, ListWorkspacesRequest, ListWorkspacesResponse, MemoryResourceCapabilities, NegotiatedExtensionInfo, - PeerNotifyConfigUpdateRequest, PeerNotifyConfigUpdateResponse, PeerRelayFrame, - ProviderProfileResponse, ProviderResponse, PushSandboxLogsRequest, PushSandboxLogsResponse, - RefreshSandboxTokenRequest, RefreshSandboxTokenResponse, RejectDraftChunkRequest, - RejectDraftChunkResponse, RelayFrame, RemoveWorkspaceMemberRequest, + PeerGetSandboxLogsRequest, PeerNotifyConfigUpdateRequest, PeerNotifyConfigUpdateResponse, + PeerPublishSandboxEventsRequest, PeerPublishSandboxEventsResponse, PeerRelayFrame, + PeerWatchSandboxRequest, ProviderProfileResponse, ProviderResponse, PushSandboxLogsRequest, + PushSandboxLogsResponse, RefreshSandboxTokenRequest, RefreshSandboxTokenResponse, + RejectDraftChunkRequest, RejectDraftChunkResponse, RelayFrame, RemoveWorkspaceMemberRequest, RemoveWorkspaceMemberResponse, ReportEndpointStatusRequest, ReportEndpointStatusResponse, ReportMainProcessExitRequest, ReportMainProcessExitResponse, ReportPolicyStatusRequest, ReportPolicyStatusResponse, ReportProviderReadinessRequest, ReportProviderReadinessResponse, @@ -1387,6 +1388,29 @@ impl OpenShell for OpenShellService { ) -> Result, Status> { crate::config_delivery::handle_peer_notify_config_update(&self.state, request) } + + async fn peer_publish_sandbox_events( + &self, + request: Request, + ) -> Result, Status> { + policy::handle_peer_publish_sandbox_events(&self.state, request) + } + + async fn peer_get_sandbox_logs( + &self, + request: Request, + ) -> Result, Status> { + policy::handle_peer_get_sandbox_logs(&self.state, request) + } + + type PeerWatchSandboxStream = sandbox::WatchSandboxStream; + + async fn peer_watch_sandbox( + &self, + request: Request, + ) -> Result, Status> { + sandbox::handle_peer_watch_sandbox(&self.state, request) + } } fn public_extension_info(extension: &NegotiatedExtension) -> NegotiatedExtensionInfo { diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b9d5fa8fff..68a6a5d9c2 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -80,6 +80,9 @@ use openshell_core::proto::{ L7DenyRule, L7Rule, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, Provider, Sandbox, SandboxPolicy as ProtoSandboxPolicy, StaticCredentialEndpointBinding, }; +use openshell_core::proto::{ + PeerGetSandboxLogsRequest, PeerPublishSandboxEventsRequest, PeerPublishSandboxEventsResponse, +}; use openshell_core::telemetry::{ LifecycleOperation, LifecycleResource, PolicyDecisionOperation, TelemetryOutcome, }; @@ -5499,6 +5502,56 @@ pub(super) async fn handle_get_sandbox_logs( .await?; let sandbox_id = sandbox.object_id(); + if let Some(endpoint) = crate::supervisor_session::log_home_peer(state, sandbox_id).await { + let request = PeerGetSandboxLogsRequest { + sandbox_id: sandbox_id.to_string(), + request: Some(req.clone()), + }; + match crate::supervisor_session::forward_sandbox_logs_to_peer(state, &endpoint, request) + .await + { + Ok(response) => return Ok(Response::new(response)), + Err(status) => { + debug!(endpoint, error = %status, "log home unreachable; serving local sandbox logs"); + } + } + } + sandbox_logs_here(state, sandbox_id, req).map(Response::new) +} + +pub(super) fn handle_peer_get_sandbox_logs( + state: &Arc, + request: Request, +) -> Result, Status> { + super::provider_readiness::ensure_peer_request(&request)?; + let PeerGetSandboxLogsRequest { + sandbox_id, + request, + } = request.into_inner(); + let req = request.ok_or_else(|| Status::invalid_argument("request is required"))?; + sandbox_logs_here(state, &sandbox_id, req).map(Response::new) +} + +pub(super) fn handle_peer_publish_sandbox_events( + state: &Arc, + request: Request, +) -> Result, Status> { + super::provider_readiness::ensure_peer_request(&request)?; + for routed in request.into_inner().events { + if let Some(event) = routed.event { + state + .tracing_log_bus + .publish_here(&routed.sandbox_id, event); + } + } + Ok(Response::new(PeerPublishSandboxEventsResponse {})) +} + +fn sandbox_logs_here( + state: &ServerState, + sandbox_id: &str, + req: GetSandboxLogsRequest, +) -> Result { let lines = if req.lines == 0 { 2000 } else { req.lines }; let tail = state.tracing_log_bus.tail(sandbox_id, lines as usize); @@ -5537,7 +5590,7 @@ pub(super) async fn handle_get_sandbox_logs( }) .collect(); - Ok(Response::new(GetSandboxLogsResponse { logs, buffer_total })) + Ok(GetSandboxLogsResponse { logs, buffer_total }) } /// How often an open push stream re-reads its sandbox record to detect that diff --git a/crates/openshell-server/src/grpc/provider_readiness.rs b/crates/openshell-server/src/grpc/provider_readiness.rs index 8a690c6c74..227fa04060 100644 --- a/crates/openshell-server/src/grpc/provider_readiness.rs +++ b/crates/openshell-server/src/grpc/provider_readiness.rs @@ -694,7 +694,7 @@ async fn handle_report_provider_readiness_inner( })) } -fn ensure_peer_request(request: &Request) -> Result<(), Status> { +pub(super) fn ensure_peer_request(request: &Request) -> Result<(), Status> { if matches!( request .extensions() diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..b3fb3cd675 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -37,12 +37,13 @@ use openshell_core::proto::{ ExecSandboxEvent, ExecSandboxExit, ExecSandboxInput, ExecSandboxRequest, ExecSandboxStderr, ExecSandboxStdout, GetSandboxRequest, GetSandboxTemplateRequest, ListSandboxProvidersRequest, ListSandboxProvidersResponse, ListSandboxTemplatesRequest, ListSandboxTemplatesResponse, - ListSandboxesRequest, ListSandboxesResponse, Provider, ProviderMutationKind, - ResourceRequirements, ResumeSandboxRequest, RevokeSshSessionRequest, RevokeSshSessionResponse, - SandboxResources, SandboxResponse, SandboxSpec, SandboxStreamEvent, SandboxTemplateResponse, - SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, SshRelayTarget, - StartSandboxRequest, StopSandboxRequest, SuspendSandboxRequest, TcpForwardFrame, - TcpForwardInit, TcpRelayTarget, WatchSandboxRequest, relay_open, tcp_forward_init, + ListSandboxesRequest, ListSandboxesResponse, PeerWatchSandboxRequest, Provider, + ProviderMutationKind, ResourceRequirements, ResumeSandboxRequest, RevokeSshSessionRequest, + RevokeSshSessionResponse, SandboxResources, SandboxResponse, SandboxSpec, SandboxStreamEvent, + SandboxTemplateResponse, SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, + SshRelayTarget, StartSandboxRequest, StopSandboxRequest, SuspendSandboxRequest, + TcpForwardFrame, TcpForwardInit, TcpRelayTarget, WatchSandboxRequest, relay_open, + tcp_forward_init, }; use openshell_core::proto::{ BeginRootfsTarStagingRequest, BeginRootfsTarStagingResponse, Sandbox, SandboxPhase, @@ -2213,6 +2214,51 @@ pub(super) async fn handle_watch_sandbox( .await?; let sandbox_id = sandbox.object_id().to_string(); + if (req.follow_logs || req.follow_events) + && let Some(endpoint) = crate::supervisor_session::log_home_peer(state, &sandbox_id).await + { + let request = PeerWatchSandboxRequest { + sandbox_id: sandbox_id.clone(), + request: Some(req.clone()), + }; + match crate::supervisor_session::open_peer_watch(state, &endpoint, request).await { + Ok(mut upstream) => { + let (tx, rx) = mpsc::channel(256); + let producer = tokio::spawn(async move { + while let Some(item) = futures::StreamExt::next(&mut upstream).await { + if tx.send(item).await.is_err() { + return; + } + } + }); + return Ok(Response::new(WatchSandboxStream::new(rx, producer))); + } + Err(status) => { + debug!(endpoint, error = %status, "log home unreachable; watching locally"); + } + } + } + watch_sandbox_here(state, sandbox_id, req) +} + +pub(super) fn handle_peer_watch_sandbox( + state: &Arc, + request: Request, +) -> Result, Status> { + super::provider_readiness::ensure_peer_request(&request)?; + let PeerWatchSandboxRequest { + sandbox_id, + request, + } = request.into_inner(); + let req = request.ok_or_else(|| Status::invalid_argument("request is required"))?; + watch_sandbox_here(state, sandbox_id, req) +} + +fn watch_sandbox_here( + state: &Arc, + sandbox_id: String, + req: WatchSandboxRequest, +) -> Result, Status> { let follow_status = req.follow_status; let follow_logs = req.follow_logs; let follow_events = req.follow_events; diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 8edc7adc6b..1873f38c59 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -31,6 +31,7 @@ mod gateway_ocsf; mod gateway_ring; mod grpc; mod http; +mod log_routing; mod middleware; mod multiplex; mod network_trust; @@ -1353,6 +1354,7 @@ pub(crate) async fn run_server( state.tracing_log_bus.clone(), shutdown_rx.clone(), ); + log_routing::spawn(state.clone(), shutdown_rx.clone()); } let membership_worker = gateway_members::spawn_membership_worker( state.clone(), diff --git a/crates/openshell-server/src/log_routing.rs b/crates/openshell-server/src/log_routing.rs new file mode 100644 index 0000000000..a44f0bd21f --- /dev/null +++ b/crates/openshell-server/src/log_routing.rs @@ -0,0 +1,425 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Keeps each sandbox's log lines and platform events on one gateway replica, +//! its log home (see [`crate::supervisor_session::log_home_peer`]), so every +//! replica serves the same history. +//! +//! Every replica sends what it publishes to the home and proxies log reads and +//! log or event watches there. History does not follow a move: once another +//! replica records taking the session, the old home drops its buffers, which +//! ends the watches it serves. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use openshell_core::proto::{ + PeerPublishSandboxEventsRequest, PeerSandboxEvent, SandboxStreamEvent, +}; +use prost::Message; +use tokio::sync::mpsc::{self, error::TrySendError}; +use tokio::sync::watch; +use tracing::{debug, info, warn}; + +use crate::ServerState; +use crate::gateway_metrics::{LogEventDrop, record_log_events_dropped}; +use crate::persistence::{PersistenceResult, Store, WriteCondition}; +use crate::supervisor_session::{forward_sandbox_events_to_peer, log_home_peer}; + +const HOME_OBJECT_TYPE: &str = "sandbox_log_home"; +const HOME_ID_PREFIX: &str = "sandbox-log-home:"; +/// Events waiting for the router; more are dropped. +const ROUTER_QUEUE: usize = 16 * 1024; +/// Events waiting to be sent to one peer, or for one sandbox's home to +/// resolve; more are dropped. +const PEER_QUEUE: usize = 8 * 1024; +/// Most events per forwarded batch. +const MAX_BATCH: usize = 512; +/// Encoded size budget per forwarded batch, well below the 1 MiB a peer +/// decodes. +const MAX_BATCH_BYTES: usize = 256 * 1024; +/// How long the router reuses resolved homes. +const HOME_CACHE_TTL: Duration = Duration::from_secs(2); +/// How long a peer's sender lingers without events. +const PEER_IDLE: Duration = Duration::from_mins(1); +/// How often a replica drops the buffers of sandboxes whose home moved away. +const MOVE_CHECK_INTERVAL: Duration = crate::bus_sweeper::SWEEP_INTERVAL; +/// Buffers active more recently than this are not checked. It outlasts +/// [`HOME_CACHE_TTL`], so events routed here before a move have stopped. +const MOVE_MIN_IDLE: Duration = Duration::from_secs(10); + +fn home_object_id(sandbox_id: &str) -> String { + format!("{HOME_ID_PREFIX}{sandbox_id}") +} + +/// The replica that last held `sandbox_id`'s supervisor session. +pub async fn last_home(state: &ServerState, sandbox_id: &str) -> Option { + let record = state + .store + .get(HOME_OBJECT_TYPE, &home_object_id(sandbox_id)) + .await + .ok()??; + String::from_utf8(record.payload).ok() +} + +/// Record this replica as the last to hold `sandbox_id`'s supervisor session. +pub fn record_home(state: &Arc, sandbox_id: &str) { + if state.store.is_single_replica() { + return; + } + let state = state.clone(); + let sandbox_id = sandbox_id.to_string(); + tokio::spawn(async move { + let id = home_object_id(&sandbox_id); + let condition = match state.store.get(HOME_OBJECT_TYPE, &id).await { + Ok(Some(record)) if record.payload == state.replica_id.as_bytes() => return, + Ok(Some(record)) => WriteCondition::MatchResourceVersion(record.resource_version), + Ok(None) => WriteCondition::MustCreate, + Err(error) => { + warn!(sandbox_id, error = %error, "failed to read the sandbox log home"); + return; + } + }; + // Another replica may have taken the session since; it records itself. + if !state.supervisor_sessions.has_session(&sandbox_id) { + return; + } + let written = state + .store + .put_if( + HOME_OBJECT_TYPE, + &id, + &sandbox_id, + "", + state.replica_id.as_bytes(), + None, + condition, + ) + .await; + // A conflict means another replica recorded itself in between. + if let Err(error) = written + && !error.is_expected() + { + warn!(sandbox_id, error = %error, "failed to record the sandbox log home"); + } + }); +} + +pub async fn delete_home(store: &Store, sandbox_id: &str) -> PersistenceResult { + store + .delete(HOME_OBJECT_TYPE, &home_object_id(sandbox_id)) + .await +} + +/// Route every sandbox event this replica publishes to its log home. Only +/// multi-replica deployments need it. +pub fn spawn(state: Arc, shutdown_rx: watch::Receiver) { + let (events_tx, events_rx) = mpsc::channel(ROUTER_QUEUE); + state.tracing_log_bus.route_to(events_tx); + tokio::spawn(route_events(state.clone(), events_rx)); + tokio::spawn(drop_moved_buffers(state, shutdown_rx)); +} + +enum Home { + /// Events published while the home is being resolved, in publish order. + Resolving(Vec), + Known { + peer: Option, + at: Instant, + }, +} + +/// Keeps each sandbox's events in publish order. Homes resolve in background +/// tasks, so a slow store read holds back only that sandbox. Nothing here may +/// log with a `sandbox_id` field, which would route the line back to itself. +struct Router { + state: Arc, + homes: HashMap, + peers: HashMap>, + resolved: mpsc::UnboundedSender<(String, Option)>, +} + +async fn route_events( + state: Arc, + mut events: mpsc::Receiver<(String, SandboxStreamEvent)>, +) { + let (resolved, mut resolved_rx) = mpsc::unbounded_channel(); + let mut router = Router { + state, + homes: HashMap::new(), + peers: HashMap::new(), + resolved, + }; + let mut expire = tokio::time::interval(HOME_CACHE_TTL); + loop { + tokio::select! { + event = events.recv() => { + let Some((sandbox_id, event)) = event else { + return; + }; + router.route(sandbox_id, event); + } + Some((sandbox_id, peer)) = resolved_rx.recv() => router.resolved(&sandbox_id, peer), + _ = expire.tick() => router.homes.retain(|_, home| { + !matches!(home, Home::Known { at, .. } if at.elapsed() >= HOME_CACHE_TTL) + }), + } + } +} + +impl Router { + fn route(&mut self, sandbox_id: String, event: SandboxStreamEvent) { + match self.homes.get_mut(&sandbox_id) { + Some(Home::Resolving(pending)) => { + if pending.len() < PEER_QUEUE { + pending.push(event); + } else { + record_log_events_dropped(LogEventDrop::QueueFull, 1); + } + } + Some(Home::Known { peer, at }) if at.elapsed() < HOME_CACHE_TTL => { + let peer = peer.clone(); + self.deliver(sandbox_id, peer, event); + } + _ if self.state.supervisor_sessions.has_session(&sandbox_id) => { + self.state.tracing_log_bus.publish_here(&sandbox_id, event); + } + _ => { + self.homes + .insert(sandbox_id.clone(), Home::Resolving(vec![event])); + let state = self.state.clone(); + let resolved = self.resolved.clone(); + tokio::spawn(async move { + let peer = log_home_peer(&state, &sandbox_id).await; + let _ = resolved.send((sandbox_id, peer)); + }); + } + } + } + + fn resolved(&mut self, sandbox_id: &str, peer: Option) { + let known = Home::Known { + peer: peer.clone(), + at: Instant::now(), + }; + let Some(Home::Resolving(pending)) = self.homes.insert(sandbox_id.to_string(), known) + else { + return; + }; + for event in pending { + self.deliver(sandbox_id.to_string(), peer.clone(), event); + } + } + + fn deliver(&mut self, sandbox_id: String, peer: Option, event: SandboxStreamEvent) { + let Some(endpoint) = + peer.filter(|_| !self.state.supervisor_sessions.has_session(&sandbox_id)) + else { + self.state.tracing_log_bus.publish_here(&sandbox_id, event); + return; + }; + let event = PeerSandboxEvent { + sandbox_id, + event: Some(event), + }; + let sender = self + .peers + .entry(endpoint.clone()) + .or_insert_with(|| spawn_peer_sender(&self.state, endpoint.clone())); + let event = match sender.try_send(event) { + Err(TrySendError::Closed(event)) => { + *sender = spawn_peer_sender(&self.state, endpoint); + sender.try_send(event) + } + sent => sent, + }; + if event.is_err() { + record_log_events_dropped(LogEventDrop::QueueFull, 1); + } + } +} + +/// Batch events to `endpoint` in order. Exits once idle; the router replaces +/// it on the next event. +fn spawn_peer_sender(state: &Arc, endpoint: String) -> mpsc::Sender { + let (events_tx, mut events_rx) = mpsc::channel(PEER_QUEUE); + let state = state.clone(); + tokio::spawn(async move { + let mut received = Vec::with_capacity(MAX_BATCH); + while let Ok(count) = + tokio::time::timeout(PEER_IDLE, events_rx.recv_many(&mut received, MAX_BATCH)).await + { + if count == 0 { + return; + } + for events in byte_batches(std::mem::take(&mut received)) { + let count = events.len(); + let request = PeerPublishSandboxEventsRequest { events }; + if let Err(status) = + forward_sandbox_events_to_peer(&state, &endpoint, request).await + { + record_log_events_dropped(LogEventDrop::ForwardFailed, count); + debug!(endpoint, error = %status, "dropped sandbox events for an unreachable log home"); + } + } + } + }); + events_tx +} + +/// Split `events` into batches of at most [`MAX_BATCH_BYTES`] encoded. An +/// event larger than that goes alone. +fn byte_batches(events: Vec) -> Vec> { + let mut batches = Vec::new(); + let mut batch = Vec::new(); + let mut bytes = 0; + for event in events { + let len = event.encoded_len(); + let size = 1 + prost::length_delimiter_len(len) + len; + if !batch.is_empty() && bytes + size > MAX_BATCH_BYTES { + batches.push(std::mem::take(&mut batch)); + bytes = 0; + } + bytes += size; + batch.push(event); + } + if !batch.is_empty() { + batches.push(batch); + } + batches +} + +/// Drop the buffers of sandboxes whose log home moved to another replica, +/// ending the watches served from them. +async fn drop_moved_buffers(state: Arc, mut shutdown_rx: watch::Receiver) { + let mut timer = tokio::time::interval(MOVE_CHECK_INTERVAL); + timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { + changed = shutdown_rx.changed() => { + if changed.is_err() || *shutdown_rx.borrow() { + return; + } + } + _ = timer.tick() => match drop_moved_once(&state, MOVE_MIN_IDLE).await { + Ok(0) => {} + Ok(dropped) => info!(dropped, "dropped log buffers of sandboxes whose log home moved"), + Err(error) => warn!(error = %error, "failed to check sandbox log homes"), + }, + } + } +} + +/// Drop idle buffers whose sandbox another live replica recorded as its log +/// home, and return how many were dropped. One batched read covers them all. +async fn drop_moved_once(state: &ServerState, min_idle: Duration) -> PersistenceResult { + let ids: Vec = state + .tracing_log_bus + .idle_sandbox_ids(min_idle) + .iter() + .filter(|id| !state.supervisor_sessions.has_session(id)) + .map(|id| home_object_id(id)) + .collect(); + if ids.is_empty() { + return Ok(0); + } + let records = state.store.get_many(HOME_OBJECT_TYPE, &ids).await?; + let Ok(peers) = state.gateway_peers.read() else { + return Ok(0); + }; + let mut dropped = 0; + for record in records { + let moved = record.payload != state.replica_id.as_bytes() + && std::str::from_utf8(&record.payload).is_ok_and(|home| peers.contains_key(home)); + if let Some(sandbox_id) = record.id.strip_prefix(HOME_ID_PREFIX) + && moved + { + state.tracing_log_bus.remove(sandbox_id); + dropped += 1; + } + } + Ok(dropped) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn event(bytes: usize) -> PeerSandboxEvent { + PeerSandboxEvent { + sandbox_id: "x".repeat(bytes), + event: None, + } + } + + #[test] + fn forwarded_batches_stay_within_the_byte_budget() { + let events = vec![ + event(100 * 1024), + event(100 * 1024), + event(100 * 1024), + event(10), + ]; + + let batches = byte_batches(events); + + assert_eq!(batches.iter().map(Vec::len).collect::>(), [2, 2]); + for batch in &batches { + let request = PeerPublishSandboxEventsRequest { + events: batch.clone(), + }; + assert!(request.encoded_len() <= MAX_BATCH_BYTES); + } + } + + #[tokio::test] + async fn only_buffers_whose_home_moved_to_a_live_replica_are_dropped() { + let state = crate::grpc::test_support::test_server_state().await; + state + .gateway_peers + .write() + .unwrap() + .insert("replica-b".to_string(), "http://replica-b".to_string()); + for (sandbox_id, home) in [ + ("sb-moved", "replica-b"), + ("sb-dead-home", "replica-gone"), + ("sb-here", state.replica_id.as_str()), + ] { + state + .store + .put( + HOME_OBJECT_TYPE, + &home_object_id(sandbox_id), + sandbox_id, + "", + home.as_bytes(), + None, + ) + .await + .unwrap(); + } + for sandbox_id in ["sb-moved", "sb-dead-home", "sb-here", "sb-no-record"] { + state + .tracing_log_bus + .publish_external(openshell_core::proto::SandboxLogLine { + sandbox_id: sandbox_id.to_string(), + message: "line".to_string(), + ..Default::default() + }); + } + + assert_eq!(drop_moved_once(&state, Duration::ZERO).await.unwrap(), 1); + assert!(state.tracing_log_bus.tail("sb-moved", 10).is_empty()); + for kept in ["sb-dead-home", "sb-here", "sb-no-record"] { + assert_eq!(state.tracing_log_bus.tail(kept, 10).len(), 1, "{kept}"); + } + } + + #[test] + fn an_oversized_event_goes_alone() { + let batches = byte_batches(vec![event(10), event(MAX_BATCH_BYTES), event(10)]); + + assert_eq!(batches.iter().map(Vec::len).collect::>(), [1, 1, 1]); + } +} diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 6b8a4d1406..a2be601c68 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -75,6 +75,7 @@ const POLLED_PATHS: &[&str] = &[ "/openshell.v1.OpenShell/GetSandboxConfig", "/openshell.v1.OpenShell/ReportProviderReadiness", "/openshell.v1.OpenShell/PeerReportProviderReadiness", + "/openshell.v1.OpenShell/PeerPublishSandboxEvents", ]; /// Build a tracing span for an inbound request, recording the `request_id` diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index cb8ee48173..6fb0dc2d7d 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -971,6 +971,28 @@ impl Store { store_dispatch_traced!(self.existing_ids(object_type, ids)) } + /// Fetch the objects among `ids` that exist for an object type, using + /// bounded primary-key lookups. + #[tracing::instrument( + name = "store", + level = "debug", + skip_all, + fields( + otel.name = "store.get_many", + otel.status_code = tracing::field::Empty, + object_type = %object_type, + object_count = ids.len(), + batch_count = ids.len().div_ceil(EXISTING_IDS_BATCH_SIZE), + ) + )] + pub async fn get_many( + &self, + object_type: &str, + ids: &[String], + ) -> PersistenceResult> { + store_dispatch_traced!(self.get_many(object_type, ids)) + } + /// Count objects of a given type within a workspace. #[tracing::instrument( name = "store", diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index d212d85ba9..8bfafeea48 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -1505,6 +1505,33 @@ WHERE object_type = $1 AND workspace = $2 AND name = $3 Ok(existing) } + pub async fn get_many( + &self, + object_type: &str, + ids: &[String], + ) -> PersistenceResult> { + let mut records = Vec::with_capacity(ids.len()); + for ids in ids.chunks(EXISTING_IDS_BATCH_SIZE) { + let mut query = QueryBuilder::::new( + "SELECT object_type, id, name, workspace, payload, created_at_ms, updated_at_ms, labels, resource_version FROM objects WHERE object_type = ", + ); + query.push_bind(object_type).push(" AND id IN ("); + let mut separated = query.separated(", "); + for id in ids { + separated.push_bind(id); + } + separated.push_unseparated(")"); + + let rows = query + .build() + .fetch_all(&self.pool) + .await + .map_err(|e| map_db_error(&e))?; + records.extend(rows.into_iter().map(row_to_object_record)); + } + Ok(records) + } + pub async fn count_in_workspace( &self, object_type: &str, diff --git a/crates/openshell-server/src/persistence/sqlite.rs b/crates/openshell-server/src/persistence/sqlite.rs index b98b65ce3d..1458aaad55 100644 --- a/crates/openshell-server/src/persistence/sqlite.rs +++ b/crates/openshell-server/src/persistence/sqlite.rs @@ -1022,6 +1022,33 @@ WHERE "object_type" = ?1 AND "id" = ?2 Ok(existing) } + pub async fn get_many( + &self, + object_type: &str, + ids: &[String], + ) -> PersistenceResult> { + let mut records = Vec::with_capacity(ids.len()); + for ids in ids.chunks(EXISTING_IDS_BATCH_SIZE) { + let mut query = QueryBuilder::::new( + r#"SELECT "object_type", "id", "name", "workspace", "payload", "created_at_ms", "updated_at_ms", "labels", "resource_version" FROM "objects" WHERE "object_type" = "#, + ); + query.push_bind(object_type).push(r#" AND "id" IN ("#); + let mut separated = query.separated(", "); + for id in ids { + separated.push_bind(id); + } + separated.push_unseparated(")"); + + let rows = query + .build() + .fetch_all(&self.pool) + .await + .map_err(|e| map_db_error(&e))?; + records.extend(rows.into_iter().map(row_to_object_record)); + } + Ok(records) + } + pub async fn count_in_workspace( &self, object_type: &str, diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..c5aa16eb54 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -252,7 +252,7 @@ mod tests { // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "bb1cc5e3d793871d5f5a507b6f4174ebf2a5938e3917e1b4d57438c9ca8476b4"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = @@ -306,6 +306,11 @@ mod tests { const PEER_CONFIG_RPC_SIGNATURES: [&str; 1] = [ "openshell.v1.OpenShell/PeerNotifyConfigUpdate|.openshell.v1.PeerNotifyConfigUpdateRequest|.openshell.v1.PeerNotifyConfigUpdateResponse|false|false", ]; + const PEER_LOG_RPC_SIGNATURES: [&str; 3] = [ + "openshell.v1.OpenShell/PeerGetSandboxLogs|.openshell.v1.PeerGetSandboxLogsRequest|.openshell.v1.GetSandboxLogsResponse|false|false", + "openshell.v1.OpenShell/PeerPublishSandboxEvents|.openshell.v1.PeerPublishSandboxEventsRequest|.openshell.v1.PeerPublishSandboxEventsResponse|false|false", + "openshell.v1.OpenShell/PeerWatchSandbox|.openshell.v1.PeerWatchSandboxRequest|.openshell.v1.SandboxStreamEvent|false|true", + ]; // Synthetic SandboxSpec bytes with log level, provider, and command fields, // emitted before the gateway-owned attachment epoch field was introduced. const PRE_READINESS_SANDBOX_SPEC: &str = @@ -744,11 +749,18 @@ mod tests { "peer config RPC is missing or changed: {signature}" ); } + for signature in PEER_LOG_RPC_SIGNATURES { + assert!( + methods.iter().any(|method| method == signature), + "peer log RPC is missing or changed: {signature}" + ); + } assert_eq!( compiled_method_count, 124 + PROVIDER_READINESS_RPC_SIGNATURES.len() + PEER_OWNER_RPC_SIGNATURES.len() + PEER_CONFIG_RPC_SIGNATURES.len() + + PEER_LOG_RPC_SIGNATURES.len() + isolation_methods.len() + sandbox_protocol_methods.len() + supervisor_host_methods.len(), @@ -758,7 +770,8 @@ mod tests { methods.len(), 91 + PROVIDER_READINESS_RPC_SIGNATURES.len() + PEER_OWNER_RPC_SIGNATURES.len() - + PEER_CONFIG_RPC_SIGNATURES.len(), + + PEER_CONFIG_RPC_SIGNATURES.len() + + PEER_LOG_RPC_SIGNATURES.len(), "inventory every public gateway RPC" ); assert_eq!( @@ -769,6 +782,7 @@ mod tests { 88 + PROVIDER_READINESS_RPC_SIGNATURES.len() + PEER_OWNER_RPC_SIGNATURES.len() + PEER_CONFIG_RPC_SIGNATURES.len() + + PEER_LOG_RPC_SIGNATURES.len() ); assert!(methods.iter().all(|method| !method.contains(".storage."))); assert!( @@ -817,7 +831,7 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), + (374, 32), (104, 23), (88, 23), PUBLIC_RPC_SCHEMA_SHA256, diff --git a/crates/openshell-server/src/supervisor_pool.rs b/crates/openshell-server/src/supervisor_pool.rs index c5e8d10812..67f8d04bad 100644 --- a/crates/openshell-server/src/supervisor_pool.rs +++ b/crates/openshell-server/src/supervisor_pool.rs @@ -2172,6 +2172,12 @@ impl SupervisorPool { // never removes a row a new term wrote meanwhile. let report_rows = self.report_rows().await?; let mut owners = self.owners().await?; + self.spread.observe_owners(owners.values().map(|record| { + ( + record.payload.sandbox_id.as_str(), + record.payload.member_id.as_str(), + ) + })); // Listed after the owners: an instance is published before its owner // is recorded, so every owner listed has its instance listed unless // it was withdrawn. diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index f9f46b153b..e15e8631f9 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -19,13 +19,15 @@ use uuid::Uuid; use openshell_core::jwt::CredentialEpoch; use openshell_core::proto::{ - GatewayMessage, GetSandboxProviderStatusRequest, GetSandboxProviderStatusResponse, - PeerNotifyConfigUpdateRequest, PeerNotifyConfigUpdateResponse, PeerRelayFrame, PeerRelayInit, - ProviderReadinessObservation, RelayFrame, RelayInit, RelayOpen, ReportEndpointStatusRequest, - ReportEndpointStatusResponse, ReportMainProcessExitRequest, ReportMainProcessExitResponse, - ReportProviderReadinessRequest, ReportProviderReadinessResponse, Sandbox, SandboxPhase, - SessionAccepted, SessionRedirect, SshRelayTarget, SupervisorHello, SupervisorMessage, - gateway_message, open_shell_client, peer_relay_frame, relay_open, supervisor_message, + GatewayMessage, GetSandboxLogsResponse, GetSandboxProviderStatusRequest, + GetSandboxProviderStatusResponse, PeerGetSandboxLogsRequest, PeerNotifyConfigUpdateRequest, + PeerNotifyConfigUpdateResponse, PeerPublishSandboxEventsRequest, PeerRelayFrame, PeerRelayInit, + PeerWatchSandboxRequest, ProviderReadinessObservation, RelayFrame, RelayInit, RelayOpen, + ReportEndpointStatusRequest, ReportEndpointStatusResponse, ReportMainProcessExitRequest, + ReportMainProcessExitResponse, ReportProviderReadinessRequest, ReportProviderReadinessResponse, + Sandbox, SandboxPhase, SandboxStreamEvent, SessionAccepted, SessionRedirect, SshRelayTarget, + SupervisorHello, SupervisorMessage, gateway_message, open_shell_client, peer_relay_frame, + relay_open, supervisor_message, }; use openshell_core::transport_errors::is_expected_transport_close_status; @@ -1525,6 +1527,53 @@ pub(crate) async fn forward_config_notify_to_peer( .inspect_err(|_| state.peer_routes.evict_channel(endpoint)) } +pub(crate) async fn forward_sandbox_events_to_peer( + state: &Arc, + endpoint: &str, + request: PeerPublishSandboxEventsRequest, +) -> Result<(), Status> { + let mut client = peer_rpc_client(state, endpoint).await?; + client + .peer_publish_sandbox_events(request) + .await + .map(drop) + .inspect_err(|status| { + // The peer answered, so its channel is healthy. + if !matches!( + status.code(), + tonic::Code::ResourceExhausted | tonic::Code::OutOfRange + ) { + state.peer_routes.evict_channel(endpoint); + } + }) +} + +pub(crate) async fn forward_sandbox_logs_to_peer( + state: &Arc, + endpoint: &str, + request: PeerGetSandboxLogsRequest, +) -> Result { + let mut client = peer_rpc_client(state, endpoint).await?; + client + .peer_get_sandbox_logs(request) + .await + .map(Response::into_inner) + .inspect_err(|_| state.peer_routes.evict_channel(endpoint)) +} + +pub(crate) async fn open_peer_watch( + state: &Arc, + endpoint: &str, + request: PeerWatchSandboxRequest, +) -> Result, Status> { + let mut client = peer_rpc_client(state, endpoint).await?; + client + .peer_watch_sandbox(request) + .await + .map(Response::into_inner) + .inspect_err(|_| state.peer_routes.evict_channel(endpoint)) +} + pub(crate) async fn remote_supervisor_owner( state: &Arc, sandbox_id: &str, @@ -1825,6 +1874,51 @@ fn owner_is_fresh(owner: &crate::supervisor_owner::OwnerRecord) -> bool { owner.is_fresh(OWNER_TTL) } +/// Peer endpoint of the replica that keeps `sandbox_id`'s logs and platform +/// events, or `None` when this replica keeps them. +/// +/// That replica is the sandbox's parent: the one holding its supervisor +/// session, else the last live one to hold it, else the one expected to get +/// it. It changes only when another replica takes the session. +pub(crate) async fn log_home_peer(state: &Arc, sandbox_id: &str) -> Option { + if state.store.is_single_replica() || state.supervisor_sessions.has_session(sandbox_id) { + return None; + } + let owner_index = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL); + match resolve_owner(state, &owner_index, sandbox_id).await { + Ok(Some(owner)) if owner_is_fresh(&owner) => { + return (owner.owner_replica_id != state.replica_id) + .then(|| owner.peer_endpoint().map(str::to_string)) + .flatten(); + } + Ok(_) => {} + Err(_) => return None, + } + let live_replica = |replica: &str| -> Option> { + if replica == state.replica_id { + return Some(None); + } + let endpoint = state.gateway_peers.read().ok()?.get(replica).cloned()?; + Some(Some(endpoint)) + }; + if let Some(home) = crate::log_routing::last_home(state, sandbox_id) + .await + .as_deref() + .and_then(live_replica) + { + return home; + } + if let Some(home) = state + .supervisor_spread + .sandbox_replica(sandbox_id) + .as_deref() + .and_then(live_replica) + { + return home; + } + preferred_peer_redirect(state, sandbox_id).map(|redirect| redirect.peer_endpoint) +} + /// Whether this sandbox's supervisor is connected to any replica. /// /// A peer replica counts only through a fresh owner record. An owner record @@ -2360,6 +2454,7 @@ async fn accept_supervisor_session(setup: SessionSetup) -> Result<(), Status> { )); } } + crate::log_routing::record_home(&state, &sandbox_id); if let Some(bootstrap) = bootstrap_in_flight { state.supervisor_sessions.begin_config_bootstrap( &sandbox_id, diff --git a/crates/openshell-server/src/supervisor_spread.rs b/crates/openshell-server/src/supervisor_spread.rs index 264435a42b..0149e2c6a1 100644 --- a/crates/openshell-server/src/supervisor_spread.rs +++ b/crates/openshell-server/src/supervisor_spread.rs @@ -36,6 +36,8 @@ struct Inner { homes: HashMap, /// Replica each member was placed on here, and when. placed: HashMap, + /// Replica serving the member that owns each pooled sandbox. + sandboxes: HashMap, } impl SupervisorSpread { @@ -45,7 +47,7 @@ impl SupervisorSpread { .inner .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - let Inner { homes, placed } = &mut *inner; + let Inner { homes, placed, .. } = &mut *inner; *homes = members .iter() .filter(|member| !member.leaving) @@ -56,6 +58,33 @@ impl SupervisorSpread { }); } + /// Take the pool's owners as `(sandbox_id, member_id)` pairs, after + /// [`Self::observe`] took the members. + pub fn observe_owners<'a>(&self, owners: impl IntoIterator) { + let mut inner = self + .inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Inner { + homes, sandboxes, .. + } = &mut *inner; + *sandboxes = owners + .into_iter() + .filter_map(|(sandbox, member)| Some((sandbox.to_string(), homes.get(member)?.clone()))) + .collect(); + } + + /// The replica serving the shared supervisor of `sandbox_id`, by the + /// pool's records. + pub fn sandbox_replica(&self, sandbox_id: &str) -> Option { + self.inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .sandboxes + .get(sandbox_id) + .cloned() + } + /// The replica on `ring` that `member_id` should move to from `here`, or /// `None` when `here` keeps it. The member counts on its replica from now /// on either way. A host that does not accept a redirect stays `here`. @@ -138,6 +167,20 @@ mod tests { counts } + #[test] + fn a_pooled_sandbox_maps_to_its_owners_replica() { + let spread = SupervisorSpread::default(); + spread.observe(&[member("sup-1", "gw-a"), member("sup-2", "gw-b")]); + spread.observe_owners([("sb-1", "sup-1"), ("sb-2", "sup-2"), ("sb-3", "sup-gone")]); + assert_eq!(spread.sandbox_replica("sb-1").as_deref(), Some("gw-a")); + assert_eq!(spread.sandbox_replica("sb-2").as_deref(), Some("gw-b")); + assert_eq!(spread.sandbox_replica("sb-3"), None); + + spread.observe_owners([("sb-2", "sup-1")]); + assert_eq!(spread.sandbox_replica("sb-1"), None); + assert_eq!(spread.sandbox_replica("sb-2").as_deref(), Some("gw-a")); + } + #[test] fn simultaneous_arrivals_split_before_the_records_show_them() { let spread = SupervisorSpread::default(); diff --git a/crates/openshell-server/src/tracing_bus.rs b/crates/openshell-server/src/tracing_bus.rs index 23ddfee5fe..b0923dd667 100644 --- a/crates/openshell-server/src/tracing_bus.rs +++ b/crates/openshell-server/src/tracing_bus.rs @@ -4,12 +4,12 @@ //! Capture openshell-server tracing logs for streaming over gRPC. use std::collections::{HashMap, VecDeque}; -use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; use std::time::{Duration, Instant}; use openshell_core::proto::{SandboxLogLine, SandboxStreamEvent}; use openshell_ocsf::OCSF_TARGET; -use tokio::sync::broadcast; +use tokio::sync::{broadcast, mpsc}; use tracing::{Event, Subscriber}; use tracing_subscriber::Layer; use tracing_subscriber::layer::Context; @@ -23,6 +23,33 @@ pub struct TracingLogBus { inner: Arc>, pub(crate) platform_event_bus: PlatformEventBus, seq: SeqAllocator, + router: Router, +} + +/// Queue that takes every published event once [`TracingLogBus::route_to`] +/// runs, so the router can buffer it on the sandbox's log home. +pub type RoutedEvents = mpsc::Sender<(String, SandboxStreamEvent)>; + +/// Shared by both buses, so either routes once one is installed. +type Router = Arc>; + +/// `event` back when no router is installed and this bus buffers it itself. +fn route( + router: &Router, + sandbox_id: &str, + event: SandboxStreamEvent, +) -> Option { + let Some(router) = router.get() else { + return Some(event); + }; + // Tracing callers cannot wait, so a full queue drops the event. + if router.try_send((sandbox_id.to_string(), event)).is_err() { + crate::gateway_metrics::record_log_events_dropped( + crate::gateway_metrics::LogEventDrop::QueueFull, + 1, + ); + } + None } #[derive(Debug, Clone)] @@ -291,12 +318,34 @@ impl TracingLogBus { // One allocator, shared with the platform event bus so both draw from // a single per-sandbox cursor space. let seq = SeqAllocator::default(); + let router = Router::default(); Self { inner: Arc::new(Mutex::new(Inner { per_id: HashMap::new(), })), - platform_event_bus: PlatformEventBus::new(seq.clone()), + platform_event_bus: PlatformEventBus::new(seq.clone(), router.clone()), seq, + router, + } + } + + /// Send every event published from now on, on either bus, to `router` + /// instead of buffering it. The router hands back the ones this replica + /// keeps through [`Self::publish_here`]. Only the first call takes effect. + pub fn route_to(&self, router: RoutedEvents) { + let _ = self.router.set(router); + } + + /// Buffer an event on this replica, on the bus its payload belongs to, + /// bypassing the router. + pub fn publish_here(&self, sandbox_id: &str, event: SandboxStreamEvent) { + if matches!( + event.payload, + Some(openshell_core::proto::sandbox_stream_event::Payload::Log(_)) + ) { + self.publish_locally(sandbox_id, event, Self::DEFAULT_TAIL); + } else { + self.platform_event_bus.publish_locally(sandbox_id, event); } } @@ -496,7 +545,13 @@ impl TracingLogBus { /// Default tail buffer capacity (lines per sandbox). const DEFAULT_TAIL: usize = 2000; - fn publish(&self, sandbox_id: &str, mut event: SandboxStreamEvent, tail_cap: usize) { + fn publish(&self, sandbox_id: &str, event: SandboxStreamEvent, tail_cap: usize) { + if let Some(event) = route(&self.router, sandbox_id, event) { + self.publish_locally(sandbox_id, event, tail_cap); + } + } + + fn publish_locally(&self, sandbox_id: &str, mut event: SandboxStreamEvent, tail_cap: usize) { // Hold the cursor space across the tail insert so a teardown cannot // reset the counter between allocation and insertion. Lock order is // allocator -> bus map, matching `remove` and `close`. @@ -1099,6 +1154,32 @@ mod tests { bus.remove("nonexistent"); } + #[test] + fn an_installed_router_takes_every_publish_until_published_here() { + let bus = TracingLogBus::new(); + let (router_tx, mut router_rx) = mpsc::channel(8); + bus.route_to(router_tx); + let sandbox_id = "sb-routed"; + bus.publish_external(make_log_event(sandbox_id, "line")); + bus.platform_event_bus.publish( + sandbox_id, + SandboxStreamEvent { + payload: Some(openshell_core::proto::sandbox_stream_event::Payload::Event( + openshell_core::proto::PlatformEvent::default(), + )), + cursor: String::new(), + }, + ); + assert!(bus.tail(sandbox_id, 10).is_empty()); + assert!(bus.platform_event_bus.tail(sandbox_id, 10).is_empty()); + + while let Ok((id, event)) = router_rx.try_recv() { + bus.publish_here(&id, event); + } + assert_eq!(bus.tail(sandbox_id, 10).len(), 1); + assert_eq!(bus.platform_event_bus.tail(sandbox_id, 10).len(), 1); + } + #[test] fn publish_after_close_drops_without_recreating_buffers() { // The issue's leak: late publishers used to re-create the buffers a @@ -1323,7 +1404,7 @@ mod tests { #[test] fn platform_event_bus_remove_cleans_up() { - let bus = PlatformEventBus::new(SeqAllocator::default()); + let bus = PlatformEventBus::new(SeqAllocator::default(), Router::default()); let sandbox_id = "sb-4"; let mut rx = bus.subscribe(sandbox_id); @@ -1348,7 +1429,7 @@ mod tests { #[test] fn platform_event_bus_subscribe_after_remove_creates_fresh_channel() { - let bus = PlatformEventBus::new(SeqAllocator::default()); + let bus = PlatformEventBus::new(SeqAllocator::default(), Router::default()); let sandbox_id = "sb-5"; let _old_rx = bus.subscribe(sandbox_id); @@ -1366,7 +1447,7 @@ mod tests { #[test] fn platform_event_bus_remove_nonexistent_is_noop() { - let bus = PlatformEventBus::new(SeqAllocator::default()); + let bus = PlatformEventBus::new(SeqAllocator::default(), Router::default()); // Should not panic bus.remove("nonexistent"); } @@ -1375,7 +1456,7 @@ mod tests { fn platform_event_bus_tail_returns_buffered_events() { use openshell_core::proto::{PlatformEvent, sandbox_stream_event}; - let bus = PlatformEventBus::new(SeqAllocator::default()); + let bus = PlatformEventBus::new(SeqAllocator::default(), Router::default()); let sandbox_id = "sb-6"; // Publish some events @@ -1420,14 +1501,14 @@ mod tests { #[test] fn platform_event_bus_tail_empty_sandbox() { - let bus = PlatformEventBus::new(SeqAllocator::default()); + let bus = PlatformEventBus::new(SeqAllocator::default(), Router::default()); let events = bus.tail("nonexistent", 10); assert!(events.is_empty()); } #[test] fn platform_event_bus_remove_clears_tail() { - let bus = PlatformEventBus::new(SeqAllocator::default()); + let bus = PlatformEventBus::new(SeqAllocator::default(), Router::default()); let sandbox_id = "sb-7"; let evt = SandboxStreamEvent { @@ -1449,6 +1530,7 @@ mod tests { pub(crate) struct PlatformEventBus { inner: Arc>, seq: SeqAllocator, + router: Router, } impl PlatformEventBus { @@ -1458,12 +1540,13 @@ impl PlatformEventBus { /// Build a platform event bus sharing `seq` with its owning `TracingLogBus` /// so both stamp cursors from the same per-sandbox sequence. - fn new(seq: SeqAllocator) -> Self { + fn new(seq: SeqAllocator, router: Router) -> Self { Self { inner: Arc::new(Mutex::new(Inner { per_id: HashMap::new(), })), seq, + router, } } @@ -1483,7 +1566,13 @@ impl PlatformEventBus { .subscribe() } - pub(crate) fn publish(&self, sandbox_id: &str, mut event: SandboxStreamEvent) { + pub(crate) fn publish(&self, sandbox_id: &str, event: SandboxStreamEvent) { + if let Some(event) = route(&self.router, sandbox_id, event) { + self.publish_locally(sandbox_id, event); + } + } + + fn publish_locally(&self, sandbox_id: &str, mut event: SandboxStreamEvent) { // Hold the cursor space across the tail insert (same allocator -> map // lock order as `TracingLogBus::publish`), so teardown cannot reset the // counter underneath an in-flight publish. diff --git a/crates/openshell-server/tests/common/mod.rs b/crates/openshell-server/tests/common/mod.rs index 71e3c6b0e6..7859c1f99e 100644 --- a/crates/openshell-server/tests/common/mod.rs +++ b/crates/openshell-server/tests/common/mod.rs @@ -60,6 +60,29 @@ impl OpenShell for TestOpenShell { Err(Status::unimplemented("not used by this test server")) } + async fn peer_publish_sandbox_events( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + + async fn peer_get_sandbox_logs( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + + type PeerWatchSandboxStream = ReceiverStream>; + + async fn peer_watch_sandbox( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn peer_notify_config_update( &self, _request: tonic::Request, diff --git a/crates/openshell-server/tests/supervisor_relay_integration.rs b/crates/openshell-server/tests/supervisor_relay_integration.rs index bff7fe5c67..7feb7b9d9c 100644 --- a/crates/openshell-server/tests/supervisor_relay_integration.rs +++ b/crates/openshell-server/tests/supervisor_relay_integration.rs @@ -58,6 +58,30 @@ impl OpenShell for RelayGateway { Err(Status::unimplemented("not used by this test server")) } + async fn peer_publish_sandbox_events( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + + async fn peer_get_sandbox_logs( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + + type PeerWatchSandboxStream = + ReceiverStream>; + + async fn peer_watch_sandbox( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn peer_notify_config_update( &self, _request: tonic::Request, diff --git a/crates/openshell-supervisor-process/src/delegated.rs b/crates/openshell-supervisor-process/src/delegated.rs index 8e39761034..2956708855 100644 --- a/crates/openshell-supervisor-process/src/delegated.rs +++ b/crates/openshell-supervisor-process/src/delegated.rs @@ -90,6 +90,7 @@ pub async fn start_boundary_access( port_forward: Arc, agent: Arc, supervisor_session_updates: Option>>, + accepted_gateway: Option>>, config_apply_tx: tokio::sync::mpsc::Sender, config_push_updates: tokio::sync::watch::Sender, supported_capabilities: Vec, @@ -132,6 +133,7 @@ pub async fn start_boundary_access( instance_id: instance_id.clone(), app_installations, session_id_updates: supervisor_session_updates, + accepted_gateway, config_apply_tx, config_push_updates, gateway_home, @@ -377,6 +379,7 @@ mod tests { rpc_test::loopback(boundary.clone()), rpc_test::process(boundary), None, + None, tokio::sync::mpsc::channel(1).0, tokio::sync::watch::channel(false).0, Vec::new(), @@ -421,6 +424,7 @@ mod tests { rpc_test::loopback(boundary.clone()), rpc_test::process(boundary), None, + None, tokio::sync::mpsc::channel(1).0, tokio::sync::watch::channel(false).0, Vec::new(), diff --git a/crates/openshell-supervisor-process/src/log_push.rs b/crates/openshell-supervisor-process/src/log_push.rs index 2819b08fa1..04d5490692 100644 --- a/crates/openshell-supervisor-process/src/log_push.rs +++ b/crates/openshell-supervisor-process/src/log_push.rs @@ -11,7 +11,7 @@ use openshell_core::grpc_client::{CachedOpenShellClient, GatewayEndpoint}; use openshell_core::proto::{PushSandboxLogsRequest, SandboxLogLine}; use std::cell::RefCell; use std::sync::Arc; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, watch}; use tracing::{Event, Subscriber}; use tracing_subscriber::Layer; use tracing_subscriber::layer::Context; @@ -161,19 +161,24 @@ pub const LOG_PUSH_QUEUE_LINES: usize = 1024; pub fn spawn_log_push_task( gateway: GatewayEndpoint, sandbox_id: String, + parent: Option>>, ) -> (mpsc::Sender, tokio::task::JoinHandle<()>) { let (tx, rx) = mpsc::channel::(LOG_PUSH_QUEUE_LINES); - (tx, start_log_push(gateway, sandbox_id, rx)) + (tx, start_log_push(gateway, sandbox_id, rx, parent)) } /// Push lines from a queue created before the caller's runtime, with the /// owning sandbox's gateway credentials. +/// +/// Lines go to the sandbox's parent gateway, the endpoint `parent` holds, +/// once known, and to `gateway` before that. pub fn start_log_push( gateway: GatewayEndpoint, sandbox_id: String, lines: mpsc::Receiver, + parent: Option>>, ) -> tokio::task::JoinHandle<()> { - tokio::spawn(run_push_loop(gateway, sandbox_id, lines)) + tokio::spawn(run_push_loop(gateway, sandbox_id, lines, parent)) } /// Maximum backoff delay between reconnection attempts. @@ -187,6 +192,7 @@ async fn run_push_loop( gateway: GatewayEndpoint, sandbox_id: String, mut rx: mpsc::Receiver, + mut parent: Option>>, ) { let mut batch = Vec::with_capacity(LOG_PUSH_BATCH_LINES); let mut backoff = INITIAL_BACKOFF; @@ -197,7 +203,11 @@ async fn run_push_loop( attempt += 1; // --- Connect --- - let client = match CachedOpenShellClient::connect(&gateway).await { + let target = parent + .as_mut() + .and_then(|parent| parent.borrow_and_update().clone()) + .map_or_else(|| gateway.clone(), |url| gateway.with_url(url)); + let client = match CachedOpenShellClient::connect(&target).await { Ok(c) => { if attempt > 1 { eprintln!("openshell: log push reconnected (attempt {attempt})"); @@ -295,6 +305,20 @@ async fn run_push_loop( fatal_auth = rpc_done.unwrap_or(false); break true; } + changed = async { + match parent.as_mut() { + Some(parent) => parent.changed().await, + None => std::future::pending().await, + } + } => { + if changed.is_err() { + parent = None; + continue; + } + // Lines already queued on this stream still reach the old + // gateway, which forwards them to the parent. + break false; + } } }; diff --git a/crates/openshell-supervisor-process/src/supervisor_session.rs b/crates/openshell-supervisor-process/src/supervisor_session.rs index bffe40fb8d..9df624798f 100644 --- a/crates/openshell-supervisor-process/src/supervisor_session.rs +++ b/crates/openshell-supervisor-process/src/supervisor_session.rs @@ -128,6 +128,9 @@ pub struct SessionRuntimeContext { pub instance_id: String, /// Publishes the currently accepted gateway session to sibling reporters. pub session_id_updates: Option>>, + /// Publishes the endpoint of the gateway that accepted the latest session, + /// the sandbox's parent gateway. + pub accepted_gateway: Option>>, /// Applies streamed configuration updates to the running supervisor. pub config_apply_tx: mpsc::Sender, /// Publishes whether the current session pushes configuration, so the @@ -431,6 +434,7 @@ pub fn spawn_with_readiness( terminating, instance_id: runtime.instance_id, session_id_updates: runtime.session_id_updates, + accepted_gateway: runtime.accepted_gateway, config_apply_tx: runtime.config_apply_tx, config_push_updates: runtime.config_push_updates, gateway_home: runtime.gateway_home, @@ -451,6 +455,7 @@ struct SessionConfig { instance_id: String, /// Publishes the currently accepted session to sibling control-plane reporters. session_id_updates: Option>>, + accepted_gateway: Option>>, config_apply_tx: mpsc::Sender, /// Publishes whether the current session pushes configuration. A /// reconnect to a gateway that does not push resumes polling. @@ -791,6 +796,15 @@ async fn run_single_session( if let Some(updates) = &config.session_id_updates { updates.send_replace(Some(accepted.session_id.clone())); } + if let Some(updates) = &config.accepted_gateway { + updates.send_if_modified(|current| { + let changed = current.as_deref() != Some(target.url()); + if changed { + *current = Some(target.url().to_string()); + } + changed + }); + } let event = session_established_event( &openshell_ocsf::ctx::ctx(), target.url(), @@ -1565,6 +1579,7 @@ mod ocsf_event_tests { terminating: Arc::new(AtomicBool::new(false)), instance_id: "instance-1".into(), session_id_updates: None, + accepted_gateway: None, config_apply_tx: mpsc::channel(1).0, config_push_updates: watch::channel(false).0, gateway_home: None, diff --git a/crates/openshell-supervisor/src/backend_setup/tests.rs b/crates/openshell-supervisor/src/backend_setup/tests.rs index 0f5b2ec5e2..6f75aa7ce3 100644 --- a/crates/openshell-supervisor/src/backend_setup/tests.rs +++ b/crates/openshell-supervisor/src/backend_setup/tests.rs @@ -845,6 +845,7 @@ async fn shared_startup_uses_selected_backend_through_readiness_and_shutdown() { container_image_uid: None, openshell_endpoint: None, gateway_home: None, + accepted_gateway: None, policy_rules: Some(rules.to_string_lossy().into_owned()), policy_data: Some(data.to_string_lossy().into_owned()), ssh_socket_path: None, @@ -1066,6 +1067,7 @@ async fn suspend_signal_exits_without_terminating_boundary() { container_image_uid: None, openshell_endpoint: None, gateway_home: None, + accepted_gateway: None, policy_rules: Some(rules.to_string_lossy().into_owned()), policy_data: Some(data.to_string_lossy().into_owned()), ssh_socket_path: None, diff --git a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs index b3c56facda..9c4aaca69f 100644 --- a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs +++ b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs @@ -297,6 +297,7 @@ async fn config_push_regression_legacy_gateway_never_observes_ready_before_workl container_image_uid: None, openshell_endpoint: Some(endpoint), gateway_home: None, + accepted_gateway: None, policy_rules: None, policy_data: None, ssh_socket_path: None, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 6278307846..243bf15724 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -938,6 +938,9 @@ pub struct SandboxInstanceConfig { /// the session dials instead of `openshell_endpoint` when set and /// nonempty. pub gateway_home: Option>>, + /// Publishes the endpoint of the gateway that accepted the latest + /// supervisor session, which the log push dials. + pub accepted_gateway: Option>>, pub policy_rules: Option, pub policy_data: Option, pub ssh_socket_path: Option, @@ -1118,6 +1121,7 @@ pub async fn run_sandbox_instance( container_image_uid: _, openshell_endpoint, gateway_home, + accepted_gateway, policy_rules, policy_data, ssh_socket_path, @@ -1796,6 +1800,7 @@ pub async fn run_sandbox_instance( running.loopback_connector(), agent.clone(), Some(supervisor_session_updates), + accepted_gateway, config_apply_tx, config_push_updates, supported_policy_capabilities(), @@ -4839,6 +4844,7 @@ mod tests { container_image_uid: Some("sha256:workload".into()), openshell_endpoint: None, gateway_home: None, + accepted_gateway: None, policy_rules: None, policy_data: None, ssh_socket_path: None, diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index b455799f1e..0c0564a7d6 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -596,6 +596,7 @@ fn main() -> Result<()> { let exit_code = runtime.block_on(async move { openshell_crypto::tls::ensure_default_provider(); + let (accepted_gateway, parent_gateway) = tokio::sync::watch::channel(None); let log_push_state = if let (Some(sandbox_id), Some(endpoint), Some(credentials)) = ( &args.sandbox_id, &args.openshell_endpoint, @@ -609,6 +610,7 @@ fn main() -> Result<()> { credentials.clone(), ), sandbox_id.clone(), + Some(parent_gateway), ); let layer = openshell_supervisor_process::log_push::LogPushLayer::new(sandbox_id.clone(), tx); @@ -718,6 +720,7 @@ fn main() -> Result<()> { .filter(|uid| !uid.trim().is_empty()), openshell_endpoint: args.openshell_endpoint, gateway_home: None, + accepted_gateway: Some(accepted_gateway), policy_rules: args.policy_rules, policy_data: args.policy_data, ssh_socket_path: args.ssh_socket_path, diff --git a/crates/openshell-supervisor/src/sandbox_instance_host.rs b/crates/openshell-supervisor/src/sandbox_instance_host.rs index ba8a9f9265..6935ed160e 100644 --- a/crates/openshell-supervisor/src/sandbox_instance_host.rs +++ b/crates/openshell-supervisor/src/sandbox_instance_host.rs @@ -745,6 +745,8 @@ pub fn sandbox_instance_launch( })); let (log_tx, log_rx) = tokio::sync::mpsc::channel(openshell_supervisor_process::log_push::LOG_PUSH_QUEUE_LINES); + let (accepted_gateway, parent_gateway) = watch::channel(None); + config.accepted_gateway = Some(accepted_gateway); let bindings = SandboxInstanceBindings { gateway_credentials, event_context: Arc::new(config.event_context()), @@ -758,7 +760,12 @@ pub fn sandbox_instance_launch( let body: SandboxInstanceBody = Box::new(move |controls| { Box::pin(async move { let _log_push = log_push.map(|(sandbox_id, gateway)| { - openshell_supervisor_process::log_push::start_log_push(gateway, sandbox_id, log_rx) + openshell_supervisor_process::log_push::start_log_push( + gateway, + sandbox_id, + log_rx, + Some(parent_gateway), + ) }); Box::pin(crate::run_sandbox_instance( backend_setup.as_ref(), diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 32108cdce4..3609ebc6ad 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -887,6 +887,7 @@ impl SharedHost { container_image_uid: None, openshell_endpoint: Some(self.gateway_endpoint.clone()), gateway_home: Some(self.gateway_home.subscribe()), + accepted_gateway: None, policy_rules: None, policy_data: None, ssh_socket_path: Some(ssh_socket.to_string_lossy().into_owned()), diff --git a/docs/observability/accessing-logs.mdx b/docs/observability/accessing-logs.mdx index b02eb01037..4c57cd6b79 100644 --- a/docs/observability/accessing-logs.mdx +++ b/docs/observability/accessing-logs.mdx @@ -51,7 +51,9 @@ When the container runtime falls behind reading the log, the main process blocks ## Gateway Log Storage -The supervisor pushes logs to the gateway over gRPC in real time. The gateway stores up to 2,000 recent log lines per sandbox in memory. This buffer is not persisted to disk. It is lost when the gateway restarts and when the sandbox is deleted, so a `--no-keep` sandbox leaves no log in the gateway after it exits. Each gateway replica keeps its own buffer. The push channel is bounded and can drop events under load or during disconnection. +The supervisor pushes logs to the gateway over gRPC in real time. The gateway stores up to 2,000 recent log lines per sandbox in memory. This buffer is not persisted to disk. It is lost when the gateway restarts and when the sandbox is deleted, so a `--no-keep` sandbox leaves no log in the gateway after it exits. The push channel is bounded and can drop events under load or during disconnection. + +With multiple gateway replicas, one replica keeps each sandbox's buffer: the replica serving the sandbox's supervisor session, or the last one that served it. Every replica forwards that sandbox's log lines and platform events there, and `openshell logs` returns the same lines from any replica. When the supervisor session moves to another replica, for example because its replica shut down, the buffer starts over on the new replica, and `openshell logs --tail` streams that were open on the old buffer end. For durable retention, collect supervisor output or files and workload container logs into an external log store, or export OCSF events with [OTLP log export](/observability/overview#otlp-log-export). The local files rotate and use temporary storage on container drivers; they are not a durable archive. See [Direct Filesystem Access](#direct-filesystem-access) for locations and collection limits, and [OCSF JSON export](/observability/ocsf-json-export) for structured file output. @@ -72,7 +74,7 @@ The gateway distinguishes recoverable from unrecoverable loss: - **Recoverable lag.** When a consumer falls behind and the gateway skips ahead in its buffer, the stream emits a warning event and keeps running. The warning is the signal that events were skipped. - **Unrecoverable gap.** When a client reconnects and asks to resume after a cursor the gateway has already trimmed from its buffer, the stream ends with an `OUT_OF_RANGE` status. The client should restart observation and, if it needs the missing lines, check collected logs or any remaining supervisor files. Those sources may also have gaps. -A cursor is bound to the cursor space that issued it. A gateway restart, teardown of the sandbox's buffers, or a reconnect that lands on a different gateway replica starts a new space, and cursors from the previous one no longer refer to anything. The gateway rejects them with `OUT_OF_RANGE` instead of treating them as caught up — which would silently suppress the new space's events. A malformed cursor is rejected with `INVALID_ARGUMENT`. +A cursor is bound to the cursor space that issued it. A gateway restart, teardown of the sandbox's buffers, or the buffer moving to another gateway replica starts a new space, and cursors from the previous one no longer refer to anything. The gateway rejects them with `OUT_OF_RANGE` instead of treating them as caught up — which would silently suppress the new space's events. A malformed cursor is rejected with `INVALID_ARGUMENT`. `OUT_OF_RANGE` is terminal for that cursor. Restart the watch with an empty resume cursor; retrying the same one fails identically. diff --git a/docs/observability/gateway-metrics.mdx b/docs/observability/gateway-metrics.mdx index 5f24a9e192..63c0ab333b 100644 --- a/docs/observability/gateway-metrics.mdx +++ b/docs/observability/gateway-metrics.mdx @@ -196,6 +196,7 @@ that owns a sandbox's supervisor session: |---|---|---|---| | `openshell_server_routed_request_attempts_total` | Counter | `operation`, `route`, `relay_kind`, `outcome`, `grpc_code` | Local relay setup and outbound peer attempts, counted once when they finish or are cancelled. Each retry counts separately. | | `openshell_server_peer_request_duration_seconds` | Histogram | `operation`, `outcome` | Latency of outbound peer requests only (`route="peer"`). For relays, until the owner's supervisor claimed the relay. | +| `openshell_server_sandbox_log_events_dropped_total` | Counter | `reason` | Sandbox log lines and platform events dropped on their way to the replica that keeps the sandbox's logs. `reason="queue_full"` means this replica produced them faster than it could forward them; `reason="forward_failed"` means that replica did not accept them. | Mutation locks: diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..4c9eb2dbcb 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -771,6 +771,30 @@ service OpenShell { }; } + // Internal routing of sandbox logs and platform events to the replica that + // holds them: the one serving the sandbox's supervisor session, or the one + // expected to. The receiver serves these from its own buffers only. + rpc PeerPublishSandboxEvents(PeerPublishSandboxEventsRequest) + returns (PeerPublishSandboxEventsResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "peer" + }; + } + + rpc PeerGetSandboxLogs(PeerGetSandboxLogsRequest) + returns (GetSandboxLogsResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "peer" + }; + } + + rpc PeerWatchSandbox(PeerWatchSandboxRequest) + returns (stream SandboxStreamEvent) { + option (openshell.options.v1.authorization) = { + auth_mode: "peer" + }; + } + // Watch a sandbox and stream updates. // // This stream can include: @@ -3739,6 +3763,30 @@ message PeerRelayFrame { } } +message PeerSandboxEvent { + string sandbox_id = 1; + // Cursor is unset; the receiver assigns one. + SandboxStreamEvent event = 2; +} + +message PeerPublishSandboxEventsRequest { + repeated PeerSandboxEvent events = 1; +} + +message PeerPublishSandboxEventsResponse {} + +// The sending replica already authorized `request` and resolved its sandbox. +message PeerGetSandboxLogsRequest { + string sandbox_id = 1; + GetSandboxLogsRequest request = 2; +} + +// The sending replica already authorized `request` and resolved its sandbox. +message PeerWatchSandboxRequest { + string sandbox_id = 1; + WatchSandboxRequest request = 2; +} + message PeerConfigSandboxTarget { string sandbox_id = 1; // Fences a targeted notification to the session observed by the sending replica.