Skip to content

Commit c74fb7e

Browse files
committed
fix(kubernetes): correct warm pool claims, failover, and cleanup
Signed-off-by: Gordon Sim <gsim@redhat.com>
1 parent d4bdcf5 commit c74fb7e

18 files changed

Lines changed: 580 additions & 85 deletions

File tree

‎crates/openshell-driver-kubernetes/README.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -327,10 +327,11 @@ retirement tombstone. Recovery never falls back to workspace Secret reads. Retir
327327
fences delayed writers before collecting their credential material. Restart uses
328328
a new generation and updates the Pod's pair label; the original physical CR name remains unchanged.
329329

330-
Development deployments using the earlier Secret-backed claim format must finish
331-
pending claims with that gateway before upgrading. The driver rejects those
332-
references explicitly; it does not read legacy claim Secrets or discard a
333-
potentially activated workload.
330+
Development deployments using Secret-backed claims or the earlier
331+
`openshell.ai/warm-claim-intent` annotation must finish in-flight launches
332+
before upgrading. New gateways store launch decisions under
333+
`internal.openshell.ai/warm-claim-intent` and treat the earlier annotation as
334+
caller metadata. Legacy Secret-backed claims require the gateway that wrote them.
334335

335336
The focused gateway-backed claim E2E uses fresh branch images and checks physical
336337
Pod reuse, gateway restart recovery before and after claiming, refill, exec,

