Skip to content

Commit ca42680

Browse files
authored
feat(sandbox): SandboxPhase::Stopped distinguishes intentional stop from crash (#5)
Add a sixth `SandboxPhase` variant so callers can tell an explicit `openshell sandbox stop` apart from a container that crashed. Previously both surfaced as `Error`, leaving consumers (the openlock reattach path in particular) unable to decide whether to resume or surface the failure. Implementation: `stop_sandbox` stamps an `openshell.io/stop-requested` label on the persisted sandbox before invoking the driver; the watch loop's `apply_sandbox_update_locked` then maps the ensuing `ContainerExited` Ready=false condition to `Stopped` instead of `Error` when the label is present. `start_sandbox` clears the label only after a successful resume so failed resumes don't get misclassified. The supervisor-session reconciler skips sandboxes already in `Stopped` to avoid silently reanimating them. Six unit tests cover the new behavior: stamping, clearing, persistence when backend is missing, the error→stopped override, and the no-label case still surfacing as Error.
1 parent 45f537a commit ca42680

3 files changed

Lines changed: 230 additions & 6 deletions

File tree

‎crates/openshell-cli/src/run.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ fn phase_name(phase: i32) -> &'static str {
8585
Ok(SandboxPhase::Ready) => "Ready",
8686
Ok(SandboxPhase::Error) => "Error",
8787
Ok(SandboxPhase::Deleting) => "Deleting",
88+
Ok(SandboxPhase::Stopped) => "Stopped",
8889
Ok(SandboxPhase::Unknown) | Err(_) => "Unknown",
8990
}
9091
}
@@ -3153,7 +3154,7 @@ pub async fn sandbox_list(
31533154
Ok(SandboxPhase::Ready) => phase.green().to_string(),
31543155
Ok(SandboxPhase::Error) => phase.red().to_string(),
31553156
Ok(SandboxPhase::Provisioning) => phase.yellow().to_string(),
3156-
Ok(SandboxPhase::Deleting) => phase.dimmed().to_string(),
3157+
Ok(SandboxPhase::Deleting | SandboxPhase::Stopped) => phase.dimmed().to_string(),
31573158
_ => phase.to_string(),
31583159
};
31593160
let created = format_epoch_ms(sandbox.metadata.as_ref().map_or(0, |m| m.created_at_ms));

‎crates/openshell-server/src/compute/mod.rs‎

Lines changed: 224 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,12 @@ impl fmt::Debug for ComputeRuntime {
248248
}
249249
}
250250

