diff --git a/.agents/agents/gator/skills/gator-gate/SKILL.md b/.agents/agents/gator/skills/gator-gate/SKILL.md index 55d7986156..4866b00bb9 100644 --- a/.agents/agents/gator/skills/gator-gate/SKILL.md +++ b/.agents/agents/gator/skills/gator-gate/SKILL.md @@ -935,7 +935,7 @@ Use `test:e2e` for changes that affect: Use `test:e2e` for Helm, Agent Sandbox CRDs, Kubernetes scheduling, namespace, workspace mode, or controller behavior; it runs the Kubernetes, managed-workspace, and operator-workspace suites. -Add `test:e2e-kubernetes` for gateway high availability or Kubernetes Secrets and Vault credential driver storage. It runs only the HA and credential-driver suites, so apply it alongside `test:e2e` when other Kubernetes coverage is also needed. +Add `test:e2e-kubernetes` for gateway high availability, shared-supervisor HA, or Kubernetes Secrets and Vault credential driver storage. It runs the HA, shared-supervisor HA, and credential-driver suites, so apply it alongside `test:e2e` when other Kubernetes coverage is also needed. Apply `test:windows` whenever a PR affects Windows support. This includes Windows or MSVC CI and `mise` tasks, Windows lock-file platform entries, the MXC driver, and `cfg(windows)` implementations or tests in otherwise cross-platform crates. Apply it alongside any applicable E2E label; it is not a substitute for runtime coverage. diff --git a/.config/nextest.toml b/.config/nextest.toml index c5a25293b4..f212177b4c 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -32,7 +32,7 @@ test-group = "kubernetes-ha" # they kill members or gateways, or scale the pool. Never run them at once. # Test names, not binary(), for the reason above. [[profile.e2e-kubernetes.overrides]] -filter = "test(/^(losing_a_supervisor_pod_moves_its_sandboxes_without_restarting_them|scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running|pool_sessions_follow_their_supervisors_gateway|shared_supervisor_acts_as_each_sandboxs_stable_spiffe_identity|supervisors_spread_evenly_across_gateways)$/)" +filter = "test(/^(losing_a_supervisor_pod_moves_its_sandboxes_without_restarting_them|exec_survives_an_abrupt_supervisor_kill|exec_survives_a_supervisor_rollout_restart|scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running|pool_sessions_follow_their_supervisors_gateway|shared_supervisor_acts_as_each_sandboxs_stable_spiffe_identity|supervisors_spread_evenly_across_gateways)$/)" test-group = "kubernetes-shared-supervisor-pool" # Scaling the pool runs two bounded Helm upgrades (up to 6 minutes each), waits @@ -47,6 +47,19 @@ slow-timeout = { period = "60s", terminate-after = 20 } filter = "test(/^pool_sessions_follow_their_supervisors_gateway$/)" slow-timeout = { period = "60s", terminate-after = 20 } +# One abrupt kill, the bounded wait for another member to admit the route, +# and the settle and recovery exec rounds. Waited exec probes block for up to +# the CLI's wait budget each. +[[profile.e2e-kubernetes.overrides]] +filter = "test(/^exec_survives_an_abrupt_supervisor_kill$/)" +slow-timeout = { period = "60s", terminate-after = 15 } + +# A rollout restart of both supervisor members plus a per-sandbox recovery +# bound, and the known-Stopped sandbox is still probed to its deadline. +[[profile.e2e-kubernetes.overrides]] +filter = "test(/^exec_survives_a_supervisor_rollout_restart$/)" +slow-timeout = { period = "60s", terminate-after = 20 } + [[profile.e2e-kubernetes.overrides]] filter = "test(/^shared_supervisor_acts_as_each_sandboxs_stable_spiffe_identity$/)" # Fresh acquisitions through every node and a replacement agent precede diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index d5340f9569..979b3e06eb 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -30,6 +30,7 @@ jobs: run_core_e2e: ${{ steps.labels.outputs.run_core_e2e }} run_kubernetes_ha_e2e: ${{ steps.labels.outputs.run_kubernetes_ha_e2e }} run_kubernetes_credential_drivers_e2e: ${{ steps.labels.outputs.run_kubernetes_credential_drivers_e2e }} + run_kubernetes_shared_supervisor_ha_e2e: ${{ steps.labels.outputs.run_kubernetes_shared_supervisor_ha_e2e }} run_continuity_e2e: ${{ steps.labels.outputs.run_continuity_e2e }} run_any_e2e: ${{ steps.labels.outputs.run_any_e2e }} steps: @@ -54,6 +55,7 @@ jobs: run_core_e2e="$(jq -r 'index("test:e2e") != null' <<< "$LABELS_JSON")" run_kubernetes_ha_e2e="$(jq -r 'index("test:e2e-kubernetes") != null' <<< "$LABELS_JSON")" run_kubernetes_credential_drivers_e2e="$(jq -r 'index("test:e2e-kubernetes") != null' <<< "$LABELS_JSON")" + run_kubernetes_shared_supervisor_ha_e2e="$(jq -r 'index("test:e2e-kubernetes") != null' <<< "$LABELS_JSON")" run_continuity_e2e="$(jq -r 'index("test:e2e:continuity") != null' <<< "$LABELS_JSON")" ;; *) @@ -61,6 +63,7 @@ jobs: run_core_e2e=true run_kubernetes_ha_e2e=false run_kubernetes_credential_drivers_e2e=false + run_kubernetes_shared_supervisor_ha_e2e=false run_continuity_e2e=true ;; esac @@ -68,9 +71,12 @@ jobs: run_core_e2e=false run_kubernetes_ha_e2e=false run_kubernetes_credential_drivers_e2e=false + run_kubernetes_shared_supervisor_ha_e2e=false run_continuity_e2e=false fi - if [ "$run_core_e2e" = "true" ] || [ "$run_kubernetes_ha_e2e" = "true" ] || [ "$run_kubernetes_credential_drivers_e2e" = "true" ]; then + if [ "$run_core_e2e" = "true" ] || [ "$run_kubernetes_ha_e2e" = "true" ] \ + || [ "$run_kubernetes_credential_drivers_e2e" = "true" ] \ + || [ "$run_kubernetes_shared_supervisor_ha_e2e" = "true" ]; then run_any_e2e=true else run_any_e2e=false @@ -82,6 +88,7 @@ jobs: echo "run_core_e2e=$run_core_e2e" echo "run_kubernetes_ha_e2e=$run_kubernetes_ha_e2e" echo "run_kubernetes_credential_drivers_e2e=$run_kubernetes_credential_drivers_e2e" + echo "run_kubernetes_shared_supervisor_ha_e2e=$run_kubernetes_shared_supervisor_ha_e2e" echo "run_continuity_e2e=$run_continuity_e2e" echo "run_any_e2e=$run_any_e2e" } >> "$GITHUB_OUTPUT" @@ -799,6 +806,22 @@ jobs: job-name: Kubernetes Credential Drivers E2E e2e-task: e2e:kubernetes:credential-drivers + kubernetes-shared-supervisor-ha-e2e: + needs: [pr_metadata, build-binaries-linux, build-conformance, build-images] + if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_kubernetes_shared_supervisor_ha_e2e == 'true' + permissions: + actions: read + contents: read + packages: read + uses: ./.github/workflows/e2e-kubernetes-test.yml + with: + checkout-ref: ${{ needs.pr_metadata.outputs.sha }} + prebuilt-conformance: true + image-tag: ${{ needs.pr_metadata.outputs.sha }} + job-name: Kubernetes Shared Supervisor HA E2E + e2e-task: e2e:kubernetes:shared-supervisor-ha + external-postgres-secret: openshell-ha-pg + core-e2e-result: name: Core E2E result needs: @@ -857,3 +880,16 @@ jobs: - uses: ./.github/actions/check-job-results with: results: ${{ toJSON(needs) }} + + kubernetes-shared-supervisor-ha-e2e-result: + name: Kubernetes Shared Supervisor HA E2E result + needs: [pr_metadata, build-binaries-macos, kubernetes-shared-supervisor-ha-e2e] + if: always() && needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_kubernetes_shared_supervisor_ha_e2e == 'true' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ./.github/actions/check-job-results + with: + results: ${{ toJSON(needs) }} diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index dc1ed89ade..4ccc486422 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -1864,6 +1864,19 @@ enum SandboxCommands { #[arg(long)] no_login_shell: bool, + /// Seconds to wait for the sandbox to become Ready before running the + /// command (default: 45, or `OPENSHELL_EXEC_WAIT_TIMEOUT`). Only a + /// sandbox in Provisioning or Starting waits, such as during a + /// supervisor takeover; every other phase fails immediately. `0` + /// disables the wait, like `--no-exec-wait`. + #[arg(long, value_name = "SECONDS", overrides_with = "no_exec_wait")] + exec_wait_timeout: Option, + + /// Fail immediately when the sandbox is not Ready instead of waiting + /// for a supervisor takeover to finish. + #[arg(long, overrides_with = "exec_wait_timeout")] + no_exec_wait: bool, + /// Set a non-secret environment variable for the command. /// Do not use this option for API keys, tokens, or other secrets; attach /// a provider to the sandbox instead. Repeatable. @@ -3885,6 +3898,8 @@ async fn run_async() -> Result<()> { envs, command, no_login_shell, + exec_wait_timeout, + no_exec_wait, } => { let name = resolve_sandbox_name(name.or(sandbox), &ctx.name, &cli.workspace)?; @@ -3896,6 +3911,15 @@ async fn run_async() -> Result<()> { } else { None // auto-detect }; + // Resolve --exec-wait-timeout / --no-exec-wait. A + // zero budget disables the wait; the environment + // and the 45s default are applied in + // `run::sandbox_exec_grpc`. + let exec_wait_timeout_secs = if no_exec_wait { + Some(0) + } else { + exec_wait_timeout + }; let env_map = run::parse_env_pairs(&envs)?; let exit_code = run::sandbox_exec_grpc( endpoint, @@ -3903,6 +3927,7 @@ async fn run_async() -> Result<()> { &command, workdir.as_deref(), timeout, + exec_wait_timeout_secs, tty_override, &env_map, no_login_shell, @@ -6794,6 +6819,61 @@ mod tests { ); } + fn exec_wait_flags(args: &[&str]) -> (Option, bool) { + let cli = Cli::try_parse_from( + ["openshell", "sandbox", "exec", "test-sandbox"] + .into_iter() + .chain(args.iter().copied()) + .chain(["--", "true"]), + ) + .unwrap(); + match cli.command { + Some(Commands::Sandbox { + command: + Some(SandboxCommands::Exec { + exec_wait_timeout, + no_exec_wait, + .. + }), + .. + }) => (exec_wait_timeout, no_exec_wait), + other => panic!("expected SandboxCommands::Exec, got: {other:?}"), + } + } + + #[test] + fn sandbox_exec_wait_flags_parse() { + assert_eq!( + exec_wait_flags(&["--exec-wait-timeout", "5"]), + (Some(5), false) + ); + assert_eq!( + exec_wait_flags(&["--exec-wait-timeout", "0"]), + (Some(0), false), + "a zero budget must parse: it disables the wait like --no-exec-wait" + ); + assert_eq!(exec_wait_flags(&["--no-exec-wait"]), (None, true)); + assert_eq!( + exec_wait_flags(&[]), + (None, false), + "neither flag leaves both unset so the 45s default applies" + ); + } + + #[test] + fn sandbox_exec_wait_flags_use_the_last_one_given() { + assert_eq!( + exec_wait_flags(&["--no-exec-wait", "--exec-wait-timeout", "5"]), + (Some(5), false), + "a later --exec-wait-timeout must clear an earlier --no-exec-wait" + ); + assert_eq!( + exec_wait_flags(&["--exec-wait-timeout", "5", "--no-exec-wait"]), + (None, true), + "a later --no-exec-wait must clear an earlier --exec-wait-timeout" + ); + } + #[test] fn sandbox_create_restart_policy_rejects_unknown_value() { assert!( diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 90e7dd66e3..011a783120 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -45,6 +45,7 @@ use crate::tls::{ GrpcClient, TlsOptions, grpc_client, owner_replica, retry_unrouted, routed_to, with_owner_hint, }; use futures::StreamExt; +use futures::future::{BoxFuture, FutureExt}; use miette::{IntoDiagnostic, Result, WrapErr, miette}; use openshell_bootstrap::{ GatewayMetadata, clear_last_sandbox_if_matches, get_gateway_metadata, save_last_sandbox, @@ -53,27 +54,34 @@ use openshell_core::create_retry::{ AlreadyExistsPlan, CleanupPhase, HolderProvenance, RetryPlan, cleanup_wait_delay, plan_already_exists, plan_retry, retry_stopped_suffix, }; +use openshell_core::exec_wait::{ + ExecWaitPlan, exec_wait_is_waitable, exec_wait_poll_delay, exec_wait_stopped_suffix, + plan_exec_wait, +}; use openshell_core::net::set_tcp_nodelay_best_effort; use openshell_core::proto::{ ApproveAllDraftChunksRequest, ApproveDraftChunkRequest, BeginRootfsTarStagingRequest, ClearDraftChunksRequest, CreateSandboxRequest, CreateSandboxTemplateRequest, CreateSshSessionRequest, DeleteSandboxRequest, DeleteSandboxTemplateRequest, - DeleteServiceRequest, DeletionOutcome, EndpointResult, EndpointStatus, ExecSandboxRequest, - ExposeServiceRequest, GetCurrentUserRequest, GetDraftHistoryRequest, GetDraftPolicyRequest, - GetGatewayConfigRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, - GetSandboxLogsRequest, GetSandboxPolicyStatusRequest, GetSandboxRequest, - GetSandboxTemplateRequest, GetServiceRequest, GpuResourceRequirements, - ListSandboxPoliciesRequest, ListSandboxTemplatesRequest, ListSandboxesRequest, - ListServicesRequest, PolicySource, PolicyStatus, RejectDraftChunkRequest, ResourceRequirements, - ResumeSandboxRequest, RevokeSshSessionRequest, Sandbox, SandboxCondition, SandboxPhase, - SandboxPolicy, SandboxResources, SandboxResponse, SandboxRestartPolicy, SandboxServiceExposure, - SandboxServiceLevel, SandboxSpec, SandboxStartup, SandboxTemplate, SandboxWorkloadConfig, - SandboxWorkloadTemplate, SandboxWorkloadTemplateSpec, ServiceAuthorizationMode, - ServiceBackendHttpVersion, ServiceEndpointResponse, SettingScope, StartSandboxRequest, - StopSandboxRequest, SuspendSandboxRequest, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, - UpdateConfigRequest, WatchSandboxRequest, exec_sandbox_event, tcp_forward_init, + DeleteServiceRequest, DeletionOutcome, EndpointResult, EndpointStatus, ExecSandboxEvent, + ExecSandboxInput, ExecSandboxRequest, ExposeServiceRequest, GetCurrentUserRequest, + GetDraftHistoryRequest, GetDraftPolicyRequest, GetGatewayConfigRequest, + GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxLogsRequest, + GetSandboxPolicyStatusRequest, GetSandboxRequest, GetSandboxTemplateRequest, GetServiceRequest, + GpuResourceRequirements, ListSandboxPoliciesRequest, ListSandboxTemplatesRequest, + ListSandboxesRequest, ListServicesRequest, PolicySource, PolicyStatus, RejectDraftChunkRequest, + ResourceRequirements, ResumeSandboxRequest, RevokeSshSessionRequest, Sandbox, SandboxCondition, + SandboxPhase, SandboxPolicy, SandboxResources, SandboxResponse, SandboxRestartPolicy, + SandboxServiceExposure, SandboxServiceLevel, SandboxSpec, SandboxStartup, SandboxTemplate, + SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateSpec, + ServiceAuthorizationMode, ServiceBackendHttpVersion, ServiceEndpointResponse, SettingScope, + StartSandboxRequest, StopSandboxRequest, SuspendSandboxRequest, TcpForwardFrame, + TcpForwardInit, TcpRelayTarget, UpdateConfigRequest, WatchSandboxRequest, exec_sandbox_event, + tcp_forward_init, +}; +use openshell_core::rpc_error::{ + MUTATION_LOCK_TIMEOUT, SANDBOX_NOT_READY, decode_details, is_mutation_lock_timeout, }; -use openshell_core::rpc_error::{MUTATION_LOCK_TIMEOUT, decode_details, is_mutation_lock_timeout}; use openshell_core::settings; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; use prost::Message; @@ -513,6 +521,43 @@ impl Default for SandboxCreateConfig<'_> { /// cannot build a budget that overflows the retry deadline. const MAX_CREATE_RETRY_TIMEOUT_SECS: u64 = 86_400; +/// Upper bound on `OPENSHELL_EXEC_WAIT_TIMEOUT`, for the same reason. +const MAX_EXEC_WAIT_TIMEOUT_SECS: u64 = 86_400; + +/// Default `sandbox exec` readiness wait: it covers the observed ten to +/// twenty seconds of a supervisor takeover with headroom. +const DEFAULT_EXEC_WAIT_TIMEOUT_SECS: u64 = 45; + +/// Resolve a wall-clock budget from the flag value and an environment variable. +/// +/// The flag wins; the environment follows the `OPENSHELL_PROVISION_TIMEOUT` +/// precedent; `default_secs` applies when neither is set. Both sources are +/// clamped to `ceiling`, so neither can build a budget that runs without +/// bound. A zero budget disables the wait it feeds. +fn resolve_budget( + flag_secs: Option, + env_var: &str, + default_secs: u64, + ceiling: u64, +) -> Duration { + if let Some(secs) = flag_secs { + return Duration::from_secs(u64::from(secs).min(ceiling)); + } + let secs = std::env::var(env_var).ok().map_or(default_secs, |value| { + // An all-digits value that overflows `u64` is still a budget, not + // garbage: clamp it to the ceiling instead of falling back to the + // default. + value.parse::().unwrap_or_else(|_| { + if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) { + u64::MAX + } else { + default_secs + } + }) + }); + Duration::from_secs(secs.min(ceiling)) +} + /// Resolve the create-retry budget from the flag value and the environment. /// /// The flag wins; `OPENSHELL_CREATE_RETRY_TIMEOUT` follows the @@ -521,24 +566,28 @@ const MAX_CREATE_RETRY_TIMEOUT_SECS: u64 = 86_400; /// selects. Both sources are clamped to 24 hours, so neither can build a /// budget that runs without bound. fn resolve_create_retry_timeout(flag_secs: Option) -> Duration { - if let Some(secs) = flag_secs { - return Duration::from_secs(u64::from(secs).min(MAX_CREATE_RETRY_TIMEOUT_SECS)); - } - let secs = std::env::var("OPENSHELL_CREATE_RETRY_TIMEOUT") - .ok() - .map_or(60, |value| { - // An all-digits value that overflows `u64` is still a budget, not - // garbage: clamp it to the ceiling instead of falling back to the - // default. - value.parse::().unwrap_or_else(|_| { - if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) { - u64::MAX - } else { - 60 - } - }) - }); - Duration::from_secs(secs.min(MAX_CREATE_RETRY_TIMEOUT_SECS)) + resolve_budget( + flag_secs, + "OPENSHELL_CREATE_RETRY_TIMEOUT", + 60, + MAX_CREATE_RETRY_TIMEOUT_SECS, + ) +} + +/// Resolve the `sandbox exec` readiness-wait budget from the flag value and +/// the environment. +/// +/// The flag wins; `OPENSHELL_EXEC_WAIT_TIMEOUT` follows the create-retry +/// precedent; the default waits 45 seconds. A zero budget disables the wait, +/// which `--no-exec-wait` selects and `--exec-wait-timeout 0` also expresses. +/// Both sources are clamped to 24 hours. +fn resolve_exec_wait_timeout(flag_secs: Option) -> Duration { + resolve_budget( + flag_secs, + "OPENSHELL_EXEC_WAIT_TIMEOUT", + DEFAULT_EXEC_WAIT_TIMEOUT_SECS, + MAX_EXEC_WAIT_TIMEOUT_SECS, + ) } /// Deadline `budget` from now, saturating rather than panicking when the @@ -554,13 +603,13 @@ fn deadline_after(budget: Duration) -> Instant { } } -/// Seed for create-retry jitter, drawn once per create call. +/// Seed for client-wait jitter, drawn once per command invocation. /// /// `RandomState::new()` mixes a per-process and per-thread counter, so separate -/// CLI invocations retrying the same sandbox name pick different jitter. -/// Deriving it from the sandbox name instead would make every contender -/// re-collide in lockstep. -fn create_retry_seed() -> u64 { +/// CLI invocations waiting on the same sandbox pick different jitter. Deriving +/// it from the sandbox name instead would make every contender re-collide in +/// lockstep. +fn jitter_seed() -> u64 { use std::hash::{BuildHasher, Hasher}; std::collections::hash_map::RandomState::new() @@ -1245,7 +1294,7 @@ pub async fn sandbox_create( &mut client, request, workspace, - CreateRetry::new(create_retry_timeout, create_retry_seed()), + CreateRetry::new(create_retry_timeout, jitter_seed()), )) .await? }; @@ -2517,6 +2566,354 @@ fn piped_stdin_limit_error() -> miette::Report { miette::miette!("piped stdin exceeds the 4 MiB limit; use `sandbox upload` for larger input") } +/// The gateway's pre-relay readiness rejection. +/// +/// The server's readiness gate returns `failed_precondition` with the +/// [`SANDBOX_NOT_READY`] reason before it opens a relay, so the command +/// provably never started. The CLI's own readiness failure carries +/// `(phase: ...)` and a hint instead, which keeps the two distinguishable. +/// +/// Older gateways send only the bare message without error details, so that +/// exact message stays a fallback; a newer gateway's structured reason is +/// authoritative and survives wording drift on either side. +const SERVER_NOT_READY_MESSAGE: &str = "sandbox is not ready"; + +/// The machine-readable reason the gateway attached to `status`, when present. +fn status_reason(status: &Status) -> Option { + Some(decode_details(status)?.error_info()?.reason.clone()) +} + +/// Whether `status` is the gateway's readiness gate, before any relay opened. +fn server_readiness_rejection(status: &Status) -> bool { + if status.code() != Code::FailedPrecondition { + return false; + } + status_reason(status).map_or_else( + || status.message() == SERVER_NOT_READY_MESSAGE, + |reason| reason == SANDBOX_NOT_READY, + ) +} + +/// Wall-clock budget and jitter seed shared by one exec readiness wait. +#[derive(Debug, Clone, Copy)] +struct ExecWait { + budget: Duration, + deadline: Instant, + seed: u64, +} + +impl ExecWait { + fn new(budget: Duration, seed: u64) -> Self { + Self { + budget, + deadline: deadline_after(budget), + seed, + } + } + + /// Time left for polls. + fn remaining(&self) -> Duration { + self.deadline.saturating_duration_since(Instant::now()) + } + + /// Time spent waiting so far. + fn elapsed(&self) -> Duration { + self.budget.saturating_sub(self.remaining()) + } +} + +/// Resolve the sandbox by name and learn which gateway replica owns it. +/// +/// Errors stay [`Status`] so a wait loop can tell a transient read failure from +/// a fatal one before the caller turns it into a report. +async fn fetch_sandbox( + client: &mut GrpcClient, + name: &str, + workspace: &str, +) -> std::result::Result<(Sandbox, Option), Status> { + let response = client + .get_sandbox(with_owner_hint(GetSandboxRequest { + name: name.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + workspace.to_string(), + )), + })) + .await?; + let replica = owner_replica(&response); + let sandbox = response + .into_inner() + .sandbox + .ok_or_else(|| Status::not_found("sandbox not found"))?; + Ok((sandbox, replica)) +} + +/// Exec's readiness failure, with the wait outcome when a bounded wait ended +/// without reaching `Ready`. +fn sandbox_not_ready_report( + name: &str, + phase: SandboxPhase, + wait_suffix: Option<&str>, +) -> miette::Report { + miette::miette!( + "sandbox '{name}' is not ready (phase: {}){}; wait for it to reach Ready state", + phase_name(phase as i32), + wait_suffix.unwrap_or_default() + ) +} + +/// Exec's readiness failure when the rewait's entry read never observed a +/// phase. +/// +/// Naming the pre-rejection snapshot here would contradict itself with "not +/// ready (phase: Ready)", and the rewait's own span is the time it can +/// honestly report. +fn rewait_stopped_report(name: &str, waited: Duration) -> miette::Report { + miette::miette!( + "sandbox '{name}' is not ready; the readiness re-check after the gateway rejected the \ + exec stopped after {}s without observing a phase; wait for it to reach Ready state", + waited.as_secs() + ) +} + +/// Wait until `sandbox` reaches `Ready`, or stop on a phase exec cannot use. +/// +/// `sandbox` is the snapshot from the name resolution. With `wait`, polls +/// `GetSandbox` with the shared jittered backoff until the sandbox is `Ready` +/// or the budget runs out; without it, only an already-`Ready` snapshot passes, +/// which preserves the instant failure `--no-exec-wait` selects. Every phase +/// other than `Provisioning` and `Starting` fails immediately, so a stopped or +/// suspended sandbox cannot burn the budget. Progress lines go to stderr so +/// structured stdout stays parseable. Returns the ready snapshot and the owner +/// replica the latest read reported. +async fn wait_for_sandbox_ready( + client: &mut GrpcClient, + mut sandbox: Sandbox, + workspace: &str, + wait: Option, +) -> Result<(Sandbox, Option)> { + let name = sandbox.object_name().to_string(); + let mut replica = None; + let mut poll_attempt: u32 = 0; + loop { + let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); + let plan = match wait { + Some(wait) => plan_exec_wait(phase, poll_attempt, wait.seed, wait.remaining()), + None if phase == SandboxPhase::Ready => ExecWaitPlan::Proceed, + None => ExecWaitPlan::Stop, + }; + match plan { + ExecWaitPlan::Proceed => return Ok((sandbox, replica)), + ExecWaitPlan::Stop => { + // Name the wait only when the sandbox was waitable: a stopped + // or suspended phase never had a wait to exhaust. + let suffix = wait + .filter(|_| exec_wait_is_waitable(phase)) + .map(|wait| exec_wait_stopped_suffix(wait.elapsed(), phase_name(phase as i32))); + return Err(sandbox_not_ready_report(&name, phase, suffix.as_deref())); + } + ExecWaitPlan::Sleep(delay) => { + let wait = wait.expect("only a configured wait polls"); + eprintln!( + "waiting for sandbox '{name}' to become ready (phase: {}); budget {} left", + phase_name(phase as i32), + format_retry_budget(wait.remaining()) + ); + tokio::time::sleep(delay).await; + poll_attempt = poll_attempt.saturating_add(1); + let remaining = wait.remaining(); + if remaining.is_zero() { + // A late timer wake must not start a read outside the + // budget. + return Err(sandbox_not_ready_report( + &name, + phase, + Some(&exec_wait_stopped_suffix( + wait.elapsed(), + phase_name(phase as i32), + )), + )); + } + // Bound the read itself: a stuck GetSandbox must not keep the + // exec pending past its budget. + let observed = match tokio::time::timeout( + remaining, + fetch_sandbox(client, &name, workspace), + ) + .await + { + Err(_elapsed) => { + return Err(sandbox_not_ready_report( + &name, + phase, + Some(&exec_wait_stopped_suffix( + wait.elapsed(), + phase_name(phase as i32), + )), + )); + } + // A transient read failure says nothing about the + // sandbox: ask again after the next poll interval + // while the budget allows. The loop's own plan sleeps + // that interval and stops once it no longer fits, and + // the edge proxy answers `unavailable` while gateway + // replicas roll. + Ok(Err(transient)) if transient.code() == Code::Unavailable => { + eprintln!( + "sandbox '{name}' readiness status unavailable; retrying (budget {} left)", + format_retry_budget(wait.remaining()), + ); + continue; + } + Ok(result) => result.into_diagnostic()?, + }; + let (observed, owner) = observed; + sandbox = observed; + if owner.is_some() { + replica = owner; + } + } + } + } +} + +/// Re-enter the bounded wait after the gateway's pre-relay readiness +/// rejection. +/// +/// The rejection proves the command never started, so a caller may resend it +/// once after the sandbox comes back. The entry read is bounded by the wait's +/// remaining budget: a hung `GetSandbox` must not hold the exec past it. Every +/// failure carries the original gate rejection as context, so the user sees +/// both what rejected the exec and what ended the wait. +/// +/// The future is boxed so it does not bloat every caller's state machine, the +/// way the gateway boxes its create handler. +fn rewait_after_readiness_rejection<'a>( + client: &'a mut GrpcClient, + name: &'a str, + workspace: &'a str, + wait: ExecWait, + rejection: &'a Status, +) -> BoxFuture<'a, Result>> { + let context = format!( + "the exec was first rejected by the gateway readiness gate: {}", + rejection.message() + ); + async move { + // Only the entry read can stop the rewait before the shared wait loop + // takes over, and it observes no phase: reporting the pre-rejection + // snapshot here would contradict itself with "not ready (phase: + // Ready)", and charging the whole exec wait's elapsed time would + // overstate this re-check. + let rewait_started = Instant::now(); + let stopped = move || rewait_stopped_report(name, rewait_started.elapsed()); + let outcome = async { + let mut poll_attempt: u32 = 0; + let (observed, fetched_owner) = loop { + let remaining = wait.remaining(); + if remaining.is_zero() { + return Err(stopped()); + } + let fetched = + match tokio::time::timeout(remaining, fetch_sandbox(client, name, workspace)) + .await + { + Err(_elapsed) => return Err(stopped()), + Ok(fetched) => fetched, + }; + match fetched { + Ok(fetched) => break fetched, + // The edge proxy answers `unavailable` while gateway + // replicas roll, which is exactly when this wait + // re-enters. Mirror the main loop's tolerance exactly: + // the shared jittered poll delay, and the wall-clock + // budget as the only bound — no attempt cap, which could + // only truncate the budget the caller advertised. + Err(transient) if transient.code() == Code::Unavailable => { + let delay = exec_wait_poll_delay(poll_attempt, wait.seed); + if delay >= wait.remaining() { + return Err(stopped()); + } + tokio::time::sleep(delay).await; + poll_attempt = poll_attempt.saturating_add(1); + } + Err(fatal) => { + // Keep the status diagnostic the main loop would show. + let failed: std::result::Result<_, Status> = Err(fatal); + return failed.into_diagnostic(); + } + } + }; + let (_, polled_owner) = + wait_for_sandbox_ready(client, observed, workspace, Some(wait)).await?; + Ok(polled_owner.or(fetched_owner)) + } + .await; + outcome.wrap_err(context) + } + .boxed() +} + +/// Send one exec request, retrying once without routing when no gateway +/// received it. +async fn send_exec( + client: &mut GrpcClient, + request: ExecSandboxRequest, + replica: Option<&AsciiMetadataValue>, +) -> std::result::Result>, Status> { + let retry = replica.is_some().then(|| request.clone()); + match ( + client.exec_sandbox(routed_to(request, replica)).await, + retry, + ) { + (Err(status), Some(unrouted)) if retry_unrouted(replica, &status) => { + client.exec_sandbox(unrouted).await + } + (response, _) => response, + } +} + +/// Raw interactive exec response, kept un-converted so a caller can still +/// classify a gateway readiness rejection. +type InteractiveExecResponse = + std::result::Result>, Status>; + +/// Send one interactive exec request, retrying once without routing when no +/// gateway received it. +/// +/// Returns the input sender the caller must keep alive for the stream's +/// lifetime, alongside the raw response. Both the first attempt and the +/// post-readiness resend go through here so the unrouted fallback cannot +/// drift between them. +async fn send_exec_interactive( + client: &mut GrpcClient, + start: &ExecSandboxInput, + replica: Option<&AsciiMetadataValue>, +) -> Result<( + tokio::sync::mpsc::Sender, + InteractiveExecResponse, +)> { + use tokio_stream::wrappers::ReceiverStream; + + let (tx, rx) = tokio::sync::mpsc::channel::(64); + tx.send(start.clone()).await.into_diagnostic()?; + let response = client + .exec_sandbox_interactive(routed_to(ReceiverStream::new(rx), replica)) + .await; + if let Err(status) = &response + && retry_unrouted(replica, status) + { + // No gateway received the first request, so the unrouted retry cannot + // double-start the command. + let (tx, rx) = tokio::sync::mpsc::channel::(64); + tx.send(start.clone()).await.into_diagnostic()?; + let retried = client + .exec_sandbox_interactive(ReceiverStream::new(rx)) + .await; + return Ok((tx, retried)); + } + Ok((tx, response)) +} + /// Execute a command in a running sandbox via gRPC, streaming output to the terminal. /// /// Returns the remote command's exit code, or an error if the event stream @@ -2528,6 +2925,7 @@ pub async fn sandbox_exec_grpc( command: &[String], workdir: Option<&str>, timeout_seconds: u32, + exec_wait_timeout_secs: Option, tty_override: Option, environment: &HashMap, no_login_shell: bool, @@ -2537,29 +2935,22 @@ pub async fn sandbox_exec_grpc( let mut client = grpc_client(server, tls).await?; // Resolve sandbox name to id. - let response = client - .get_sandbox(with_owner_hint(GetSandboxRequest { - name: name.to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - workspace.to_string(), - )), - })) + let (sandbox, fetched_replica) = fetch_sandbox(&mut client, name, workspace) .await .into_diagnostic()?; - let replica = owner_replica(&response); - let sandbox = response - .into_inner() - .sandbox - .ok_or_else(|| miette::miette!("sandbox not found"))?; - - // Verify the sandbox is ready before issuing the exec. - if SandboxPhase::try_from(sandbox.phase()) != Ok(SandboxPhase::Ready) { - return Err(miette::miette!( - "sandbox '{}' is not ready (phase: {}); wait for it to reach Ready state", - name, - phase_name(sandbox.phase()) - )); - } + let exec_wait_budget = resolve_exec_wait_timeout(exec_wait_timeout_secs); + let exec_wait = + (!exec_wait_budget.is_zero()).then(|| ExecWait::new(exec_wait_budget, jitter_seed())); + + // Wait for the sandbox to come back before collecting stdin or issuing + // anything: exec is not idempotent and piped input cannot be replayed. A + // supervisor takeover leaves a shared sandbox in `Provisioning` or + // `Starting` for ten to twenty seconds, and failing on the first + // observation turns that window into an instant error. Without a budget + // this only keeps the previous fail-fast behavior. + let (sandbox, polled_replica) = + wait_for_sandbox_ready(&mut client, sandbox, workspace, exec_wait).await?; + let mut replica = polled_replica.or(fetched_replica); // Resolve TTY mode: explicit --tty / --no-tty wins, otherwise auto-detect. let stdin_is_terminal = std::io::stdin().is_terminal(); @@ -2626,6 +3017,7 @@ pub async fn sandbox_exec_grpc( return sandbox_exec_streaming_grpc( client, &sandbox, + workspace, command, workdir, timeout_seconds, @@ -2636,25 +3028,37 @@ pub async fn sandbox_exec_grpc( std::mem::take(&mut request.stdin), stdin_rest, replica.as_ref(), + exec_wait, ) .await; } - // Make the streaming gRPC call. - let retry = replica.is_some().then(|| request.clone()); - let mut stream = match ( - client - .exec_sandbox(routed_to(request, replica.as_ref())) - .await, - retry, - ) { - (Err(status), Some(request)) if retry_unrouted(replica.as_ref(), &status) => { - client.exec_sandbox(request).await + // Send the exec, retrying once without routing only when no gateway + // received it. + // + // A Ready read can go stale before the gateway sees the request: when the + // supervisor died in that window, the gateway rejects with its own + // readiness gate before it opens the relay, so the command provably never + // started and nothing has been streamed. Wait again within the same budget + // in that one case, when the wait is on, and send the exec once more. Every + // other failure, including a relay timeout and a post-stream error, stays + // fatal. + let mut resend = exec_wait.map(|_| request.clone()); + let mut response = send_exec(&mut client, request, replica.as_ref()).await; + let rejection = response + .as_ref() + .err() + .filter(|status| server_readiness_rejection(status)) + .cloned(); + if let (Some(wait), Some(request), Some(rejection)) = (exec_wait, resend.take(), rejection) { + if let Some(owner) = + rewait_after_readiness_rejection(&mut client, name, workspace, wait, &rejection).await? + { + replica = Some(owner); } - (response, _) => response, + response = send_exec(&mut client, request, replica.as_ref()).await; } - .into_diagnostic()? - .into_inner(); + let mut stream = response.into_diagnostic()?.into_inner(); // Stream output to terminal in real-time. let mut exit_code = 0i32; @@ -3118,6 +3522,7 @@ impl Drop for TaskGuard { async fn sandbox_exec_streaming_grpc( mut client: GrpcClient, sandbox: &Sandbox, + workspace: &str, command: &[String], workdir: Option<&str>, timeout_seconds: u32, @@ -3128,11 +3533,11 @@ async fn sandbox_exec_streaming_grpc( stdin_prefix: Vec, stdin_rest: Option>>>, replica: Option<&AsciiMetadataValue>, + exec_wait: Option, ) -> Result { #[cfg(unix)] use openshell_core::proto::ExecSandboxWindowResize; - use openshell_core::proto::{ExecSandboxInput, exec_sandbox_input}; - use tokio_stream::wrappers::ReceiverStream; + use openshell_core::proto::exec_sandbox_input; let (cols, rows) = if tty { local_terminal_size().unwrap_or((80, 24)) @@ -3160,24 +3565,35 @@ async fn sandbox_exec_streaming_grpc( })), }; - let (mut input_tx, input_rx) = tokio::sync::mpsc::channel::(64); - input_tx.send(start.clone()).await.into_diagnostic()?; - let mut stream = match client - .exec_sandbox_interactive(routed_to(ReceiverStream::new(input_rx), replica)) - .await - { - Err(status) if retry_unrouted(replica, &status) => { - let (tx, rx) = tokio::sync::mpsc::channel::(64); - tx.send(start).await.into_diagnostic()?; - input_tx = tx; - client - .exec_sandbox_interactive(ReceiverStream::new(rx)) - .await - } - response => response, + let (mut input_tx, mut response) = send_exec_interactive(&mut client, &start, replica).await?; + + // A Ready read can go stale before the gateway sees the start message, so + // the gateway can reject with its own readiness gate before it opens the + // relay: the command provably never started. The start message and the + // collected stdin prefix are replayable, so wait again within the same + // budget and resend once. Piped stdin that is still open (`stdin_rest`) is + // not replayable — its receiver is consumed once into the input channel — + // so that rejection stays fatal, as does every post-stream failure. + let rejection = response + .as_ref() + .err() + .filter(|status| server_readiness_rejection(status)) + .cloned(); + if let (Some(wait), Some(rejection), true) = (exec_wait, rejection, stdin_rest.is_none()) { + let owner = rewait_after_readiness_rejection( + &mut client, + sandbox.object_name(), + workspace, + wait, + &rejection, + ) + .await?; + let (tx, resend) = + send_exec_interactive(&mut client, &start, owner.as_ref().or(replica)).await?; + input_tx = tx; + response = resend; } - .into_diagnostic()? - .into_inner(); + let mut stream = response.into_diagnostic()?.into_inner(); // Raw mode is only appropriate for an interactive terminal, not a pipe. let raw_guard = if tty && stdin_is_terminal { @@ -7718,16 +8134,17 @@ fn format_endpoint(endpoint: &openshell_core::proto::NetworkEndpoint) -> String mod tests { use super::{ CreateAttemptPlan, CreateRetry, ForwardTcpConnectionError, MAX_CREATE_RETRY_TIMEOUT_SECS, - PolicyGetView, ProvisioningStep, build_sandbox_resource_limits, create_retry_annotation, - deadline_after, format_endpoint, format_log_line, forward_requires_session_token, - git_sync_files, has_main_process_result, parse_cli_setting_value, - parse_credential_expiry_cli_value, parse_driver_config_json, parse_env_from_pairs, - parse_secret_material_env_pairs, policy_revision_list_json, policy_revision_to_json, - proto_execution_timeout, provisioning_blocker_message, provisioning_timeout_message, - relay_local_socket, resolve_create_retry_timeout, resolve_from, - rootfs_tar_sources_supported_for_gateway, sandbox_should_persist, sandbox_upload_plan, - service_endpoint_to_json, service_status_error, service_url_for_gateway, - workspace_member_to_json, + MAX_EXEC_WAIT_TIMEOUT_SECS, PolicyGetView, ProvisioningStep, build_sandbox_resource_limits, + create_retry_annotation, deadline_after, format_endpoint, format_log_line, + forward_requires_session_token, git_sync_files, has_main_process_result, + parse_cli_setting_value, parse_credential_expiry_cli_value, parse_driver_config_json, + parse_env_from_pairs, parse_secret_material_env_pairs, policy_revision_list_json, + policy_revision_to_json, proto_execution_timeout, provisioning_blocker_message, + provisioning_timeout_message, relay_local_socket, resolve_create_retry_timeout, + resolve_exec_wait_timeout, resolve_from, rewait_stopped_report, + rootfs_tar_sources_supported_for_gateway, sandbox_not_ready_report, sandbox_should_persist, + sandbox_upload_plan, server_readiness_rejection, service_endpoint_to_json, + service_status_error, service_url_for_gateway, workspace_member_to_json, }; use openshell_core::proto::TcpForwardFrame; @@ -7982,6 +8399,155 @@ mod tests { }); } } + + #[test] + fn exec_wait_timeout_prefers_the_flag_then_the_environment() { + assert_eq!(resolve_exec_wait_timeout(Some(5)), Duration::from_secs(5)); + assert_eq!( + resolve_exec_wait_timeout(Some(0)), + Duration::ZERO, + "--exec-wait-timeout 0 disables the wait like --no-exec-wait" + ); + assert_eq!( + resolve_exec_wait_timeout(Some(u32::MAX)), + Duration::from_secs(MAX_EXEC_WAIT_TIMEOUT_SECS), + "the flag is clamped to 24 hours like the environment" + ); + Environment::new() + .set("OPENSHELL_EXEC_WAIT_TIMEOUT", "7") + .run(|| { + assert_eq!( + resolve_exec_wait_timeout(None), + Duration::from_secs(7), + "the environment supplies the budget when the flag is absent" + ); + assert_eq!( + resolve_exec_wait_timeout(Some(3)), + Duration::from_secs(3), + "the flag wins over the environment" + ); + }); + Environment::new() + .remove("OPENSHELL_EXEC_WAIT_TIMEOUT") + .run(|| { + assert_eq!( + resolve_exec_wait_timeout(None), + Duration::from_secs(45), + "the wait stays on by default" + ); + }); + Environment::new() + .set("OPENSHELL_EXEC_WAIT_TIMEOUT", "0") + .run(|| { + assert_eq!( + resolve_exec_wait_timeout(None), + Duration::ZERO, + "a zero environment budget disables the wait" + ); + }); + for value in ["90000", "18446744073709551615", "18446744073709551616"] { + Environment::new() + .set("OPENSHELL_EXEC_WAIT_TIMEOUT", value) + .run(|| { + assert_eq!( + resolve_exec_wait_timeout(None), + Duration::from_secs(MAX_EXEC_WAIT_TIMEOUT_SECS), + "an oversized environment budget is clamped to 24 hours, \ + including a value above u64::MAX" + ); + }); + } + for value in ["abc", "-1"] { + Environment::new() + .set("OPENSHELL_EXEC_WAIT_TIMEOUT", value) + .run(|| { + assert_eq!( + resolve_exec_wait_timeout(None), + Duration::from_secs(45), + "an unparseable environment budget falls back to the default" + ); + }); + } + } + + #[test] + fn only_the_gateways_pre_relay_rejection_counts_as_not_ready() { + // The current gateway attaches SANDBOX_NOT_READY, so the classification + // holds even if either side rewords the prose. + assert!(server_readiness_rejection( + &openshell_core::rpc_error::failed_precondition( + openshell_core::rpc_error::SANDBOX_NOT_READY, + "sandbox is not ready" + ) + )); + assert!(server_readiness_rejection( + &openshell_core::rpc_error::failed_precondition( + openshell_core::rpc_error::SANDBOX_NOT_READY, + "sandbox not ready yet" + ) + )); + // A structured reason under another name is a different rejection, even + // when its prose happens to match the gate's. + assert!(!server_readiness_rejection( + &openshell_core::rpc_error::failed_precondition( + "SOMETHING_ELSE", + "sandbox is not ready" + ) + )); + // An older gateway sends only the bare message, so keep the exact-match + // fallback for it. + assert!(server_readiness_rejection(&Status::failed_precondition( + "sandbox is not ready" + ))); + // The CLI's own failure carries the phase and a hint; it must never be + // mistaken for the gateway's pre-start rejection. + assert!(!server_readiness_rejection(&Status::failed_precondition( + "sandbox 'a' is not ready (phase: Provisioning); wait for it to reach Ready state" + ))); + for other in [ + Status::unavailable("sandbox is not ready"), + Status::internal("sandbox is not ready"), + ] { + assert!( + !server_readiness_rejection(&other), + "only failed_precondition is the readiness gate" + ); + } + } + + #[test] + fn not_ready_report_appends_the_wait_suffix_only_when_given_one() { + use openshell_core::proto::SandboxPhase; + + // A terminal phase never had a wait, so its failure carries no suffix. + assert_eq!( + sandbox_not_ready_report("x", SandboxPhase::Stopped, None).to_string(), + "sandbox 'x' is not ready (phase: Stopped); wait for it to reach Ready state" + ); + // A waitable phase whose wait ran out names the budget and last phase + // without turning the timeout into a terminal-state message. + assert_eq!( + sandbox_not_ready_report( + "x", + SandboxPhase::Provisioning, + Some(" (exec wait stopped after 45s; last observed phase: Provisioning)"), + ) + .to_string(), + "sandbox 'x' is not ready (phase: Provisioning) (exec wait stopped after 45s; last observed phase: Provisioning); wait for it to reach Ready state" + ); + } + + #[test] + fn rewait_stopped_report_never_names_the_pre_rejection_phase() { + // The rewait's entry read can stop before it observes a phase, and the + // snapshot that passed the wait is always Ready; naming it would + // produce a contradictory "not ready (phase: Ready)". + let message = rewait_stopped_report("x", Duration::from_secs(3)).to_string(); + assert!(message.contains("after 3s"), "{message}"); + assert!(message.contains("without observing a phase"), "{message}"); + assert!(!message.contains("phase: Ready"), "{message}"); + } + use crate::TEST_ENV_LOCK; use crate::commands::common::{ parse_credential_expiry_pairs, parse_credential_pairs, progress_step_from_metadata, diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index e20c253af1..d0aa6944a5 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -15,8 +15,8 @@ use openshell_core::proto::{ CreateSandboxRequest, CreateSandboxTemplateRequest, CreateSshSessionRequest, CreateSshSessionResponse, DeleteProviderRequest, DeleteProviderResponse, DeleteSandboxRequest, DeleteSandboxResponse, DeleteSandboxTemplateRequest, DetachSandboxProviderRequest, - DetachSandboxProviderResponse, ExecSandboxEvent, ExecSandboxRequest, GetGatewayConfigRequest, - GetGatewayConfigResponse, GetProviderRequest, GetSandboxConfigRequest, + DetachSandboxProviderResponse, ExecSandboxEvent, ExecSandboxExit, ExecSandboxRequest, + GetGatewayConfigRequest, GetGatewayConfigResponse, GetProviderRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, GetSandboxRequest, GetSandboxTemplateRequest, GpuResourceRequirements, HealthRequest, HealthResponse, ListProvidersRequest, @@ -27,8 +27,8 @@ use openshell_core::proto::{ SandboxResponse, SandboxStatus, SandboxStreamEvent, SandboxTemplateResponse, SandboxWorkloadTemplate, ServiceAuthorizationMode, ServiceBackendHttpVersion, ServiceEndpoint, ServiceStatus, SettingValue, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, - UpdateProviderRequest, WatchSandboxRequest, sandbox_stream_event, tcp_forward_frame, - tcp_forward_init, + UpdateProviderRequest, WatchSandboxRequest, exec_sandbox_event, sandbox_stream_event, + tcp_forward_frame, tcp_forward_init, }; use openshell_core::rpc_error::StatusExt as _; use openshell_server::test_support::grpc::open_shell_server::{OpenShell, OpenShellServer}; @@ -90,6 +90,15 @@ struct SandboxState { /// sandboxes. Checked before `get_sandbox_failures` and /// `get_sandbox_phases`. get_sandbox_script: Arc>>, + /// Scripted `x-openshell-owner` response headers for `get_sandbox`, oldest + /// first. `None` leaves that response unrouted. + get_sandbox_owner: Arc>>>, + /// Scripted `exec_sandbox` outcomes, oldest first. Empty opens an empty + /// relay, the response every non-exec test already got. + exec_outcomes: Arc>>, + /// The `x-openshell-replica` header of every `exec_sandbox` call, in call + /// order, so a test can assert where each resend was routed. + exec_requests: Arc>>>, expose_service_requests: Arc>>, expose_service_supports_http2: Arc, fail_delete_sandbox_message: Arc>>, @@ -141,6 +150,15 @@ enum GetSandboxOutcome { NoMetadata(SandboxPhase), } +/// One scripted `exec_sandbox` outcome. +enum ExecOutcome { + /// Reject the exec before a relay opens, as the gateway readiness gate + /// does. + Reject(Status), + /// Open a relay that reports a clean exit with this code. + Exit(i32), +} + #[tonic::async_trait] impl OpenShell for TestOpenShell { // The rejected-suspend test checks that this error preserves active forwards. @@ -326,12 +344,26 @@ impl OpenShell for TestOpenShell { ..Sandbox::default() }; sandbox.set_phase(phase as i32); - Ok(Response::new(SandboxResponse { + let owner = self + .state + .get_sandbox_owner + .lock() + .await + .pop_front() + .flatten(); + let mut response = Response::new(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), sandbox: Some(sandbox), service_urls: HashMap::new(), - })) + }); + if let Some(owner) = owner { + response.metadata_mut().insert( + openshell_core::replica_routing::OWNER_REPLICA_HEADER, + owner.parse().expect("ascii owner replica"), + ); + } + Ok(response) } async fn list_sandboxes( @@ -913,12 +945,39 @@ impl OpenShell for TestOpenShell { async fn exec_sandbox( &self, - _request: tonic::Request, + request: tonic::Request, ) -> Result>, Status> { - let (_tx, rx) = mpsc::channel(1); - Ok(Response::new(Box::pin( - tokio_stream::wrappers::ReceiverStream::new(rx), - ))) + let replica = request + .metadata() + .get(openshell_core::replica_routing::ROUTE_REPLICA_HEADER) + .map(|value| value.to_str().expect("ascii replica header").to_string()); + self.state.exec_requests.lock().await.push(replica); + + let outcome = self.state.exec_outcomes.lock().await.pop_front(); + match outcome { + Some(ExecOutcome::Reject(status)) => Err(status), + Some(ExecOutcome::Exit(code)) => { + let (tx, rx) = mpsc::channel(1); + tokio::spawn(async move { + let _ = tx + .send(Ok(ExecSandboxEvent { + payload: Some(exec_sandbox_event::Payload::Exit(ExecSandboxExit { + exit_code: code, + })), + })) + .await; + }); + Ok(Response::new(Box::pin( + tokio_stream::wrappers::ReceiverStream::new(rx), + ))) + } + None => { + let (_tx, rx) = mpsc::channel(1); + Ok(Response::new(Box::pin( + tokio_stream::wrappers::ReceiverStream::new(rx), + ))) + } + } } async fn update_config( @@ -3310,6 +3369,54 @@ async fn run_cli_sandbox_create_with_xdg_and_env( .unwrap() } +/// Run `sandbox exec` through the CLI binary. +/// +/// `Command::output` gives the child a closed stdin, so the exec takes the +/// single-request path whose pre-relay rejection this suite exercises. +async fn run_cli_sandbox_exec(server: &TestServer, extra_args: &[&str]) -> std::process::Output { + let xdg_dir = helpers::tempdir().unwrap(); + prepare_cli_xdg(server, &xdg_dir); + let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell")); + for (key, _) in std::env::vars().filter(|(k, _)| k.starts_with("OPENSHELL_")) { + cmd.env_remove(&key); + } + cmd.args([ + "--gateway", + "openshell", + "--gateway-endpoint", + &server.endpoint, + "--color", + "never", + "sandbox", + "exec", + "--name", + "test-sandbox", + "--no-tty", + "--no-login-shell", + ]) + .args(extra_args) + .arg("--") + .arg("test-command") + .env("XDG_CONFIG_HOME", xdg_dir.path()) + .env("HOME", xdg_dir.path()) + .output() + .await + .unwrap() +} + +/// Collapse an error report to one line for substring matching. +/// +/// miette wraps the report to the terminal width and prefixes each wrapped +/// line with a gutter, so a wrapped message would otherwise split the text a +/// test looks for. +fn flatten_report(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes) + .split_whitespace() + .filter(|token| !matches!(*token, "│" | "×")) + .collect::>() + .join(" ") +} + async fn run_cli_sandbox_create( server: &TestServer, name: &str, @@ -5461,6 +5568,188 @@ async fn sandbox_create_first_attempt_cleanup_wait_exhaustion_is_annotated() { .await; } +#[tokio::test] +async fn sandbox_exec_rewait_resends_once_when_a_ready_read_goes_stale_before_the_relay() { + // The initial Ready read went stale: the gateway's own readiness gate + // rejects the exec before any relay opens, proving the command never + // started. With the wait on, the CLI must re-fetch the sandbox, wait for it + // to come back Ready, and resend the exec exactly once. + let server = run_server().await; + { + let mut outcomes = server.openshell.state.exec_outcomes.lock().await; + outcomes.push_back(ExecOutcome::Reject(Status::failed_precondition( + "sandbox is not ready", + ))); + outcomes.push_back(ExecOutcome::Exit(0)); + } + { + // Both the initial read and the re-fetch see Ready; only the exec + // between them is rejected. + let mut phases = server.openshell.state.get_sandbox_phases.lock().await; + phases.push_back(SandboxPhase::Ready); + phases.push_back(SandboxPhase::Ready); + } + { + // The re-fetch reports the new owner replica, which the resent exec + // must route to. + let mut owner = server.openshell.state.get_sandbox_owner.lock().await; + owner.push_back(None); + owner.push_back(Some("openshell-2")); + } + + let output = run_cli_sandbox_exec(&server, &[]).await; + assert!( + output.status.success(), + "the rejected exec should be resent after the wait: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + *server.openshell.state.exec_requests.lock().await, + vec![None, Some("openshell-2".to_string())], + "the exec must be resent exactly once, routed to the re-fetched owner" + ); +} + +#[tokio::test] +async fn sandbox_exec_does_not_rewait_without_a_wait() { + // Without a wait the gateway's readiness rejection stays fatal: deleting + // the re-wait block must not change this case. + let server = run_server().await; + { + let mut outcomes = server.openshell.state.exec_outcomes.lock().await; + outcomes.push_back(ExecOutcome::Reject(Status::failed_precondition( + "sandbox is not ready", + ))); + outcomes.push_back(ExecOutcome::Exit(0)); + } + + let output = run_cli_sandbox_exec(&server, &["--no-exec-wait"]).await; + assert!(!output.status.success(), "the rejection must stay fatal"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("sandbox is not ready"), "{stderr}"); + assert_eq!( + server.openshell.state.exec_requests.lock().await.len(), + 1, + "--no-exec-wait must not resend the exec" + ); +} + +#[tokio::test] +async fn sandbox_exec_does_not_rewait_on_a_failure_that_is_not_the_gateways_readiness_gate() { + // The same message under a different code does not prove the command never + // started, so it must not trigger a resend. + let server = run_server().await; + { + let mut outcomes = server.openshell.state.exec_outcomes.lock().await; + outcomes.push_back(ExecOutcome::Reject(Status::internal( + "sandbox is not ready", + ))); + outcomes.push_back(ExecOutcome::Exit(0)); + } + + let output = run_cli_sandbox_exec(&server, &[]).await; + assert!( + !output.status.success(), + "only the readiness gate is retryable" + ); + assert_eq!( + server.openshell.state.exec_requests.lock().await.len(), + 1, + "a non-gateway failure must not be resent" + ); +} + +#[tokio::test] +async fn sandbox_exec_wait_retries_a_transient_read_failure() { + // The edge proxy answers `unavailable` while gateway replicas roll. A read + // that fails that way says nothing about the sandbox, so the wait must poll + // again within the same budget instead of failing the exec. + let server = run_server().await; + { + // The name read sees Provisioning, so the wait polls at least once. + let mut script = server.openshell.state.get_sandbox_script.lock().await; + script.push_back(GetSandboxOutcome::Phase(SandboxPhase::Provisioning)); + } + { + let mut failures = server.openshell.state.get_sandbox_failures.lock().await; + failures.push_back(Status::unavailable("no healthy upstream")); + } + { + let mut outcomes = server.openshell.state.exec_outcomes.lock().await; + outcomes.push_back(ExecOutcome::Exit(0)); + } + + let output = run_cli_sandbox_exec(&server, &["--exec-wait-timeout", "10"]).await; + assert!( + output.status.success(), + "a transient readiness read must not fail the exec: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + server.openshell.state.exec_requests.lock().await.len(), + 1, + "the exec must still be issued exactly once" + ); +} + +#[tokio::test] +async fn sandbox_exec_wait_timeout_names_the_budget_and_the_last_waitable_phase() { + // A sandbox stuck in Provisioning past the budget must fail with the wait + // annotation, never with a bare terminal-state message. + let server = run_server().await; + { + let mut phases = server.openshell.state.get_sandbox_phases.lock().await; + for _ in 0..4 { + phases.push_back(SandboxPhase::Provisioning); + } + } + + let output = run_cli_sandbox_exec(&server, &["--exec-wait-timeout", "1"]).await; + assert!( + !output.status.success(), + "a sandbox stuck provisioning must time out" + ); + let stderr = String::from_utf8_lossy(&output.stderr); + let flat = flatten_report(&output.stderr); + assert!(flat.contains("(phase: Provisioning)"), "{stderr}"); + assert!( + flat.contains("(exec wait stopped after ") + && flat.contains("last observed phase: Provisioning)"), + "an exhausted wait must name its budget and last phase: {stderr}" + ); + assert_eq!( + server.openshell.state.exec_requests.lock().await.len(), + 0, + "the exec must never be issued before the sandbox is ready" + ); +} + +#[tokio::test] +async fn sandbox_exec_not_ready_failure_omits_the_wait_suffix_for_a_terminal_phase() { + // A Stopped sandbox cannot reach Ready without a start, so the wait never + // begins and the failure must not claim one ran out. + let server = run_server().await; + { + let mut phases = server.openshell.state.get_sandbox_phases.lock().await; + phases.push_back(SandboxPhase::Stopped); + } + + let output = run_cli_sandbox_exec(&server, &["--exec-wait-timeout", "5"]).await; + assert!(!output.status.success(), "a stopped sandbox must fail fast"); + let stderr = String::from_utf8_lossy(&output.stderr); + let flat = flatten_report(&output.stderr); + assert!(flat.contains("(phase: Stopped)"), "{stderr}"); + assert!( + !flat.contains("exec wait stopped after"), + "a terminal phase never had a wait to exhaust: {stderr}" + ); + assert_eq!( + server.openshell.state.exec_requests.lock().await.len(), + 0, + "the exec must never be issued to a terminal sandbox" + ); +} + #[tokio::test] async fn sandbox_create_retry_progress_goes_to_stderr() { let server = run_server().await; diff --git a/crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs b/crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs index 657ee8e12c..1a2753d7c7 100644 --- a/crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs +++ b/crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs @@ -12,6 +12,7 @@ use std::time::Duration; use helpers::{build_ca, build_client_cert, build_server_cert}; use openshell_core::proto::{self, exec_sandbox_event, exec_sandbox_input}; +use openshell_core::replica_routing::{OWNER_REPLICA_HEADER, ROUTE_REPLICA_HEADER}; use openshell_server::test_support::grpc::open_shell_server::{OpenShell, OpenShellServer}; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::net::TcpListener; @@ -33,12 +34,19 @@ enum Scenario { EarlyExit, ErrorAfterExit, ErrorAfterInput, + /// The gateway's readiness gate rejects the first interactive attempt, + /// then the edge proxy answers the routed resend as unavailable. + ReadinessThenRoutedUnavailable, + /// The rewait's entry read meets a transient unavailable, then the routed + /// resend succeeds. + RewaitTransientLookup, } #[derive(Default)] struct Calls { lookups: usize, unary: usize, + interactive: usize, starts: Vec, input_bytes: usize, } @@ -93,6 +101,10 @@ impl MockGateway { } return; } + Scenario::ReadinessThenRoutedUnavailable | Scenario::RewaitTransientLookup => { + let _ = output.send(Ok(exit(0))).await; + return; + } Scenario::Echo | Scenario::ErrorAfterInput => {} } @@ -158,8 +170,17 @@ impl OpenShell for MockGateway { &self, _: Request, ) -> Result, Status> { - self.calls.lock().unwrap().lookups += 1; - Ok(Response::new(proto::SandboxResponse { + let lookup = { + let mut calls = self.calls.lock().unwrap(); + calls.lookups += 1; + calls.lookups + }; + if matches!(self.scenario, Scenario::RewaitTransientLookup) && lookup == 2 { + // The edge proxy answers `unavailable` while gateway replicas + // roll, which is exactly when the rewait re-reads the sandbox. + return Err(Status::unavailable("no healthy upstream")); + } + let mut response = Response::new(proto::SandboxResponse { sandbox: Some(proto::Sandbox { metadata: Some(proto::datamodel::v1::ObjectMeta { id: "test-id".to_string(), @@ -174,7 +195,12 @@ impl OpenShell for MockGateway { ..Default::default() }), ..Default::default() - })) + }); + response.metadata_mut().insert( + OWNER_REPLICA_HEADER, + tonic::metadata::AsciiMetadataValue::from_static("gateway-test"), + ); + Ok(response) } async fn exec_sandbox( @@ -189,6 +215,35 @@ impl OpenShell for MockGateway { &self, request: Request>, ) -> Result, Status> { + let routed = request.metadata().contains_key(ROUTE_REPLICA_HEADER); + if matches!( + self.scenario, + Scenario::ReadinessThenRoutedUnavailable | Scenario::RewaitTransientLookup + ) { + let attempt = { + let mut calls = self.calls.lock().unwrap(); + calls.interactive += 1; + calls.interactive + }; + match (self.scenario, attempt) { + (_, 1) => { + assert!(routed, "the first attempt targets the owner"); + // The gateway's readiness gate, before any relay opens. + return Err(Status::failed_precondition("sandbox is not ready")); + } + (Scenario::ReadinessThenRoutedUnavailable, 2) => { + assert!(routed, "the resend targets the owner the rewait re-learned"); + return Err(Status::unavailable("no healthy upstream")); + } + (Scenario::ReadinessThenRoutedUnavailable, 3) => { + assert!(!routed, "the fallback must retry without routing"); + } + (Scenario::RewaitTransientLookup, 2) => { + assert!(routed, "the resend targets the owner the rewait re-learned"); + } + _ => panic!("unexpected interactive attempt {attempt}"), + } + } let (sender, receiver) = mpsc::channel(1); let service = self.clone(); tokio::spawn(async move { @@ -273,6 +328,9 @@ impl TestGateway { "exec", "--name", "test-sandbox", + // Opt into the readiness wait the retry scenarios exercise. + "--exec-wait-timeout", + "30", ]); command .args(["--no-tty", "--no-login-shell", "--", "test-command"]) @@ -442,3 +500,51 @@ async fn default_open_pipe_overflow_warns_after_forwarding_prefix() { gateway.assert_one_stream(); assert!(gateway.calls.lock().unwrap().input_bytes <= STDIN_LIMIT); } + +/// Run an exec whose collected stdin forces the interactive streaming path, +/// then closes so the request is replayable. +async fn run_large_pipe_exec(gateway: &TestGateway) -> Output { + let input_path = gateway.config.path().join("stdin"); + std::fs::write(&input_path, vec![b'x'; 1024 * 1024]).unwrap(); + let child = gateway + .command() + .stdin(Stdio::from(std::fs::File::open(input_path).unwrap())) + .spawn() + .unwrap(); + finish(child).await +} + +/// The interactive resend after a readiness-gate rejection has the same +/// unrouted fallback as the first attempt: the edge proxy can answer the +/// re-learned owner with `unavailable` while replicas roll, and no gateway +/// received the command, so replaying the start message is safe. +#[tokio::test] +async fn interactive_resend_retries_unrouted_after_readiness_rejection() { + let gateway = TestGateway::start(Scenario::ReadinessThenRoutedUnavailable).await; + let output = run_large_pipe_exec(&gateway).await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let calls = gateway.calls.lock().unwrap(); + assert_eq!(calls.interactive, 3, "the resend must fall back unrouted"); + assert_eq!(calls.starts.len(), 1, "a command must not be relaunched"); +} + +/// The rewait's entry read tolerates the edge proxy's transient `unavailable` +/// the way the main wait loop does, instead of failing the exec. +#[tokio::test] +async fn rewait_entry_read_tolerates_unavailable() { + let gateway = TestGateway::start(Scenario::RewaitTransientLookup).await; + let output = run_large_pipe_exec(&gateway).await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let calls = gateway.calls.lock().unwrap(); + assert_eq!(calls.lookups, 3, "the rewait must retry the transient read"); + assert_eq!(calls.interactive, 2); + assert_eq!(calls.starts.len(), 1, "a command must not be relaunched"); +} diff --git a/crates/openshell-core/src/create_retry.rs b/crates/openshell-core/src/create_retry.rs index 344019799f..cc6d348876 100644 --- a/crates/openshell-core/src/create_retry.rs +++ b/crates/openshell-core/src/create_retry.rs @@ -234,13 +234,17 @@ fn retry_delay_floor(server_delay: Option) -> Duration { /// /// A server-supplied delay is a minimum the client promised to honor, so a /// delay above the ceiling stays binding instead of being silently shortened. -fn backoff_floor(base: Duration, step: u32, cap: Duration) -> Duration { +/// Shared with [`crate::exec_wait`] so both client waits back off the same way. +pub(crate) fn backoff_floor(base: Duration, step: u32, cap: Duration) -> Duration { let factor = 1_u32 << step.min(31); base.saturating_mul(factor).min(cap.max(base)) } /// Jitter for one attempt, proportional to the delay: at most half of it. -fn jitter(seed: u64, attempt: u32, delay: Duration) -> Duration { +/// +/// Shared with [`crate::exec_wait`] so concurrent clients spread their polls +/// and retries the same way. +pub(crate) fn jitter(seed: u64, attempt: u32, delay: Duration) -> Duration { let bound = delay / 2; let bound_nanos = u64::try_from(bound.as_nanos()).unwrap_or(u64::MAX); if bound_nanos == 0 { @@ -250,7 +254,7 @@ fn jitter(seed: u64, attempt: u32, delay: Duration) -> Duration { } /// `SplitMix64` finalizer: deterministic mixing without a dependency. -fn mix(mut value: u64) -> u64 { +pub(crate) fn mix(mut value: u64) -> u64 { value = value.wrapping_add(0x9E37_79B9_7F4A_7C15); value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); diff --git a/crates/openshell-core/src/exec_wait.rs b/crates/openshell-core/src/exec_wait.rs new file mode 100644 index 0000000000..51ac3b94cd --- /dev/null +++ b/crates/openshell-core/src/exec_wait.rs @@ -0,0 +1,277 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Wait policy for `sandbox exec` while its sandbox is not ready yet. +//! +//! When a shared supervisor dies or its pool rolls, the gateway hands the +//! sandbox's supervisor session to another member, and the sandbox reads +//! `Provisioning` (or `Starting`) for the ten to twenty seconds of the +//! takeover. An exec that gives up on its first observation turns that window +//! into an instant `sandbox is not ready` failure, so the CLI polls +//! `GetSandbox` and waits, within a bounded wall-clock budget, for the sandbox +//! to come back before it starts anything. +//! +//! The module is pure: it takes one decoded observation and returns a +//! decision. Clock, sleeping, transport, and jitter seeds stay with the caller, +//! matching [`crate::create_retry`]. +//! +//! Only the takeover window is waitable. `Provisioning` and `Starting` can +//! reach `Ready` on their own; every other phase stops the wait with the +//! failure exec already returned, because it cannot reach `Ready` without +//! another lifecycle request: `Suspended` and `Suspending` need a resume, +//! `Stopped` needs a start, and `Completed`, `Error`, `Stopping`, `Deleting`, +//! and `Unknown` are terminal for an exec, while `Unspecified` is no +//! observation at all. This taxonomy deliberately differs from +//! `lifecycle_phase_blocks_target` in the CLI: `Stopped` blocks nothing when +//! `sandbox start` waits for `Ready`, but for exec it fails fast, and a wait on +//! a `Suspended` or `Stopping` sandbox could only burn the caller's budget. +//! +//! The wait is bounded by its wall-clock budget alone, with no attempt cap. +//! [`crate::create_retry::MAX_CREATE_ATTEMPTS`] exists because every create +//! attempt re-enters the gateway's mutation-lock wait, which holds a shared +//! connection for its whole budget; an exec-wait attempt is a cheap +//! `GetSandbox` read, so a cap could only truncate the budget the caller +//! advertised. +//! +//! The SDK's `OpenShellClient::wait_ready` classifies phases differently: +//! `Completed` is success there and a failure for exec, and `Suspending` and +//! `Suspended` are its errors. The CLI's exec path drives the raw gRPC client +//! rather than the SDK client, so the SDK keeps its behavior for now; a later +//! SDK opt-in should be expressed through this same policy so the two +//! classifications converge instead of forking a third. + +use std::time::Duration; + +use crate::create_retry::{backoff_floor, jitter}; +use crate::proto::SandboxPhase; + +/// Floor of the readiness poll interval. +pub const MIN_EXEC_WAIT_POLL: Duration = Duration::from_secs(1); + +/// Ceiling of the readiness poll interval before jitter. +pub const MAX_EXEC_WAIT_POLL: Duration = Duration::from_secs(5); + +/// Decision for the next `sandbox exec` readiness poll. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExecWaitPlan { + /// Sleep for the given duration, then observe the phase again. + Sleep(Duration), + /// The sandbox is ready; issue the exec. + Proceed, + /// The sandbox cannot reach `Ready` on its own, or the budget is spent; + /// fail the way exec already did. + Stop, +} + +/// Whether `phase` can reach `Ready` without another lifecycle request. +/// +/// Only a supervisor takeover leaves a sandbox in one of these phases on its +/// way back to `Ready`. A caller uses this to tell "waited but the budget ran +/// out" from "stopped on a phase that never had a wait". +#[must_use] +pub fn exec_wait_is_waitable(phase: SandboxPhase) -> bool { + match phase { + SandboxPhase::Provisioning | SandboxPhase::Starting => true, + SandboxPhase::Unspecified + | SandboxPhase::Ready + | SandboxPhase::Error + | SandboxPhase::Deleting + | SandboxPhase::Unknown + | SandboxPhase::Stopping + | SandboxPhase::Stopped + | SandboxPhase::Completed + | SandboxPhase::Suspending + | SandboxPhase::Suspended => false, + } +} + +/// Plan the next `sandbox exec` readiness poll. +/// +/// `poll_attempt` counts the polls already slept for this exec. A waitable +/// phase sleeps one poll interval: [`MIN_EXEC_WAIT_POLL`] doubling per poll up +/// to [`MAX_EXEC_WAIT_POLL`], plus jitter of at most half the interval so the +/// hundreds of execs a takeover interrupts do not poll the recovering gateway +/// in lockstep. `seed` stretches the jitter; callers derive one per exec call +/// and keep it stable across polls. A sleep that does not fit in +/// `remaining_budget` stops instead of overrunning the caller's deadline. +#[must_use] +pub fn plan_exec_wait( + phase: SandboxPhase, + poll_attempt: u32, + seed: u64, + remaining_budget: Duration, +) -> ExecWaitPlan { + if phase == SandboxPhase::Ready { + return ExecWaitPlan::Proceed; + } + if !exec_wait_is_waitable(phase) { + return ExecWaitPlan::Stop; + } + let sleep = exec_wait_poll_delay(poll_attempt, seed); + if sleep <= remaining_budget { + ExecWaitPlan::Sleep(sleep) + } else { + ExecWaitPlan::Stop + } +} + +/// Delay before the next readiness poll. +/// +/// Shares the retry policy's backoff and jitter so both client loops spread a +/// recovering gateway's load the same way. +#[must_use] +pub fn exec_wait_poll_delay(poll_attempt: u32, seed: u64) -> Duration { + let delay = backoff_floor(MIN_EXEC_WAIT_POLL, poll_attempt, MAX_EXEC_WAIT_POLL); + delay.saturating_add(jitter(seed, poll_attempt, delay)) +} + +/// Suffix appended to an exec failure that ended the readiness wait. +/// +/// Names the wait's elapsed wall-clock time and the last observed phase, so a +/// timeout is never read as a terminal sandbox state. The CLI appends it only +/// when the sandbox was waitable and a wait was configured. +#[must_use] +pub fn exec_wait_stopped_suffix(waited: Duration, last_phase: &str) -> String { + format!( + " (exec wait stopped after {}s; last observed phase: {last_phase})", + waited.as_secs() + ) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + + use super::*; + + fn sleep_of(plan: ExecWaitPlan) -> Duration { + match plan { + ExecWaitPlan::Sleep(sleep) => sleep, + other => panic!("expected a poll sleep, got {other:?}"), + } + } + + #[test] + fn ready_proceeds_without_waiting() { + assert_eq!( + plan_exec_wait(SandboxPhase::Ready, 0, 7, Duration::from_mins(1)), + ExecWaitPlan::Proceed + ); + } + + #[test] + fn provisioning_and_starting_wait() { + for phase in [SandboxPhase::Provisioning, SandboxPhase::Starting] { + let sleep = sleep_of(plan_exec_wait(phase, 0, 7, Duration::from_mins(1))); + assert!( + sleep >= MIN_EXEC_WAIT_POLL, + "{phase:?}: {sleep:?} is below the poll floor" + ); + assert!( + sleep <= MIN_EXEC_WAIT_POLL + MIN_EXEC_WAIT_POLL / 2, + "{phase:?}: {sleep:?} exceeds the jitter bound of the poll floor" + ); + assert!(exec_wait_is_waitable(phase)); + } + } + + #[test] + fn every_other_phase_stops_immediately() { + // Exhaustive over the proto enum: a new phase must be decided here + // rather than silently inherit a wait or a failure. + for phase in [ + SandboxPhase::Unspecified, + SandboxPhase::Unknown, + SandboxPhase::Error, + SandboxPhase::Stopping, + SandboxPhase::Stopped, + SandboxPhase::Deleting, + SandboxPhase::Completed, + SandboxPhase::Suspending, + SandboxPhase::Suspended, + ] { + assert_eq!( + plan_exec_wait(phase, 0, 7, Duration::from_mins(1)), + ExecWaitPlan::Stop, + "{phase:?} cannot reach Ready on its own" + ); + assert!(!exec_wait_is_waitable(phase), "{phase:?}"); + } + } + + #[test] + fn poll_delay_backs_off_to_the_cap_and_stays_jittered() { + for (poll_attempt, floor) in [ + (0, Duration::from_secs(1)), + (1, Duration::from_secs(2)), + (2, Duration::from_secs(4)), + (3, MAX_EXEC_WAIT_POLL), + (8, MAX_EXEC_WAIT_POLL), + ] { + let sleep = sleep_of(plan_exec_wait( + SandboxPhase::Provisioning, + poll_attempt, + 7, + Duration::from_mins(1), + )); + assert!( + sleep >= floor, + "poll {poll_attempt}: {sleep:?} is below the {floor:?} floor" + ); + assert!( + sleep <= floor + floor / 2, + "poll {poll_attempt}: {sleep:?} exceeds the jitter bound of {floor:?}" + ); + } + } + + #[test] + fn distinct_seeds_decorrelate_the_poll() { + let polls: BTreeSet = (0..64) + .map(|seed| { + sleep_of(plan_exec_wait( + SandboxPhase::Provisioning, + 0, + seed, + Duration::from_mins(1), + )) + }) + .collect(); + assert!( + polls.len() > 1, + "every seed produced the same poll: {polls:?}" + ); + } + + #[test] + fn a_poll_that_does_not_fit_the_budget_stops() { + assert_eq!( + plan_exec_wait(SandboxPhase::Provisioning, 0, 7, Duration::ZERO), + ExecWaitPlan::Stop, + "a zero budget cannot cover the poll floor" + ); + let sleep = sleep_of(plan_exec_wait( + SandboxPhase::Provisioning, + 0, + 7, + Duration::from_mins(1), + )); + assert_eq!( + plan_exec_wait(SandboxPhase::Provisioning, 0, 7, sleep), + ExecWaitPlan::Sleep(sleep) + ); + let just_short = sleep.checked_sub(Duration::from_nanos(1)).unwrap(); + assert_eq!( + plan_exec_wait(SandboxPhase::Provisioning, 0, 7, just_short), + ExecWaitPlan::Stop + ); + } + + #[test] + fn stopped_suffix_names_the_budget_and_the_phase() { + assert_eq!( + exec_wait_stopped_suffix(Duration::from_secs(45), "Provisioning"), + " (exec wait stopped after 45s; last observed phase: Provisioning)" + ); + } +} diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index ee524f84d7..27c86eebc2 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -28,6 +28,7 @@ pub mod endpoint_failure; pub mod endpoint_path; pub mod endpoint_status; pub mod error; +pub mod exec_wait; pub mod extension_protocol; #[cfg(unix)] pub mod external_driver_socket; diff --git a/crates/openshell-core/src/rpc_error.rs b/crates/openshell-core/src/rpc_error.rs index 5c4b2ab602..6892b292d4 100644 --- a/crates/openshell-core/src/rpc_error.rs +++ b/crates/openshell-core/src/rpc_error.rs @@ -19,6 +19,9 @@ pub const ERROR_DOMAIN: &str = "openshell.nvidia.com"; /// Reason reported when a request lost the mutation lock budget. pub const MUTATION_LOCK_TIMEOUT: &str = "MUTATION_LOCK_TIMEOUT"; +/// Reason reported when the sandbox is not ready to start the requested work. +pub const SANDBOX_NOT_READY: &str = "SANDBOX_NOT_READY"; + /// Decode supported details without trusting inconsistent envelopes or delays. /// Unknown and malformed details remain available on the original status. pub fn decode_details(status: &Status) -> Option { diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 7caff43df4..12170fe306 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -280,7 +280,12 @@ pub(super) async fn resolve_and_authorize_sandbox_name( fn require_ready_sandbox(sandbox: &Sandbox) -> Result<(), Status> { match SandboxPhase::try_from(sandbox.phase()).ok() { Some(SandboxPhase::Ready) => Ok(()), - _ => Err(Status::failed_precondition("sandbox is not ready")), + // The CLI re-waits on this rejection, so attach the machine-readable + // reason clients match on instead of relying on the prose. + _ => Err(openshell_core::rpc_error::failed_precondition( + openshell_core::rpc_error::SANDBOX_NOT_READY, + "sandbox is not ready", + )), } } @@ -4382,6 +4387,24 @@ mod tests { assert!(exec_loop_result(Some(0), false).is_err()); assert!(exec_loop_result(None, true).is_err()); } + + #[test] + fn exec_readiness_rejection_carries_the_structured_reason() { + let mut ready = Sandbox::default(); + ready.set_phase(SandboxPhase::Ready as i32); + require_ready_sandbox(&ready).expect("a Ready sandbox is executable"); + + let mut provisioning = Sandbox::default(); + provisioning.set_phase(SandboxPhase::Provisioning as i32); + let status = require_ready_sandbox(&provisioning).expect_err("Provisioning is not Ready"); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); + assert_eq!(status.message(), "sandbox is not ready"); + let details = + openshell_core::rpc_error::decode_details(&status).expect("structured error details"); + let info = details.error_info().expect("error reason"); + assert_eq!(info.reason, openshell_core::rpc_error::SANDBOX_NOT_READY); + assert_eq!(info.domain, openshell_core::rpc_error::ERROR_DOMAIN); + } use crate::grpc::test_support::{ authed_request, test_server_state, test_server_state_with_compute_driver, test_server_state_with_driver, diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 169a131821..90b6a276a6 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -373,6 +373,8 @@ OpenShell allocates a TTY automatically when both stdin and stdout are terminals | `--no-tty` | Disable TTY allocation even when attached to a terminal. | | `--no-login-shell`| Run the command without sourcing shell login startup files. | | `--env` | Set an environment variable for the command (`KEY=VALUE`, repeatable). | +| `--exec-wait-timeout` | Seconds to wait for the sandbox to become `Ready` before running the command (default: 45, or `OPENSHELL_EXEC_WAIT_TIMEOUT`). `0` disables the wait. | +| `--no-exec-wait` | Fail immediately when the sandbox is not `Ready`. | ### Skip shell startup files @@ -1194,6 +1196,8 @@ Image preparation and initial supervisor startup have an absolute deadline of 18 `sandbox create` retries when the gateway reports that the create lost the mutation lock, for 60 seconds by default. Set the budget with `--create-retry-timeout ` or `OPENSHELL_CREATE_RETRY_TIMEOUT` (both clamped to 24 hours), or pass `--no-create-retry` to fail on the first busy reply. Retry progress goes to stderr. +`sandbox exec` likewise waits before running the command when the sandbox is `Provisioning` or `Starting`, such as while a supervisor takeover finishes, for 45 seconds by default. Set the budget with `--exec-wait-timeout ` or `OPENSHELL_EXEC_WAIT_TIMEOUT` (both clamped to 24 hours; `0` disables the wait), or pass `--no-exec-wait`. Every other phase still fails immediately. + The first authenticated configuration report from the current supervisor ends preparation and starts a separate admission repair window (300 seconds by default). A slow image download therefore does not consume time reserved for fixing policy. During admission, an effective policy, settings, provider, profile, or attachment change resets the window from its stored change time. The first failed configuration load for that change grants another full window. Repeated failures, duplicate reports, and reconnects do not extend it; reaching `Ready` clears it. Preparation expiry sets the sandbox to `Error` with reason `ImagePreparationTimedOut`; admission repair expiry uses `ProvisioningTimedOut`. The gateway stops its workload and supervisor compute, retaining the sandbox record, diagnostic, and restartable storage. Cleanup can remain pending if the backend is unavailable; the gateway retries it. Inspect `provisioning` in JSON output for the active `phase`, `deadline`, original `preparation_deadline`, `admission_start_time`, and cleanup timestamps. TUI NOTES identifies preparation timeout and distinguishes pending cleanup from reclaimed compute. diff --git a/e2e/rust/src/harness/binary.rs b/e2e/rust/src/harness/binary.rs index cd853906b9..b3a23de0f7 100644 --- a/e2e/rust/src/harness/binary.rs +++ b/e2e/rust/src/harness/binary.rs @@ -46,9 +46,16 @@ pub fn openshell_bin() -> PathBuf { /// /// The command has `kill_on_drop(true)` set so that background child processes /// are cleaned up when the handle is dropped. +/// +/// It also pins `OPENSHELL_EXEC_WAIT_TIMEOUT=0`, so every harness-spawned CLI +/// keeps the pre-wait instant `sandbox exec` failure unless a call site opts in +/// with an explicit `--exec-wait-timeout` (the flag wins over the environment). +/// Otherwise the CLI's default-on bounded wait would re-time suites that probe +/// exec during churn. pub fn openshell_cmd() -> tokio::process::Command { let mut cmd = tokio::process::Command::new(openshell_bin()); cmd.kill_on_drop(true); + cmd.env("OPENSHELL_EXEC_WAIT_TIMEOUT", "0"); cmd } diff --git a/e2e/rust/src/harness/sandbox.rs b/e2e/rust/src/harness/sandbox.rs index 9d14092cb2..38a6571abf 100644 --- a/e2e/rust/src/harness/sandbox.rs +++ b/e2e/rust/src/harness/sandbox.rs @@ -482,6 +482,11 @@ impl SandboxGuard { /// Stdout and stderr are captured and returned together; PTY allocation /// is disabled so the call is suitable for non-interactive setups. /// + /// The readiness wait is pinned to today's instant failure with + /// `--no-exec-wait`: the CLI's default-on bounded wait would otherwise + /// re-time every suite that probes exec during churn. Use + /// [`SandboxGuard::exec_with_wait_timeout`] to opt in. + /// /// # Arguments /// /// * `argv` — Command and arguments to execute (passed after `--`). @@ -490,13 +495,44 @@ impl SandboxGuard { /// /// Returns an error if the CLI exits non-zero. pub async fn exec(&self, argv: &[&str]) -> Result { + self.exec_with_wait_timeout(argv, None).await + } + + /// Run a one-shot command, opting into the CLI's bounded readiness wait. + /// + /// `wait_timeout_secs` is `sandbox exec --exec-wait-timeout`'s budget, so + /// the probe waits for a supervisor takeover to finish instead of failing + /// on a sandbox that is momentarily `Provisioning` or `Starting`. `None` + /// keeps `--no-exec-wait`, today's instant failure. + /// + /// # Arguments + /// + /// * `argv` — Command and arguments to execute (passed after `--`). + /// * `wait_timeout_secs` — Readiness-wait budget in seconds. + /// + /// # Errors + /// + /// Returns an error if the CLI exits non-zero. + pub async fn exec_with_wait_timeout( + &self, + argv: &[&str], + wait_timeout_secs: Option, + ) -> Result { let mut cmd = openshell_cmd(); cmd.arg("sandbox") .arg("exec") .arg("--name") .arg(&self.name) - .arg("--no-tty") - .arg("--"); + .arg("--no-tty"); + match wait_timeout_secs { + Some(secs) => { + cmd.arg("--exec-wait-timeout").arg(secs.to_string()); + } + None => { + cmd.arg("--no-exec-wait"); + } + } + cmd.arg("--"); for arg in argv { cmd.arg(arg); } diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_ha.rs b/e2e/rust/tests/kubernetes_shared_supervisor_ha.rs index 5ab9255062..8c32f4e767 100644 --- a/e2e/rust/tests/kubernetes_shared_supervisor_ha.rs +++ b/e2e/rust/tests/kubernetes_shared_supervisor_ha.rs @@ -25,12 +25,15 @@ mod shared_supervisor; use std::process::Stdio; use std::time::Duration; +use openshell_e2e::harness::cli::run_cli; +use openshell_e2e::harness::output::strip_ansi; use openshell_e2e::harness::sandbox::SandboxGuard; use shared_supervisor::{ - EXEC_PROBE_TIMEOUT, GATEWAY_SELECTOR, HostEndpoint, SUPERVISOR_CONTAINER, call_host, - counts_past, create, gateway_log_lines, generation, is_takeover, kill_abruptly, kubectl, - kubectl_command, main_process, owner_of, policy, release_namespace, supervisor_pods, - wait_for_owner, wait_until_attached, + EXEC_PROBE_TIMEOUT, GATEWAY_SELECTOR, HostEndpoint, MainProcess, ProbeOptions, + SUPERVISOR_CONTAINER, SampleBounds, Samples, call_host, check_samples, counts_past, create, + gateway_log_lines, generation, is_takeover, kill_abruptly, kubectl, kubectl_command, + kubectl_json, main_process, owner_of, policy, release_namespace, supervisor_pods, + wait_for_owner, wait_until_attached, while_probing, }; use tokio::io::AsyncBufReadExt as _; @@ -49,6 +52,107 @@ const PLACEMENT_ATTEMPTS: usize = 32; const EXPIRY_EVIDENCE: Duration = Duration::from_secs(10); /// What a supervisor logs as it begins to leave the pool. const LEAVING: &str = "pool member is leaving"; +/// The readiness-wait budget these regression scenarios opt into: the CLI's +/// 45-second default, enough for the ten- to twenty-second takeover with +/// headroom. +const EXEC_WAIT_SECS: u32 = 45; +/// Bound on one waited exec probe: [`EXEC_WAIT_SECS`] plus 30 seconds of +/// margin for process startup and the command. +const EXEC_WAIT_PROBE_TIMEOUT: Duration = Duration::from_secs(75); +/// Interval between probes of a sandbox during the churn window. +const CHURN_PROBE_INTERVAL: Duration = Duration::from_secs(2); +/// Probing continues this long after the transition returned. +const CHURN_SETTLE: Duration = Duration::from_secs(15); +/// Exec failures a genuine Ready-read/exec race may still cost the fixed CLI. +/// The pre-fix CLI fails every probe in the takeover window, so the abrupt-kill +/// scenario fails this assertion there. +const EXEC_RACE_ALLOWANCE: usize = 2; +/// Bound on a sandbox recovering from a supervisor Deployment rollout: both +/// members restart, so each sandbox waits for a fresh session plus the wait +/// budget. Size it from the lane's observed recovery, not from the budget +/// alone. +const ROLLOUT_RECOVERY_DEADLINE: Duration = Duration::from_mins(4); + +/// How these regression scenarios probe: exec only, opting into the CLI's +/// readiness wait so a takeover is waited out instead of failing instantly. +fn takeover_probe_options() -> ProbeOptions { + ProbeOptions { + interval: CHURN_PROBE_INTERVAL, + port: None, + exec_wait_timeout_secs: Some(EXEC_WAIT_SECS), + exec_probe_timeout: EXEC_WAIT_PROBE_TIMEOUT, + } +} + +/// Bounds for one sandbox that recovered from the churn. +fn takeover_bounds(recovery: Duration) -> SampleBounds { + SampleBounds { + exec_outage: recovery, + network_outage: recovery, + exec_failure_allowance: Some(EXEC_RACE_ALLOWANCE), + exec_probe: Some(EXEC_WAIT_PROBE_TIMEOUT), + } +} + +/// Poll a non-waiting exec probe until it succeeds, or return the last failure +/// once `deadline` passes. +async fn wait_for_exec(sandbox: &SandboxGuard, deadline: Duration) -> Result { + let mut last = String::from("exec never ran"); + tokio::time::timeout(deadline, async { + loop { + match main_process(sandbox).await { + Ok(current) => return current, + Err(error) => last = error, + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + }) + .await + .map_err(|_| last) +} + +/// The sandbox's phase as the CLI's structured output reports it, retried +/// briefly so a gateway read during churn does not decide the verdict. +async fn sandbox_phase(sandbox: &SandboxGuard) -> Option { + for _ in 0..5 { + let (output, code) = run_cli(&["sandbox", "get", &sandbox.name, "--output", "json"]).await; + if code == 0 + && let Some(phase) = serde_json::from_str::(&strip_ansi(&output)) + .ok() + .and_then(|value| { + value + .get("phase") + .and_then(|phase| phase.as_str()) + .map(ToOwned::to_owned) + }) + { + return Some(phase); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + None +} + +/// Whether the sandbox ended up `Stopped`, read from its structured phase +/// rather than from CLI error prose, whose wording can drift. +/// +/// A rolling restart can leave a pool sandbox `Stopped`, which is a separate, +/// unconfirmed failure tracked under the issue's AC (c): the scenario reports +/// it loudly from `stopped_sandbox_verdict` instead of failing on it. +async fn left_stopped(sandbox: &SandboxGuard) -> bool { + sandbox_phase(sandbox).await.as_deref() == Some("Stopped") +} + +/// Report a rollout sandbox that never came back because it was left `Stopped`. +fn stopped_sandbox_verdict(sandbox: &SandboxGuard, samples: &Samples) { + eprintln!( + "KNOWN FAILURE (AC (c) of #5659, not this test): {} was left Stopped by the rollout; \ + {} exec probes failed: {:?}", + sandbox.name, + samples.exec_failures.len(), + samples.exec_failures + ); +} /// Lines a supervisor Pod logs from its start until its container ends. struct FollowedLogs { @@ -522,15 +626,14 @@ async fn gateway_workload() -> String { } async fn rollout(action: &str, workload: &str) { - kubectl(&[ - "-n", - &release_namespace(), - "rollout", - action, - workload, - "--timeout=300s", - ]) - .await; + let namespace = release_namespace(); + // `rollout status` waits for the rollout with --timeout; `rollout + // restart` only records the restart and rejects the flag. + let mut args = vec!["-n", &namespace, "rollout", action, workload]; + if action == "status" { + args.push("--timeout=300s"); + } + kubectl(&args).await; } async fn force_delete(pod: &str) { @@ -686,3 +789,190 @@ async fn pool_sessions_follow_their_supervisors_gateway() { forward.ensure().await; drop(sandboxes); } + +/// Exec keeps working across an abrupt supervisor kill, and the CLI waits out +/// the takeover instead of failing on the first `Provisioning` read. +/// +/// The discriminating assertion is the failure count: on the pre-fix CLI every +/// probe in the takeover window fails, far above the race allowance, while on +/// the fixed CLI a probe started before the recovery waits for it and succeeds. +#[tokio::test] +#[allow(clippy::too_many_lines)] +async fn exec_survives_an_abrupt_supervisor_kill() { + let members = supervisor_pods().await; + assert!( + members.len() >= 2, + "the supervisor pool needs at least two running members: {members:?}" + ); + wait_until_attached(&members).await; + let endpoint = HostEndpoint::start().await; + let policy = policy(endpoint.port); + + let mut sandbox = create(&policy).await; + let generation_before = generation(&sandbox.name).await; + let owner_before = wait_for_owner(&generation_before.route).await; + let baseline = main_process(&sandbox) + .await + .expect("main process before the kill"); + + let (moved_after, samples) = while_probing( + &[(&sandbox, baseline.clone())], + takeover_probe_options(), + CHURN_SETTLE, + async { + let killed_at = tokio::time::Instant::now(); + let killed = kill_abruptly(&owner_before).await; + eprintln!("supervisor {owner_before} killed: {killed}"); + // The churn window ends when another member admits the route; the + // probes keep running through it and through the settle period. + tokio::time::timeout(RECOVERY_DEADLINE, async { + loop { + if owner_of(&generation_before.route) + .await + .is_some_and(|owner| owner != owner_before) + { + return killed_at.elapsed(); + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + }) + .await + .unwrap_or_else(|_| { + panic!( + "no other member admitted {} within {RECOVERY_DEADLINE:?}", + sandbox.name + ) + }) + }, + ) + .await; + + check_samples( + "abrupt supervisor kill", + &sandbox, + &samples[0], + takeover_bounds(RECOVERY_DEADLINE), + ); + + // Exec answers again after settle, on the same adopted process. + let after = wait_for_exec(&sandbox, RECOVERY_DEADLINE) + .await + .unwrap_or_else(|last| { + panic!( + "{} never answered exec again after the kill: {last}", + sandbox.name + ) + }); + assert_eq!( + (after.pid, after.start_ticks), + (baseline.pid, baseline.start_ticks), + "the main process was restarted, not adopted" + ); + assert_eq!( + generation(&sandbox.name).await, + generation_before, + "the workload Pod or runtime generation changed" + ); + let new_owner = wait_for_owner(&generation_before.route).await; + assert_ne!(new_owner, owner_before, "the lost Pod cannot own the route"); + eprintln!( + "{} moved to {new_owner} {moved_after:?} after the kill and answers exec", + sandbox.name + ); + + sandbox.cleanup().await; +} + +/// Exec keeps working across a rollout restart of the supervisor Deployment. +/// +/// The per-sandbox verdict sizes recovery from observed behavior: a sandbox +/// that comes back within the bound must satisfy the exec assertions, while one +/// the rollout leaves `Stopped` is reported as the known AC (c) failure and +/// counted separately instead of failing this test. +#[tokio::test] +#[allow(clippy::too_many_lines)] +async fn exec_survives_a_supervisor_rollout_restart() { + let members = supervisor_pods().await; + assert!( + members.len() >= 2, + "the supervisor pool needs at least two running members: {members:?}" + ); + wait_until_attached(&members).await; + let supervisor = format!("deployment.apps/{}-supervisor", release()); + let endpoint = HostEndpoint::start().await; + let policy = policy(endpoint.port); + + // Two sandboxes so the per-sandbox verdict can come out differently. + let mut tracked = Vec::new(); + for _ in 0..2 { + let sandbox = create(&policy).await; + let generation_before = generation(&sandbox.name).await; + let baseline = main_process(&sandbox) + .await + .expect("main process before the rollout"); + tracked.push((sandbox, generation_before, baseline)); + } + let probes = tracked + .iter() + .map(|(sandbox, _, baseline)| (sandbox, baseline.clone())) + .collect::>(); + let ((), samples) = while_probing(&probes, takeover_probe_options(), CHURN_SETTLE, async { + rollout("restart", &supervisor).await; + rollout("status", &supervisor).await; + }) + .await; + + let mut recovered = Vec::new(); + let mut stopped = Vec::new(); + for ((mut sandbox, generation_before, baseline), samples) in tracked.into_iter().zip(&samples) { + match wait_for_exec(&sandbox, ROLLOUT_RECOVERY_DEADLINE).await { + Ok(after) => { + assert_eq!( + (after.pid, after.start_ticks), + (baseline.pid, baseline.start_ticks), + "{}'s main process was restarted, not adopted", + sandbox.name + ); + assert_eq!( + generation(&sandbox.name).await, + generation_before, + "{}'s workload Pod or runtime generation changed", + sandbox.name + ); + check_samples( + "supervisor rollout", + &sandbox, + samples, + takeover_bounds(ROLLOUT_RECOVERY_DEADLINE), + ); + recovered.push(sandbox.name.clone()); + } + Err(last) => { + if left_stopped(&sandbox).await { + stopped_sandbox_verdict(&sandbox, samples); + stopped.push(sandbox.name.clone()); + } else { + panic!( + "{} did not answer exec within {ROLLOUT_RECOVERY_DEADLINE:?} after the rollout: {last}; failures: {:?}", + sandbox.name, samples.exec_failures + ); + } + } + } + sandbox.cleanup().await; + } + assert!( + !recovered.is_empty(), + "no sandbox survived the rollout (recovered: {recovered:?}, stopped: {stopped:?})" + ); + assert_eq!( + recovered.len() + stopped.len(), + 2, + "every tracked sandbox must get a verdict (recovered: {recovered:?}, stopped: {stopped:?})" + ); + eprintln!( + "rollout: {} recovered, {} left Stopped (known AC (c) failure)", + recovered.len(), + stopped.len() + ); +} diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_scaling.rs b/e2e/rust/tests/kubernetes_shared_supervisor_scaling.rs index 71223b5125..ae6eb3159f 100644 --- a/e2e/rust/tests/kubernetes_shared_supervisor_scaling.rs +++ b/e2e/rust/tests/kubernetes_shared_supervisor_scaling.rs @@ -28,15 +28,14 @@ use std::collections::BTreeMap; use std::process::Stdio; use std::time::Duration; -use futures_util::future::join_all; use openshell_e2e::harness::sandbox::SandboxGuard; use shared_supervisor::{ - GATEWAY_SELECTOR, HostEndpoint, MainProcess, SUPERVISOR_COMPONENT, TAKEOVER, call_host, - counts_past, create, gateway_log_lines, generation, helm_command, is_takeover, kubectl_json, - main_process, owner_of, policy, release_namespace, supervisor_pod_items, supervisor_pods, - try_call_host, wait_for_owner, wait_until_attached, + EXEC_PROBE_TIMEOUT, GATEWAY_SELECTOR, HostEndpoint, MainProcess, ProbeOptions, + SUPERVISOR_COMPONENT, SampleBounds, TAKEOVER, call_host, check_samples, counts_past, create, + gateway_log_lines, generation, helm_command, is_takeover, kubectl_json, main_process, owner_of, + policy, release_namespace, supervisor_pod_items, supervisor_pods, wait_for_owner, + wait_until_attached, while_probing, }; -use tokio::time::Instant; /// Sandboxes created, at most, until one lands on the new member. The ring /// places each sandbox by its random server-assigned ID, so placements can @@ -261,131 +260,26 @@ async fn scale_pool(replicas: usize) -> BTreeMap { .unwrap_or_else(|_| panic!("the supervisor pool did not settle at {replicas} members")) } -/// What the probes of one sandbox saw during a transition. -#[derive(Debug, Default)] -struct Samples { - exec_ok: usize, - exec_failures: Vec, - network_ok: usize, - network_failures: Vec, - /// Longest time without a successful exec probe. - exec_outage: Duration, - /// Longest time without a successful network probe. - network_outage: Duration, - last: Option, -} - -/// Probe `sandbox` every [`PROBE_INTERVAL`] until `stop`: its main process -/// must stay `baseline`'s and its counter must never go back; record how -/// long exec and the policy-mediated call to the host endpoint fail. -async fn sample( - sandbox: &SandboxGuard, - baseline: &MainProcess, - port: u16, - mut stop: tokio::sync::watch::Receiver, -) -> Samples { - let mut samples = Samples::default(); - let mut last_exec = Instant::now(); - let mut last_network = Instant::now(); - let mut counter = baseline.counter; - loop { - match main_process(sandbox).await { - Ok(current) => { - assert_eq!( - (current.pid, current.start_ticks), - (baseline.pid, baseline.start_ticks), - "{}'s main process was replaced: {baseline:?} then {current:?}", - sandbox.name - ); - assert!( - current.counter >= counter, - "{}'s in-memory counter went back from {counter} to {}", - sandbox.name, - current.counter - ); - counter = current.counter; - samples.exec_outage = samples.exec_outage.max(last_exec.elapsed()); - last_exec = Instant::now(); - samples.exec_ok += 1; - samples.last = Some(current); - } - Err(error) => samples.exec_failures.push(error), - } - match try_call_host(sandbox, port).await { - Ok(result) if result == "HA_OK" => { - samples.network_outage = samples.network_outage.max(last_network.elapsed()); - last_network = Instant::now(); - samples.network_ok += 1; - } - Ok(result) => samples.network_failures.push(result), - Err(error) => samples.network_failures.push(error), - } - if *stop.borrow() { - break; - } - tokio::select! { - () = tokio::time::sleep(PROBE_INTERVAL) => {} - _ = stop.changed() => {} - } +/// How these probes run: exec without a readiness wait (today's instant +/// failure) and one policy-mediated call per round. +fn probe_options(port: u16) -> ProbeOptions { + ProbeOptions { + interval: PROBE_INTERVAL, + port: Some(port), + exec_wait_timeout_secs: None, + exec_probe_timeout: EXEC_PROBE_TIMEOUT, } - samples.exec_outage = samples.exec_outage.max(last_exec.elapsed()); - samples.network_outage = samples.network_outage.max(last_network.elapsed()); - samples -} - -/// Run `transition` while probing every sandbox, and keep probing for -/// [`SETTLE`] after it finished. -async fn while_probing( - sandboxes: &[(&SandboxGuard, MainProcess)], - port: u16, - transition: impl Future, -) -> (T, Vec) { - let (stop, stopped) = tokio::sync::watch::channel(false); - let samplers = join_all( - sandboxes - .iter() - .map(|(sandbox, baseline)| sample(sandbox, baseline, port, stopped.clone())), - ); - let driver = async { - let outcome = transition.await; - tokio::time::sleep(SETTLE).await; - stop.send_replace(true); - outcome - }; - tokio::join!(driver, samplers) } -/// Check what the probes of `sandbox` saw against `bound`. -fn check_samples(phase: &str, sandbox: &SandboxGuard, samples: &Samples, bound: Duration) { - eprintln!( - "{phase}: {} exec {} ok / {} failed (longest outage {:?}), network {} ok / {} failed (longest outage {:?})", - sandbox.name, - samples.exec_ok, - samples.exec_failures.len(), - samples.exec_outage, - samples.network_ok, - samples.network_failures.len(), - samples.network_outage - ); - assert!( - samples.exec_ok > 0 && samples.network_ok > 0, - "{phase}: {} never answered: {samples:?}", - sandbox.name - ); - assert!( - samples.exec_outage <= bound, - "{phase}: exec on {} failed for {:?}, longer than {bound:?}: {:?}", - sandbox.name, - samples.exec_outage, - samples.exec_failures - ); - assert!( - samples.network_outage <= bound, - "{phase}: networking from {} failed for {:?}, longer than {bound:?}: {:?}", - sandbox.name, - samples.network_outage, - samples.network_failures - ); +/// What a staying or moving sandbox must satisfy: only the outage bound +/// differs between the two. +fn sample_bounds(outage: Duration) -> SampleBounds { + SampleBounds { + exec_outage: outage, + network_outage: outage, + exec_failure_allowance: None, + exec_probe: None, + } } /// A sandbox under test and what it must keep. @@ -481,11 +375,17 @@ async fn scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running() { // Phase 2: scale to two members. The new member joins; nothing moves. let (two_members, samples) = while_probing( &[(&a.sandbox, a.baseline.clone())], - endpoint.port, + probe_options(endpoint.port), + SETTLE, scale_pool(2), ) .await; - check_samples("scale up", &a.sandbox, &samples[0], STAYING_OUTAGE); + check_samples( + "scale up", + &a.sandbox, + &samples[0], + sample_bounds(STAYING_OUTAGE), + ); assert_eq!( two_members.get(&first_member), initial.get(&first_member), @@ -550,7 +450,8 @@ async fn scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running() { (&a.sandbox, a.baseline.clone()), (&b.sandbox, b.baseline.clone()), ], - endpoint.port, + probe_options(endpoint.port), + SETTLE, scale_pool(1), ) .await; @@ -591,7 +492,7 @@ async fn scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running() { }, &tracked.sandbox, samples, - if moved { MOVING_OUTAGE } else { STAYING_OUTAGE }, + sample_bounds(if moved { MOVING_OUTAGE } else { STAYING_OUTAGE }), ); } for route in &handed_off { diff --git a/e2e/rust/tests/shared_supervisor/mod.rs b/e2e/rust/tests/shared_supervisor/mod.rs index 45eed8deef..912c9e1822 100644 --- a/e2e/rust/tests/shared_supervisor/mod.rs +++ b/e2e/rust/tests/shared_supervisor/mod.rs @@ -8,9 +8,12 @@ //! Each test binary uses a subset. #![allow(dead_code)] +use std::future::Future; use std::process::Stdio; use std::time::Duration; +use futures_util::future::join_all; +use openshell_e2e::harness::container::ContainerEngine; use openshell_e2e::harness::output::strip_ansi; use openshell_e2e::harness::sandbox::SandboxGuard; use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _}; @@ -60,20 +63,34 @@ pub const NETWORK_PROBE_TIMEOUT: Duration = Duration::from_secs(40); /// Run `command` in a cluster node's container; k3d and kind name node /// containers after their nodes. async fn node_exec(node: &str, command: &[&str]) -> Result { - let output = tokio::process::Command::new("docker") + // kind runs on Docker in CI and on Podman on some dev hosts; resolve the + // engine the same way the rest of the harness does instead of assuming + // Docker, or every node-level kill fails with "No such file or directory". + let engine = ContainerEngine::from_env() + .map_err(|error| format!("container engine for exec into kind node {node}: {error}"))?; + let name = engine.name().to_string(); + let mut process = engine.command(); + // The Kubernetes gateway wrapper scopes XDG_CONFIG_HOME and XDG_DATA_HOME + // to its per-run workdir, which points a rootless Podman at a per-run + // container store. The kind nodes live in the user's real store, so an + // exec into them must drop that scoping; Docker ignores both variables. + process + .env_remove("XDG_CONFIG_HOME") + .env_remove("XDG_DATA_HOME") .arg("exec") .arg(node) .args(command) .stdout(Stdio::piped()) - .stderr(Stdio::piped()) + .stderr(Stdio::piped()); + let output = tokio::process::Command::from(process) .output() .await - .map_err(|error| format!("docker exec {node} {command:?}: {error}"))?; + .map_err(|error| format!("{name} exec {node} {command:?}: {error}"))?; if output.status.success() { Ok(String::from_utf8_lossy(&output.stdout).into_owned()) } else { Err(format!( - "docker exec {node} {command:?}: {}", + "{name} exec {node} {command:?}: {}", String::from_utf8_lossy(&output.stderr).trim() )) } @@ -592,18 +609,35 @@ pub struct MainProcess { /// One bounded exec probe of the main process. pub async fn main_process(sandbox: &SandboxGuard) -> Result { + main_process_with_wait(sandbox, None, EXEC_PROBE_TIMEOUT).await +} + +/// One bounded exec probe of the main process, opting into the CLI's readiness +/// wait. +/// +/// `wait_timeout_secs` is `sandbox exec --exec-wait-timeout`'s budget; `None` +/// keeps today's instant failure. `probe_timeout` bounds the whole CLI call, so +/// it must cover the readiness wait plus the command. +pub async fn main_process_with_wait( + sandbox: &SandboxGuard, + wait_timeout_secs: Option, + probe_timeout: Duration, +) -> Result { let output = tokio::time::timeout( - EXEC_PROBE_TIMEOUT, - sandbox.exec(&[ - "sh", - "-c", - "pid=$(cat /tmp/ha-main.pid) && echo pid=$pid && \ - echo start=$(cut -d')' -f2 /proc/$pid/stat | awk '{print $20}') && \ - echo counter=$(cat /tmp/ha-counter)", - ]), + probe_timeout, + sandbox.exec_with_wait_timeout( + &[ + "sh", + "-c", + "pid=$(cat /tmp/ha-main.pid) && echo pid=$pid && \ + echo start=$(cut -d')' -f2 /proc/$pid/stat | awk '{print $20}') && \ + echo counter=$(cat /tmp/ha-counter)", + ], + wait_timeout_secs, + ), ) .await - .map_err(|_| format!("exec did not finish within {EXEC_PROBE_TIMEOUT:?}"))??; + .map_err(|_| format!("exec did not finish within {probe_timeout:?}"))??; let field = |key: &str| { output .lines() @@ -640,6 +674,211 @@ pub async fn counts_past(sandbox: &SandboxGuard, previous: &MainProcess) -> Main .unwrap_or_else(|_| panic!("{} stopped counting after {previous:?}", sandbox.name)) } +/// How `sample` probes a sandbox. +#[derive(Debug, Clone, Copy)] +pub struct ProbeOptions { + /// Interval between probe rounds. + pub interval: Duration, + /// Host endpoint port for the policy-mediated probe; `None` samples exec + /// only. + pub port: Option, + /// Readiness-wait budget each exec probe opts into. `None` keeps the + /// CLI's instant failure, which is what every suite that probes during + /// churn used before the wait existed. + pub exec_wait_timeout_secs: Option, + /// Bound on one exec probe, covering any readiness wait. + pub exec_probe_timeout: Duration, +} + +/// What the probes of one sandbox saw during a transition. +#[derive(Debug, Default)] +pub struct Samples { + pub exec_ok: usize, + pub exec_failures: Vec, + pub network_ok: usize, + pub network_failures: Vec, + /// Longest time without a successful exec probe. + pub exec_outage: Duration, + /// Longest time without a successful network probe. + pub network_outage: Duration, + /// Longest successful exec probe, readiness wait included. + pub slowest_exec: Duration, + /// Whether the network probe ran at all. + pub network_probed: bool, + pub last: Option, +} + +/// Probe `sandbox` every [`ProbeOptions::interval`] until `stop`: its main +/// process must stay `baseline`'s and its counter must never go back; record +/// how long exec, and the policy-mediated call to the host endpoint when a +/// port is given, fail. +pub async fn sample( + sandbox: &SandboxGuard, + baseline: &MainProcess, + options: ProbeOptions, + mut stop: tokio::sync::watch::Receiver, +) -> Samples { + let mut samples = Samples { + network_probed: options.port.is_some(), + ..Samples::default() + }; + let mut last_exec = tokio::time::Instant::now(); + let mut last_network = tokio::time::Instant::now(); + let mut counter = baseline.counter; + loop { + let started = tokio::time::Instant::now(); + match main_process_with_wait( + sandbox, + options.exec_wait_timeout_secs, + options.exec_probe_timeout, + ) + .await + { + Ok(current) => { + assert_eq!( + (current.pid, current.start_ticks), + (baseline.pid, baseline.start_ticks), + "{}'s main process was replaced: {baseline:?} then {current:?}", + sandbox.name + ); + assert!( + current.counter >= counter, + "{}'s in-memory counter went back from {counter} to {}", + sandbox.name, + current.counter + ); + counter = current.counter; + samples.exec_outage = samples.exec_outage.max(last_exec.elapsed()); + samples.slowest_exec = samples.slowest_exec.max(started.elapsed()); + last_exec = tokio::time::Instant::now(); + samples.exec_ok += 1; + samples.last = Some(current); + } + Err(error) => samples.exec_failures.push(error), + } + if let Some(port) = options.port { + match try_call_host(sandbox, port).await { + Ok(result) if result == "HA_OK" => { + samples.network_outage = samples.network_outage.max(last_network.elapsed()); + last_network = tokio::time::Instant::now(); + samples.network_ok += 1; + } + Ok(result) => samples.network_failures.push(result), + Err(error) => samples.network_failures.push(error), + } + } + if *stop.borrow() { + break; + } + tokio::select! { + () = tokio::time::sleep(options.interval) => {} + _ = stop.changed() => {} + } + } + samples.exec_outage = samples.exec_outage.max(last_exec.elapsed()); + if samples.network_probed { + samples.network_outage = samples.network_outage.max(last_network.elapsed()); + } + samples +} + +/// Run `transition` while probing every sandbox, and keep probing for `settle` +/// after it finished. +pub async fn while_probing( + sandboxes: &[(&SandboxGuard, MainProcess)], + options: ProbeOptions, + settle: Duration, + transition: impl Future, +) -> (T, Vec) { + let (stop, stopped) = tokio::sync::watch::channel(false); + let samplers = join_all( + sandboxes + .iter() + .map(|(sandbox, baseline)| sample(sandbox, baseline, options, stopped.clone())), + ); + let driver = async { + let outcome = transition.await; + tokio::time::sleep(settle).await; + stop.send_replace(true); + outcome + }; + tokio::join!(driver, samplers) +} + +/// What a sampling run must satisfy. +#[derive(Debug, Clone, Copy)] +pub struct SampleBounds { + /// Longest a sandbox may go without a successful exec probe. + pub exec_outage: Duration, + /// Longest a sandbox may go without a successful policy-mediated call. + pub network_outage: Duration, + /// Exec failures a genuine read/exec race may still produce. `None` keeps + /// the older suites' no-allowance check. + pub exec_failure_allowance: Option, + /// Longest a successful exec probe may take, readiness wait included. + pub exec_probe: Option, +} + +/// Check what the probes of `sandbox` saw against `bounds`. +pub fn check_samples(phase: &str, sandbox: &SandboxGuard, samples: &Samples, bounds: SampleBounds) { + eprintln!( + "{phase}: {} exec {} ok / {} failed (longest outage {:?}, slowest probe {:?}), network {} ok / {} failed (longest outage {:?})", + sandbox.name, + samples.exec_ok, + samples.exec_failures.len(), + samples.exec_outage, + samples.slowest_exec, + samples.network_ok, + samples.network_failures.len(), + samples.network_outage + ); + assert!( + samples.exec_ok > 0, + "{phase}: {} never answered an exec probe: {samples:?}", + sandbox.name + ); + if samples.network_probed { + assert!( + samples.network_ok > 0, + "{phase}: {} never answered a network probe: {samples:?}", + sandbox.name + ); + assert!( + samples.network_outage <= bounds.network_outage, + "{phase}: networking from {} failed for {:?}, longer than {:?}: {:?}", + sandbox.name, + samples.network_outage, + bounds.network_outage, + samples.network_failures + ); + } + assert!( + samples.exec_outage <= bounds.exec_outage, + "{phase}: exec on {} failed for {:?}, longer than {:?}: {:?}", + sandbox.name, + samples.exec_outage, + bounds.exec_outage, + samples.exec_failures + ); + if let Some(allowance) = bounds.exec_failure_allowance { + assert!( + samples.exec_failures.len() <= allowance, + "{phase}: {} failed {} exec probes, more than the {allowance} a race may cost: {:?}", + sandbox.name, + samples.exec_failures.len(), + samples.exec_failures + ); + } + if let Some(probe) = bounds.exec_probe { + assert!( + samples.slowest_exec <= probe, + "{phase}: {}'s slowest successful exec probe took {:?}, longer than {probe:?}", + sandbox.name, + samples.slowest_exec + ); + } +} + /// Host endpoint that answers every request with `HA_OK`. pub struct HostEndpoint { pub port: u16, diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index d88aef9499..ca76b05313 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -476,6 +476,9 @@ whether attachment is available. A nonzero main-process exit under `on-failure`, or any exit under `always`, moves the sandbox to `Starting` during backoff and resource replacement. Connect and exec commands resume after the new supervisor session makes it `Ready`. +`sandbox exec` waits up to its readiness budget (45 seconds by default) for that +`Ready` when the sandbox reads `Provisioning` or `Starting`, instead of failing +on the first read. An explicit `sandbox stop` cancels a pending restart. ### Upload and download files @@ -520,6 +523,11 @@ command exited successfully. A descendant that keeps an inherited output pipe open for more than 30 seconds after the command exits triggers that failure. Check whether the command ran before retrying work with side effects. Use `sandbox connect` to attach to the canonical main process. +If the sandbox is `Provisioning` or `Starting`, such as during a shared +supervisor takeover, exec waits up to 45 seconds for it to reach `Ready` before +starting the command (`--exec-wait-timeout SECONDS` or +`OPENSHELL_EXEC_WAIT_TIMEOUT`; `--no-exec-wait` fails immediately). Any other +phase fails immediately, and wait progress goes to stderr. Use `--env` only for non-secret values. Attach credentials to the sandbox with a provider instead of passing API keys, tokens, or other secrets to `sandbox exec`.