‎crates/openshell-driver-kubernetes/src/driver.rs‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,8 @@ impl VerifiedControlPolicy {
480480
pub enum KubernetesDriverError {
481481
#[error("sandbox already exists")]
482482
AlreadyExists,
483+
#[error("prepared bootstrap no longer matches observed runtime coordinates")]
484+
StalePreparation,
483485
#[error("sandbox not found")]
484486
NotFound,
485487
#[error("{0}")]
@@ -587,6 +589,7 @@ impl From<KubernetesDriverError> for openshell_core::ComputeDriverError {
587589
match err {
588590
KubernetesDriverError::AlreadyExists => Self::AlreadyExists,
589591
KubernetesDriverError::NotFound => Self::NotFound,
592+
KubernetesDriverError::StalePreparation => Self::Precondition(err.to_string()),
590593
KubernetesDriverError::InvalidArgument(m) => Self::InvalidArgument(m),
591594
KubernetesDriverError::Precondition(m) => Self::Precondition(m),
592595
KubernetesDriverError::Message(m) => Self::Message(m),
@@ -1107,12 +1110,11 @@ impl std::fmt::Debug for KubernetesComputeDriver {
11071110
}
11081111

11091112
impl KubernetesComputeDriver {
1110-
/// Environment that lets a supervisor export spans, joining the current
1111-
/// trace, OCSF events, and relayed workload traces, identifying the
1112-
/// gateway that launched it.
1113-
fn supervisor_otlp_environment(&self) -> Vec<(&'static str, String)> {
1113+
/// Prepared Pods are rendered across requests. Only a cold launch inherits
1114+
/// the provisioning span; exporter settings and gateway identity apply to both.
1115+
fn supervisor_otlp_environment(&self, inherit_trace: bool) -> Vec<(&'static str, String)> {
11141116
let mut environment = self.config.supervisor_otlp.environment();
1115-
if self.config.supervisor_otlp.traces.is_some() {
1117+
if inherit_trace && self.config.supervisor_otlp.traces.is_some() {
11161118
environment.extend(openshell_otel::current_trace_context_environment());
11171119
}
11181120
if let Some(name) = &self.config.supervisor_gateway_name {
@@ -3607,7 +3609,6 @@ impl KubernetesComputeDriver {
36073609
upstream_proxy_ca_bundle_staged: bool,
36083610
warm: bool,
36093611
network_additional_ca: Option<(&str, &str)>,
3610-
tracing_environment: &[(&str, String)],
36113612
) -> Result<Pod, KubernetesDriverError> {
36123613
let mut pod = crate::sandbox_runtime::with_runtime_class(
36133614
crate::app_listener::configure_supervisor_pod(
@@ -3644,7 +3645,7 @@ impl KubernetesComputeDriver {
36443645
),
36453646
network_additional_ca,
36463647
owner,
3647-
tracing_environment,
3648+
&self.supervisor_otlp_environment(!warm),
36483649
self.config.sandbox_attach_request_timeout_seconds,
36493650
)
36503651
.map_err(KubernetesDriverError::Message)?,
@@ -3700,7 +3701,6 @@ impl KubernetesComputeDriver {
37003701
network_additional_ca
37013702
.as_ref()
37023703
.map(|generation| (generation.name.as_str(), generation.digest.as_str())),
3703-
&self.supervisor_otlp_environment(),
37043704
)?;
37053705
let stored = match pods.create(&PostParams::default(), &pod).await {
37063706
Ok(stored) => stored,
@@ -9420,7 +9420,7 @@ mod tests {
94209420
supervisor_otlp,
94219421
..Default::default()
94229422
})
9423-
.supervisor_otlp_environment()
9423+
.supervisor_otlp_environment(true)
94249424
};
94259425
let names = |supervisor_otlp| {
94269426
environment(supervisor_otlp)
@@ -9484,7 +9484,7 @@ mod tests {
94849484
..Default::default()
94859485
});
94869486
assert_eq!(
9487-
driver.supervisor_otlp_environment(),
9487+
driver.supervisor_otlp_environment(true),
94889488
[(
94899489
openshell_core::sandbox_env::GATEWAY_NAME,
94909490
"prod-west".to_string()
@@ -10122,7 +10122,7 @@ mod tests {
1012210122
}
1012310123

1012410124
#[tokio::test]
10125-
async fn sandbox_annotation_propagates_the_active_w3c_trace_context() {
10125+
async fn provisioning_trace_propagates_to_sandbox_annotations_and_cold_supervisors() {
1012610126
use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider};
1012710127
use tracing_subscriber::layer::SubscriberExt as _;
1012810128

@@ -10137,6 +10137,22 @@ mod tests {
1013710137
let annotations = tracing::subscriber::with_default(subscriber, || {
1013810138
let span = tracing::info_span!("kubernetes.provision");
1013910139
let _entered = span.enter();
10140+
let mut driver =
10141+
KubernetesComputeDriver::new_for_test(KubernetesComputeConfig::default());
10142+
driver.config.supervisor_otlp.traces = Some(openshell_core::sandbox_env::OtlpExport {
10143+
endpoint: "http://traces:4317".into(),
10144+
protocol: openshell_core::sandbox_env::OtlpProtocol::Grpc,
10145+
});
10146+
assert!(
10147+
driver
10148+
.supervisor_otlp_environment(true)
10149+
.iter()
10150+
.any(|(name, _)| *name == openshell_otel::TRACEPARENT_ENV)
10151+
);
10152+
assert_eq!(
10153+
driver.supervisor_otlp_environment(false),
10154+
driver.config.supervisor_otlp.environment()
10155+
);
1014010156
let mut annotations = BTreeMap::new();
1014110157
add_trace_context_annotation(&mut annotations);
1014210158
annotations

‎crates/openshell-driver-kubernetes/src/prepared_runtime.rs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,7 @@ impl PreparedRuntimeBootstrap {
8383
let expected =
8484
provision(registration.runtime_descriptor.tls.clone()).map_err(backend_error)?;
8585
if self.request(&expected)?.registration != registration {
86-
return Err(invalid(
87-
"prepared bootstrap no longer matches observed runtime coordinates",
88-
));
86+
return Err(KubernetesDriverError::StalePreparation);
8987
}
9088
return Ok(registration);
9189
}

‎crates/openshell-driver-kubernetes/src/warm_pool.rs‎

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ fn validate_trust(trust: &WarmRuntimeTrust) -> Result<(), KubernetesDriverError>
4040
.map_err(|_| invalid("invalid warm runtime gateway verification bundle"))
4141
}
4242

43+
#[path = "warm_pool/quantity.rs"]
44+
mod quantity;
45+
4346
#[path = "warm_pool/compatibility.rs"]
4447
mod compatibility;
4548

@@ -669,9 +672,7 @@ impl KubernetesComputeDriver {
669672
|| current_control.uid != control_policy.uid
670673
|| current_control.resource_version != control_policy.resource_version
671674
{
672-
return Err(invalid(
673-
"warm runtime network fence changed during preparation",
674-
));
675+
return Err(KubernetesDriverError::StalePreparation);
675676
}
676677
let current_namespace = Api::<Namespace>::all(self.client.clone())
677678
.get(&resource.namespace)
@@ -842,10 +843,8 @@ fn validate_pod(
842843
}
843844
let actual = serde_json::to_value(pod).map_err(record_error)?;
844845
for key in ["containers", "initContainers"] {
845-
if let Some(path) = shape_difference(
846-
&record.shape["spec"]["podTemplate"]["spec"][key],
847-
&actual["spec"][key],
848-
) {
846+
let expected = &record.shape["spec"]["podTemplate"]["spec"][key];
847+
if let Some(path) = shape_difference(expected, &actual["spec"][key], &mut vec![key]) {
849848
return Err(invalid(&format!(
850849
"warm Pod containers changed after admission at {key}{path}"
851850
)));
@@ -1038,10 +1037,14 @@ fn canonicalize_environment(value: &mut serde_json::Value) {
10381037
}
10391038

10401039
fn requested_shape_matches(expected: &serde_json::Value, actual: &serde_json::Value) -> bool {
1041-
shape_difference(expected, actual).is_none()
1040+
shape_difference(expected, actual, &mut Vec::new()).is_none()
10421041
}
10431042

1044-
fn shape_difference(expected: &serde_json::Value, actual: &serde_json::Value) -> Option<String> {
1043+
fn shape_difference<'a>(
1044+
expected: &'a serde_json::Value,
1045+
actual: &serde_json::Value,
1046+
fields: &mut Vec<&'a str>,
1047+
) -> Option<String> {
10451048
match (expected, actual) {
10461049
(serde_json::Value::Object(expected), serde_json::Value::Object(actual)) => {
10471050
expected.iter().find_map(|(key, value)| {
@@ -1055,7 +1058,12 @@ fn shape_difference(expected: &serde_json::Value, actual: &serde_json::Value) ->
10551058
|| (key == "value" && value.as_str() == Some(""));
10561059
(!omitted).then(String::new)
10571060
},
1058-
|actual| shape_difference(value, actual),
1061+
|actual| {
1062+
fields.push(key);
1063+
let difference = shape_difference(value, actual, fields);
1064+
fields.pop();
1065+
difference
1066+
},
10591067
);
10601068
difference.map(|suffix| format!("/{key}{suffix}"))
10611069
})
@@ -1069,9 +1077,25 @@ fn shape_difference(expected: &serde_json::Value, actual: &serde_json::Value) ->
10691077
.zip(actual)
10701078
.enumerate()
10711079
.find_map(|(index, (expected, actual))| {
1072-
shape_difference(expected, actual).map(|suffix| format!("/{index}{suffix}"))
1080+
shape_difference(expected, actual, fields)
1081+
.map(|suffix| format!("/{index}{suffix}"))
10731082
})
10741083
}
1084+
(left, right)
1085+
if left != right
1086+
&& matches!(
1087+
fields.as_slice(),
1088+
[
1089+
..,
1090+
"containers" | "initContainers",
1091+
"resources",
1092+
"requests" | "limits",
1093+
_
1094+
]
1095+
) =>
1096+
{
1097+
(!quantity::equivalent(left, right)).then(String::new)
1098+
}
10751099
_ => (expected != actual).then(String::new),
10761100
}
10771101
}

‎crates/openshell-driver-kubernetes/src/warm_pool/claim.rs‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,12 @@ impl KubernetesComputeDriver {
237237
.await
238238
.map(Some);
239239
}
240+
if !claim_attempted
241+
&& matches!(error, KubernetesDriverError::StalePreparation)
242+
{
243+
self.retire_warm_runtime(resource).await?;
244+
continue;
245+
}
240246
if supervision
241247
.pending_warm_claims(&resource.workspace)
242248
.await
@@ -337,21 +343,29 @@ impl KubernetesComputeDriver {
337343
}
338344

339345
/// Recover gateway reservations even when no CR carries the logical ID yet.
340-
/// Return their sessions so pool maintenance excludes them from spare capacity.
346+
/// Mark reserved resources as claimed. Keep the drain scheduled while recovery
347+
/// could still need this pool's inventory, including after an ambiguous delete.
341348
pub(super) async fn recover_pending_warm_claims(
342349
&self,
343350
workspace: &str,
344-
resources: &[WarmRuntimeResource],
345-
) -> Result<std::collections::BTreeSet<SandboxSessionId>, KubernetesDriverError> {
351+
pool_id: &str,
352+
resources: &mut [WarmRuntimeResource],
353+
) -> Result<bool, KubernetesDriverError> {
346354
let claims = self
347355
.warm_supervision()?
348356
.pending_warm_claims(workspace)
349357
.await
350358
.map_err(KubernetesDriverError::Message)?;
351-
let mut reserved = std::collections::BTreeSet::new();
359+
let mut recovering = false;
352360
for pending in claims.pending {
353361
let session = pending.intent.registration.runtime_descriptor.session_id;
354-
reserved.insert(session);
362+
if let Some(resource) = resources.iter_mut().find(|r| r.session_id == session) {
363+
resource.claimed = true;
364+
recovering |= resource.pool_id == pool_id;
365+
} else {
366+
// Missing inventory cannot identify the pool of an unresolved reservation.
367+
recovering = true;
368+
}
355369
let Ok(_guard) = self
356370
.lifecycle_gates
357371
.gate_for(&pending.sandbox.id)
@@ -373,9 +387,10 @@ impl KubernetesComputeDriver {
373387
&& retired.generation.as_str() == resource.session_id.to_string()
374388
}) {
375389
self.retire_warm_runtime(resource).await?;
390+
recovering |= resource.pool_id == pool_id;
376391
}
377392
}
378-
Ok(reserved)
393+
Ok(recovering)
379394
}
380395

381396
async fn validate_claim_retry(

‎crates/openshell-driver-kubernetes/src/warm_pool/compatibility.rs‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,6 @@ impl KubernetesComputeDriver {
3939
bundle.digest(),
4040
)
4141
});
42-
let mut telemetry = self.config.supervisor_otlp.environment();
43-
if let Some(name) = &self.config.supervisor_gateway_name {
44-
telemetry.push((openshell_core::sandbox_env::GATEWAY_NAME, name.clone()));
45-
}
4642
let pod = self.render_sandbox_runtime_supervisor(
4743
&namespace,
4844
&names,
@@ -59,7 +55,6 @@ impl KubernetesComputeDriver {
5955
network_ca
6056
.as_ref()
6157
.map(|(name, digest)| (name.as_str(), *digest)),
62-
&telemetry,
6358
)?;
6459
serde_json::json!({
6560
"dedicated": pod.spec,

‎crates/openshell-driver-kubernetes/src/warm_pool/dedicated.rs‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,10 @@ pub(in crate::driver) fn configure_dedicated_pod(
8787
) {
8888
let spec = pod.spec.as_mut().expect("supervisor spec");
8989
let container = &mut spec.containers[0];
90+
let health_port = if port == 5502 { 5503 } else { 5502 };
9091
container.startup_probe = Some(k8s_openapi::api::core::v1::Probe {
9192
tcp_socket: Some(k8s_openapi::api::core::v1::TCPSocketAction {
92-
port: IntOrString::Int(5502),
93+
port: IntOrString::Int(health_port),
9394
..Default::default()
9495
}),
9596
period_seconds: Some(1),
@@ -102,7 +103,7 @@ pub(in crate::driver) fn configure_dedicated_pod(
102103
.expect("supervisor command")
103104
.extend([
104105
"--warm-health-port".into(),
105-
"5502".into(),
106+
health_port.to_string(),
106107
"--warm-prepared-file".into(),
107108
format!("{PREPARED_DIR}/{PREPARED_KEY}"),
108109
"--runtime-listen".into(),
@@ -144,6 +145,23 @@ pub(in crate::driver) fn validate_dedicated_pod(
144145
) -> Result<(), KubernetesDriverError> {
145146
let mut actual = serde_json::to_value(stored).map_err(record_error)?;
146147
let mut expected_spec = serde_json::to_value(expected).map_err(record_error)?;
148+
// Earlier gateways propagated the reconciler's trace into a prepared Pod.
149+
// Ignore only those literal carrier values on a tracing-enabled supervisor.
150+
if let Some(env) = actual
151+
.pointer_mut("/spec/containers/0/env")
152+
.and_then(serde_json::Value::as_array_mut)
153+
&& env
154+
.iter()
155+
.any(|v| v["name"] == openshell_core::sandbox_env::OTLP_ENDPOINT)
156+
{
157+
env.retain(|v| {
158+
!matches!(
159+
v["name"].as_str(),
160+
Some(openshell_otel::TRACEPARENT_ENV | openshell_otel::TRACESTATE_ENV)
161+
) || !v["value"].is_string()
162+
|| v.get("valueFrom").is_some()
163+
});
164+
}
147165
// Gate removal is the only mutation performed after preparation. Kubernetes
148166
// may default omitted fields, but supplied container and security fields bind.
149167
actual["spec"]

0 commit comments

Comments
 (0)