251+
/// Label stamped onto a Sandbox's metadata by `stop_sandbox` and cleared by
252+
/// `start_sandbox`. When the label is present and the watch loop derives
253+
/// `Error` (because the container exited), the phase is overridden to
254+
/// `Stopped` so callers can distinguish a user-requested halt from a crash.
255+
const STOP_REQUESTED_LABEL: &str = "openshell.io/stop-requested";
256+
251257
impl ComputeRuntime {
252258
#[allow(clippy::too_many_arguments)]
253259
async fn from_driver(
@@ -561,7 +567,9 @@ impl ComputeRuntime {
561567

562568
/// Stop the compute resource backing a sandbox without removing the
563569
/// sandbox record. Workspace volume and provider links survive. Phase
564-
/// is left to the watch loop to update as the backend transitions.
570+
/// is left to the watch loop to update as the backend transitions —
571+
/// but the runtime stamps a `stop-requested` label first so the watch
572+
/// loop maps the ensuing `ContainerExited` to `Stopped`, not `Error`.
565573
/// Idempotent: a missing or already-stopped backend resource is not
566574
/// an error.
567575
pub async fn stop_sandbox(&self, name: &str) -> Result<(), Status> {
@@ -575,6 +583,20 @@ impl ComputeRuntime {
575583
return Err(Status::not_found("sandbox not found"));
576584
};
577585

586+
let _ = self
587+
.store
588+
.update_message_cas::<Sandbox, _>(sandbox.object_id(), 0, |s| {
589+
if let Some(metadata) = s.metadata.as_mut() {
590+
metadata
591+
.labels
592+
.insert(STOP_REQUESTED_LABEL.to_string(), "true".to_string());
593+
}
594+
})
595+
.await
596+
.map_err(|e| {
597+
warn!(sandbox_name = %name, error = %e, "Failed to stamp stop-requested label");
598+
});
599+
578600
let driver_sandbox = driver_sandbox_from_public(&sandbox);
579601
self.driver
580602
.stop_sandbox(Request::new(DriverStopSandboxRequest {
@@ -607,10 +629,26 @@ impl ComputeRuntime {
607629
));
608630
};
609631

610-
resume
632+
let started = resume
611633
.resume_sandbox(sandbox.object_id(), sandbox.object_name())
612634
.await
613-
.map_err(|err| Status::internal(format!("start sandbox failed: {err}")))
635+
.map_err(|err| Status::internal(format!("start sandbox failed: {err}")))?;
636+
637+
if started {
638+
let _ = self
639+
.store
640+
.update_message_cas::<Sandbox, _>(sandbox.object_id(), 0, |s| {
641+
if let Some(metadata) = s.metadata.as_mut() {
642+
metadata.labels.remove(STOP_REQUESTED_LABEL);
643+
}
644+
})
645+
.await
646+
.map_err(|e| {
647+
warn!(sandbox_name = %name, error = %e, "Failed to clear stop-requested label");
648+
});
649+
}
650+
651+
Ok(started)
614652
}
615653

616654
pub fn spawn_watchers(&self) {
@@ -990,6 +1028,14 @@ impl ComputeRuntime {
9901028
phase = SandboxPhase::Ready;
9911029
}
9921030

1031+
// Distinguish user-requested stop from a crash: when `stop_sandbox`
1032+
// stamped the stop-requested label, treat the container's terminal
1033+
// exit as `Stopped` rather than `Error`. The label is cleared by
1034+
// `start_sandbox` on a successful resume.
1035+
if phase == SandboxPhase::Error && sandbox_has_stop_requested_label(sandbox) {
1036+
phase = SandboxPhase::Stopped;
1037+
}
1038+
9931039
let old_phase =
9941040
SandboxPhase::try_from(sandbox.phase).unwrap_or(SandboxPhase::Unknown);
9951041
if old_phase != phase {
@@ -1068,8 +1114,12 @@ impl ComputeRuntime {
10681114
let current_phase =
10691115
SandboxPhase::try_from(sandbox.phase).unwrap_or(SandboxPhase::Unknown);
10701116

1071-
// Skip if sandbox is in terminal state
1072-
if current_phase == SandboxPhase::Deleting || current_phase == SandboxPhase::Error {
1117+
// Skip if sandbox is in terminal state. Stopped is intentional;
1118+
// a stale supervisor session event must not silently reanimate it.
1119+
if matches!(
1120+
current_phase,
1121+
SandboxPhase::Deleting | SandboxPhase::Error | SandboxPhase::Stopped
1122+
) {
10731123
return;
10741124
}
10751125

@@ -1627,6 +1677,13 @@ fn public_platform_event_from_driver(event: &DriverPlatformEvent) -> PlatformEve
16271677
}
16281678
}
16291679

1680+
fn sandbox_has_stop_requested_label(sandbox: &Sandbox) -> bool {
1681+
sandbox
1682+
.metadata
1683+
.as_ref()
1684+
.is_some_and(|m| m.labels.get(STOP_REQUESTED_LABEL).map(String::as_str) == Some("true"))
1685+
}
1686+
16301687
fn derive_phase(status: Option<&DriverSandboxStatus>) -> SandboxPhase {
16311688
if let Some(status) = status {
16321689
if status.deleting {
@@ -2378,6 +2435,78 @@ mod tests {
23782435
);
23792436
}
23802437

2438+
#[tokio::test]
2439+
async fn apply_sandbox_update_maps_error_to_stopped_when_stop_requested() {
2440+
let runtime = test_runtime(Arc::new(TestDriver::default())).await;
2441+
let mut sandbox = sandbox_record("sb-1", "sandbox-a", SandboxPhase::Ready);
2442+
sandbox
2443+
.metadata
2444+
.as_mut()
2445+
.unwrap()
2446+
.labels
2447+
.insert(STOP_REQUESTED_LABEL.to_string(), "true".to_string());
2448+
runtime.store.put_message(&sandbox).await.unwrap();
2449+
2450+
runtime
2451+
.apply_sandbox_update(DriverSandbox {
2452+
id: "sb-1".to_string(),
2453+
name: "sandbox-a".to_string(),
2454+
namespace: "default".to_string(),
2455+
spec: None,
2456+
status: Some(make_driver_status(make_driver_condition(
2457+
"ContainerExited",
2458+
"Container has exited",
2459+
))),
2460+
})
2461+
.await
2462+
.unwrap();
2463+
2464+
let stored = runtime
2465+
.store
2466+
.get_message::<Sandbox>("sb-1")
2467+
.await
2468+
.unwrap()
2469+
.unwrap();
2470+
assert_eq!(
2471+
SandboxPhase::try_from(stored.phase).unwrap(),
2472+
SandboxPhase::Stopped,
2473+
"watch loop must surface intentional stop as Stopped, not Error"
2474+
);
2475+
}
2476+
2477+
#[tokio::test]
2478+
async fn apply_sandbox_update_keeps_error_when_stop_label_absent() {
2479+
let runtime = test_runtime(Arc::new(TestDriver::default())).await;
2480+
let sandbox = sandbox_record("sb-1", "sandbox-a", SandboxPhase::Ready);
2481+
runtime.store.put_message(&sandbox).await.unwrap();
2482+
2483+
runtime
2484+
.apply_sandbox_update(DriverSandbox {
2485+
id: "sb-1".to_string(),
2486+
name: "sandbox-a".to_string(),
2487+
namespace: "default".to_string(),
2488+
spec: None,
2489+
status: Some(make_driver_status(make_driver_condition(
2490+
"ContainerExited",
2491+
"Container crashed",
2492+
))),
2493+
})
2494+
.await
2495+
.unwrap();
2496+
2497+
let stored = runtime
2498+
.store
2499+
.get_message::<Sandbox>("sb-1")
2500+
.await
2501+
.unwrap()
2502+
.unwrap();
2503+
assert_eq!(
2504+
SandboxPhase::try_from(stored.phase).unwrap(),
2505+
SandboxPhase::Error,
2506+
"absent stop-requested label must keep the crash signal as Error"
2507+
);
2508+
}
2509+
23812510
#[tokio::test]
23822511
async fn apply_sandbox_update_promotes_connected_supervisor_session_to_ready() {
23832512
let runtime = test_runtime(Arc::new(TestDriver::default())).await;
@@ -2903,6 +3032,96 @@ mod tests {
29033032
.expect("stop_sandbox should succeed");
29043033
}
29053034

3035+
#[tokio::test]
3036+
async fn stop_sandbox_stamps_stop_requested_label() {
3037+
let runtime = test_runtime(Arc::new(TestDriver::default())).await;
3038+
let sandbox = sandbox_record("sb-1", "live", SandboxPhase::Ready);
3039+
runtime.store.put_message(&sandbox).await.unwrap();
3040+
runtime
3041+
.stop_sandbox("live")
3042+
.await
3043+
.expect("stop_sandbox should succeed");
3044+
3045+
let stored = runtime
3046+
.store
3047+
.get_message::<Sandbox>("sb-1")
3048+
.await
3049+
.unwrap()
3050+
.unwrap();
3051+
assert!(
3052+
sandbox_has_stop_requested_label(&stored),
3053+
"stop_sandbox must stamp the stop-requested label so the watch loop maps ContainerExited→Stopped"
3054+
);
3055+
}
3056+
3057+
#[tokio::test]
3058+
async fn start_sandbox_clears_stop_requested_label_on_success() {
3059+
let resume = Arc::new(RecordingResume::default());
3060+
resume.set_result("sb-1", Ok(true)).await;
3061+
let runtime =
3062+
test_runtime_with_resume(Arc::new(TestDriver::default()), Some(resume.clone())).await;
3063+
3064+
let mut sandbox = sandbox_record("sb-1", "live", SandboxPhase::Stopped);
3065+
sandbox
3066+
.metadata
3067+
.as_mut()
3068+
.unwrap()
3069+
.labels
3070+
.insert(STOP_REQUESTED_LABEL.to_string(), "true".to_string());
3071+
runtime.store.put_message(&sandbox).await.unwrap();
3072+
3073+
let started = runtime
3074+
.start_sandbox("live")
3075+
.await
3076+
.expect("start_sandbox should succeed");
3077+
assert!(started);
3078+
3079+
let stored = runtime
3080+
.store
3081+
.get_message::<Sandbox>("sb-1")
3082+
.await
3083+
.unwrap()
3084+
.unwrap();
3085+
assert!(
3086+
!sandbox_has_stop_requested_label(&stored),
3087+
"start_sandbox must clear the stop-requested label on successful resume"
3088+
);
3089+
}
3090+
3091+
#[tokio::test]
3092+
async fn start_sandbox_preserves_stop_requested_label_when_backend_missing() {
3093+
let resume = Arc::new(RecordingResume::default());
3094+
resume.set_result("sb-1", Ok(false)).await;
3095+
let runtime =
3096+
test_runtime_with_resume(Arc::new(TestDriver::default()), Some(resume.clone())).await;
3097+
3098+
let mut sandbox = sandbox_record("sb-1", "ghost", SandboxPhase::Stopped);
3099+
sandbox
3100+
.metadata
3101+
.as_mut()
3102+
.unwrap()
3103+
.labels
3104+
.insert(STOP_REQUESTED_LABEL.to_string(), "true".to_string());
3105+
runtime.store.put_message(&sandbox).await.unwrap();
3106+
3107+
let started = runtime
3108+
.start_sandbox("ghost")
3109+
.await
3110+
.expect("start_sandbox should succeed");
3111+
assert!(!started);
3112+
3113+
let stored = runtime
3114+
.store
3115+
.get_message::<Sandbox>("sb-1")
3116+
.await
3117+
.unwrap()
3118+
.unwrap();
3119+
assert!(
3120+
sandbox_has_stop_requested_label(&stored),
3121+
"label must persist when resume hook reports backend missing — sandbox is still stopped"
3122+
);
3123+
}
3124+
29063125
#[tokio::test]
29073126
async fn start_sandbox_returns_not_found_when_sandbox_missing() {
29083127
let resume = Arc::new(RecordingResume::default());

‎proto/openshell.proto‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,10 @@ enum SandboxPhase {
369369
SANDBOX_PHASE_ERROR = 3;
370370
SANDBOX_PHASE_DELETING = 4;
371371
SANDBOX_PHASE_UNKNOWN = 5;
372+
// Compute backend is intentionally stopped (explicit Stop RPC). Distinct
373+
// from Error so reattach paths and external clients can tell a user-
374+
// requested halt from a crash. Cleared by the Start RPC.
375+
SANDBOX_PHASE_STOPPED = 6;
372376
}
373377

374378
// Public platform event exposed on the sandbox watch stream.

0 commit comments

Comments
 (0)