Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 16 additions & 8 deletions crates/openshell-driver-kubernetes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -399,14 +399,22 @@ driver instance. The gate preserves concurrency across sandboxes; it does not
provide distributed exclusion between separate gateway or driver processes.

In a high-availability gateway, only the lease holder reconciles, while any
replica can serve a lifecycle RPC. A restart marks the CR `Preparing` before it
creates the supervisor Pod, and reconciliation respects that claim until the
bootstrap grace period expires, then reaps it: a stale restart is suspended and
a stale create is deleted. Before it deletes the supervisor Pod of a stopped
sandbox, reconciliation reads the CR again and skips the deletion if the CR
changed after its refresh. Lifecycle writes to the CR retry on resourceVersion
conflicts without checking whether another replica started a transition, so a
request on one replica can still overwrite a suspension started by another.
replica can serve a lifecycle RPC. A restart claims the CR, marking it
`Preparing`, before it creates the supervisor Pod. The claim succeeds only if
the CR is stopped and no other transition is in progress, and reconciliation
respects it until the bootstrap grace period expires, then reaps it: a stale
restart is suspended and a stale create is deleted. Every create or restart
write to the CR is a compare-and-swap against the request's claim (CR UID,
operation, and generation), and supervisor Pods are deleted by UID. If another
replica started a transition such as a suspension, the request fails. A failed
create deletes its CR. A failed restart that lost its claim leaves the CR to the
other transition and deletes only the supervisor Pod it created. Stop and
suspend writes don't check a claim yet
([#6110](https://github.com/ai-openshell/openshell/issues/6110)), so a stop,
including a failed restart's rollback, can remove the supervisor Pod of a start
that claimed the CR while the stop was finishing. Before it
deletes the supervisor Pod of a stopped sandbox, reconciliation reads the CR
again and skips the deletion if the CR changed after its refresh.

## GPU Support

Expand Down
368 changes: 368 additions & 0 deletions crates/openshell-driver-kubernetes/src/bootstrap_claim.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,368 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Bootstrap claims on a Sandbox CR and the compare-and-swap writes that
//! respect them.
//!
//! A create or restart claims a Sandbox by recording its operation, phase,
//! and generation in annotations. Any gateway replica may serve the request,
//! so each later write compares the stored claim with the request's own and
//! refuses to overwrite a transition another replica started.

use super::{
ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE,
ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING,
ANNOTATION_SANDBOX_RUNTIME_GENERATION, ANNOTATION_SANDBOX_RUNTIME_READINESS, KUBE_API_TIMEOUT,
KubernetesDriverError, is_kube_resource_version_conflict, kubernetes_pod_termination_timeout,
sandbox_runtime_generation, sandbox_runtime_should_run,
};
use k8s_openapi::api::core::v1::Pod;
use kube::Api;
use kube::Error as KubeError;
use kube::api::{DeleteParams, Patch, PatchParams, Preconditions};
use kube::core::DynamicObject;
use std::collections::BTreeMap;
use std::time::Duration;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SandboxRuntimeBootstrapPhase {
Preparing,
Released,
Releasing,
Suspending,
}

impl SandboxRuntimeBootstrapPhase {
pub(super) const fn as_str(self) -> &'static str {
match self {
Self::Preparing => "preparing",
Self::Released => "released",
Self::Releasing => "releasing",
Self::Suspending => "suspending",
}
}

pub(super) fn parse(value: &str) -> Option<Self> {
match value {
"preparing" => Some(Self::Preparing),
"released" => Some(Self::Released),
"releasing" => Some(Self::Releasing),
"suspending" => Some(Self::Suspending),
_ => None,
}
}

/// Whether a create or restart claim in this phase still belongs to the
/// request that made it. `Released` does, so a request whose `Released`
/// write timed out but landed can still roll back.
const fn held_by_claimant(self) -> bool {
matches!(self, Self::Preparing | Self::Released)
}
}

/// The lifecycle request that started a bootstrap transition.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SandboxRuntimeBootstrapOperation {
Create,
Restart,
Stop,
}

impl SandboxRuntimeBootstrapOperation {
const fn as_str(self) -> &'static str {
match self {
Self::Create => "create",
Self::Restart => "restart",
Self::Stop => "stop",
}
}

fn parse(value: &str) -> Option<Self> {
[Self::Create, Self::Restart, Self::Stop]
.into_iter()
.find(|operation| operation.as_str() == value)
}
}

fn annotation<'a>(object: &'a DynamicObject, key: &str) -> Option<&'a str> {
object
.metadata
.annotations
.as_ref()
.and_then(|annotations| annotations.get(key))
.map(String::as_str)
}

pub(super) fn sandbox_runtime_bootstrap_in_progress(object: &DynamicObject) -> bool {
annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING) == Some("true")
}

pub(super) fn sandbox_runtime_bootstrap_operation(
object: &DynamicObject,
) -> Option<SandboxRuntimeBootstrapOperation> {
annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION)
.and_then(SandboxRuntimeBootstrapOperation::parse)
}

pub(super) fn sandbox_runtime_bootstrap_phase(
object: &DynamicObject,
) -> Option<SandboxRuntimeBootstrapPhase> {
annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE)
.and_then(SandboxRuntimeBootstrapPhase::parse)
}

/// Annotations that start a bootstrap transition and its grace period.
fn bootstrap_annotations(
operation: SandboxRuntimeBootstrapOperation,
phase: SandboxRuntimeBootstrapPhase,
) -> BTreeMap<String, String> {
BTreeMap::from([
(
ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING.to_string(),
"true".to_string(),
),
(
ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT.to_string(),
openshell_core::time::now_ms().to_string(),
),
(
ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION.to_string(),
operation.as_str().to_string(),
),
(
ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE.to_string(),
phase.as_str().to_string(),
),
])
}

/// Annotations that start a stop in `phase` and mark the runtime unavailable.
pub(super) fn stop_annotations(phase: SandboxRuntimeBootstrapPhase) -> BTreeMap<String, String> {
let mut annotations = bootstrap_annotations(SandboxRuntimeBootstrapOperation::Stop, phase);
annotations.insert(
ANNOTATION_SANDBOX_RUNTIME_READINESS.to_string(),
"unavailable".to_string(),
);
annotations
}

/// The resourceVersion a compare-and-swap patch pins. An object without one
/// would turn the patch into an unconditional write, so it is an error.
pub(super) fn resource_version(object: &DynamicObject) -> Result<&str, KubernetesDriverError> {
object.metadata.resource_version.as_deref().ok_or_else(|| {
KubernetesDriverError::Message(format!(
"Kubernetes resource {} has no resourceVersion",
object.metadata.name.as_deref().unwrap_or("<unnamed>")
))
})
}

/// Read `name` and apply the merge patch `patch_for` builds from it, retrying
/// with a fresh read on a resourceVersion conflict. `patch_for` sees the
/// current object each time and may refuse the write; the patch must pin
/// [`resource_version`] for the comparison to hold.
pub(super) async fn compare_and_patch_dynamic_object(
api: &Api<DynamicObject>,
name: &str,
mut patch_for: impl FnMut(&DynamicObject) -> Result<serde_json::Value, KubernetesDriverError>,
) -> Result<DynamicObject, KubernetesDriverError> {
let operation = async {
loop {
let current = api
.get(name)
.await
.map_err(KubernetesDriverError::from_kube)?;
let patch = patch_for(&current)?;
match api
.patch(name, &PatchParams::default(), &Patch::Merge(&patch))
.await
{
Ok(updated) => return Ok(updated),
Err(error) if is_kube_resource_version_conflict(&error) => {
tokio::task::yield_now().await;
}
Err(error) => return Err(KubernetesDriverError::from_kube(error)),
}
}
};
tokio::time::timeout(KUBE_API_TIMEOUT, operation)
.await
.map_err(|_| {
KubernetesDriverError::Message(format!(
"timed out after {}s updating Kubernetes resource {name}",
KUBE_API_TIMEOUT.as_secs()
))
})?
}

/// A create or restart request's claim on a Sandbox's bootstrap.
#[derive(Clone, Copy, Debug)]
pub(super) struct SandboxRuntimeBootstrapClaim<'a> {
cr_uid: &'a str,
operation: SandboxRuntimeBootstrapOperation,
generation: &'a str,
}

impl<'a> SandboxRuntimeBootstrapClaim<'a> {
pub(super) const fn new(
cr_uid: &'a str,
operation: SandboxRuntimeBootstrapOperation,
generation: &'a str,
) -> Self {
Self {
cr_uid,
operation,
generation,
}
}

pub(super) const fn cr_uid(&self) -> &'a str {
self.cr_uid
}

/// Annotations that record a claim for `operation` and `generation`. A
/// create writes them when it creates the CR, before its UID exists.
pub(super) fn annotations(
operation: SandboxRuntimeBootstrapOperation,
generation: &str,
) -> BTreeMap<String, String> {
let mut annotations =
bootstrap_annotations(operation, SandboxRuntimeBootstrapPhase::Preparing);
annotations.insert(
ANNOTATION_SANDBOX_RUNTIME_GENERATION.to_string(),
generation.to_string(),
);
annotations
}

/// Claim a stopped Sandbox that no other transition has claimed.
pub(super) async fn begin(
&self,
api: &Api<DynamicObject>,
name: &str,
) -> Result<(), KubernetesDriverError> {
compare_and_patch_dynamic_object(api, name, |current| {
if current.metadata.uid.as_deref() != Some(self.cr_uid) {
return Err(KubernetesDriverError::Precondition(
"the Sandbox resource was replaced".to_string(),
));
}
if sandbox_runtime_bootstrap_in_progress(current) || sandbox_runtime_should_run(current)
{
return Err(KubernetesDriverError::Precondition(
"another lifecycle transition claimed the sandbox; retry after it completes"
.to_string(),
));
}
Ok(serde_json::json!({
"metadata": {
"resourceVersion": resource_version(current)?,
"annotations": Self::annotations(self.operation, self.generation),
},
}))
})
.await?;
Ok(())
}

/// Apply the patch `patch_for` builds from the current resourceVersion,
/// but only while this claim still holds. Fails with `Precondition` once
/// another transition has replaced it.
pub(super) async fn patch(
&self,
api: &Api<DynamicObject>,
name: &str,
mut patch_for: impl FnMut(&str) -> serde_json::Value,
) -> Result<DynamicObject, KubernetesDriverError> {
compare_and_patch_dynamic_object(api, name, |current| {
self.ensure_held(current)?;
Ok(patch_for(resource_version(current)?))
})
.await
}

/// Mark the generation installed so reconciliation may complete it.
pub(super) async fn release(
&self,
api: &Api<DynamicObject>,
name: &str,
) -> Result<(), KubernetesDriverError> {
self.patch(api, name, |version| {
serde_json::json!({
"metadata": {
"resourceVersion": version,
"annotations": {
ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE:
SandboxRuntimeBootstrapPhase::Released.as_str(),
}
}
})
})
.await?;
Ok(())
}

fn ensure_held(&self, current: &DynamicObject) -> Result<(), KubernetesDriverError> {
let held = current.metadata.uid.as_deref() == Some(self.cr_uid)
&& sandbox_runtime_bootstrap_in_progress(current)
&& sandbox_runtime_bootstrap_phase(current)
.is_some_and(SandboxRuntimeBootstrapPhase::held_by_claimant)
&& sandbox_runtime_bootstrap_operation(current) == Some(self.operation)
&& sandbox_runtime_generation(current) == Some(self.generation);
if held {
Ok(())
} else {
Err(KubernetesDriverError::Precondition(format!(
"sandbox {} of generation {} was superseded by another lifecycle transition",
self.operation.as_str(),
self.generation
)))
}
}
}

/// Delete `pod` by UID and wait until it is gone. A Pod that has since been
/// created under the same name, such as by a restart on another replica, is
/// left running and does not extend the wait.
pub(super) async fn delete_supervisor_pod_and_wait(
pods: &Api<Pod>,
pod: Pod,
) -> Result<(), KubernetesDriverError> {
let name =
pod.metadata.name.clone().ok_or_else(|| {
KubernetesDriverError::Message("supervisor Pod has no name".to_string())
})?;
let uid = pod.metadata.uid.clone();
let deletion_timeout = kubernetes_pod_termination_timeout(&pod);
match pods
.delete(
&name,
&DeleteParams::foreground().preconditions(Preconditions {
uid: uid.clone(),
resource_version: None,
}),
)
.await
{
Ok(_) => {}
Err(KubeError::Api(error)) if error.code == 404 => return Ok(()),
Err(error) => return Err(KubernetesDriverError::from_kube(error)),
}
let deadline = tokio::time::Instant::now() + deletion_timeout;
loop {
let current = pods
.get_opt(&name)
.await
.map_err(KubernetesDriverError::from_kube)?;
if current.is_none_or(|current| current.metadata.uid != uid) {
return Ok(());
}
if tokio::time::Instant::now() >= deadline {
return Err(KubernetesDriverError::Message(format!(
"timed out after {}s waiting for supervisor Pod deletion",
deletion_timeout.as_secs()
)));
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
Loading
Loading