Skip to content

Commit 5bde8ea

Browse files
committed
refactor(warm-pool): recover from gateway persistence without workspace Secret reads
Signed-off-by: Gordon Sim <gsim@redhat.com>
1 parent b3bae4a commit 5bde8ea

32 files changed

Lines changed: 3375 additions & 1072 deletions

File tree

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

Lines changed: 48 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -199,11 +199,12 @@ It supplies no logical Sandbox ID, gateway session token, or workload credential
199199
The controller must persist the physical session, generation and route first,
200200
admit the Sandbox and gated Pod, and verify the namespace and network fences.
201201
The provisioning callback builds the boundary configuration and descriptor from
202-
those observations using the TLS pin supplied by the helper. On retry, the helper
203-
reads the existing Secret, checks its workspace and Pod UID ownership, and compares
204-
the complete bootstrap configuration with the expected one. Concurrent creators
205-
use the winning Secret's identity. Read failures, changed inputs and capacity
206-
refusals fail without replacing keys, deleting resources or releasing the gate.
202+
those observations using the generated TLS pin. All bootstrap Secret creates,
203+
including managed image-pull copies and dedicated supervisor material, finish
204+
before the gateway records the preparation. Recovery reads that public record
205+
and compares its descriptor with current resource observations. Incomplete
206+
attempts remain gated and expire into retirement; a conflicting or ambiguous
207+
Secret create never authorizes adopting its contents.
207208

208209
`driver::warm_pool` now owns the physical provisioning sequence through
209210
`prepare_warm_runtime`, `resume_warm_runtime`, and `warm_runtime_inventory`. It
@@ -219,26 +220,26 @@ shared-supervisor capacity before releasing the scheduling gate. Immediately
219220
before release it rechecks the CR, Pod, resource admission, namespace UID and
220221
network fences. Pod and CR mutations carry resource-version preconditions;
221222
gate removal preserves gates owned by other controllers. Lost responses recover
222-
through the CR journal and existing immutable Secret. Replacements, changed
223+
through the CR journal and gateway preparation record. Replacements, changed
223224
requests and premature gate removal fail closed. A replacement needs a fresh
224225
session, generation, route and Secret. Pool controllers must retain request
225226
identities across uncertain writes and never reuse retired names or sessions.
226227

227-
`retire_warm_runtime` journals retirement before asking the gateway to fence the
228-
physical route permanently, including when capacity admission never completed.
229-
Only a confirmed fence permits foreground deletion of the CR with UID and
228+
`retire_warm_runtime` asks the gateway to fence the physical route permanently,
229+
including when capacity admission never completed. Only a confirmed fence permits
230+
marking the CR retiring and deleting it in the foreground with UID and
230231
resource-version preconditions. Kubernetes collects its Pod, the Pod-owned
231232
bootstrap Secret and the CR-owned control policy; namespace-wide network fences
232233
remain. Ambiguous failures leave the journal for retry. Concurrent claims,
233234
replaced resources and changed reservations do not authorize deletion. If the
234235
CR is already absent, the controller must reconcile any remaining gateway
235236
preparation independently from its durable inventory.
236237

237-
These operations support dedicated and shared supervisors in shared and operator
238-
workspace modes. Managed namespaces need bootstrap journaling in the gateway
239-
namespace to preserve their create-only Secret permissions. Inventory includes preparing, retiring
240-
and deleting resources; a released gate does not mean that the supervisor has
241-
authenticated the runtime or that it is claimable.
238+
These operations support dedicated and shared supervisors in shared, operator
239+
and managed workspaces. Warm pooling requires no additional workspace Secret-read
240+
permissions. Secrets deliver bootstrap material to Pods; gateway persistence owns
241+
preparation and claim recovery. Inventory includes preparing, retiring and deleting
242+
resources; a released gate does not prove that a runtime is claimable.
242243

243244
Template-driven pooling is enabled by default through `warm_pool.enabled`.
244245
The gateway supplies stored template targets through the existing in-process
@@ -255,9 +256,6 @@ operator configurations. The fingerprint covers canonical driver settings,
255256
workload shape and public verification keys. Deleted templates leave journal
256257
tombstones that drain old inventory, even after restart. Recreating a name gets a
257258
new pool. Disabling pooling drains spares without affecting claimed sandboxes.
258-
Recovery requires namespace-scoped Secret `get`, granted by default in shared
259-
mode and by the operator workspace chart's `gateway.warmPoolSecretReads` setting.
260-
Kubernetes cannot constrain generated names by prefix; no list/watch is added.
261259

262260
Each pool attempts at most four operations concurrently per pass, retries
263261
unfinished operations no sooner than 30 seconds later, and bounds an operation
@@ -279,7 +277,6 @@ the process holding the authenticated connection.
279277
The loop counts reserved or released runtimes as pending until then. A missing
280278
owner, preparation timeout, maximum age or
281279
60 seconds without a ready observation retires the spare. Template workloads pass through the normal driver conversion and admission.
282-
Managed namespace pooling remains unsupported.
283280

284281
A dedicated supervisor starts with public runtime coordinates and gateway TLS trust
285282
mounted before the scheduling gate opens. It holds the authenticated runtime
@@ -298,18 +295,36 @@ original physical supervisor; restart provisions a fresh generation.
298295

299296
Sandbox creation from a template selects a ready spare from that template's
300297
current pool revision in the same workspace. Its rendered Pod shape and child environment must match exactly;
301-
non-matching requests and empty pools use cold creation. The driver writes a
302-
Pod-owned immutable claim Secret, then CAS-labels the physical CR with the logical
303-
Sandbox ID before gateway activation. Retirement and competing claims use the
304-
same CR fence. After this point an error never falls back to a second runtime.
298+
non-matching requests and empty pools use cold creation. A create that loses a
299+
spare to another sandbox or to retirement tries the next candidate only after
300+
gateway persistence confirms the outcome. Cold selection commits a launch decision
301+
that fences delayed warm reservations. An ambiguous failure cannot fall back. The driver writes a
302+
durable claim intent through `SharedSupervision`, then CAS-labels the physical CR
303+
with the logical Sandbox ID before gateway activation. Reservation and retirement
304+
compete on the gateway assignment version. Retirement must win before it marks or
305+
deletes the CR; a committed reservation excludes that runtime from pool maintenance.
306+
After reservation an error never falls back to a second runtime.
305307
Activation atomically replaces the proposed cold identity with the physical
306-
binding and canonical credentials. The canonical registration is persisted under
307-
the logical Sandbox's generation Secret name for existing recovery. Reconciliation
308-
finishes interrupted claims. Restart uses a new generation and updates the Pod's
309-
pair label; the original physical CR name remains unchanged.
308+
binding and canonical credentials. Intent and committed material live in the
309+
existing gateway credential store, with references in gateway assignment records.
310+
The CR stores only the intent's route. A link on the logical launch selects one
311+
intent before CR binding; retries resolve it before considering cold creation,
312+
even when pooling has been disabled. Reconciliation discovers pending claims from
313+
gateway records even before CR binding. It cancels unactivated claims whose launch
314+
ends, times out, or loses its physical runtime. Cancellation fences activation and
315+
leaves a terminal launch decision; a delayed CR binding is collected using the
316+
retirement tombstone. Recovery never falls back to workspace Secret reads. Retirement
317+
fences delayed writers before collecting their credential material. Restart uses
318+
a new generation and updates the Pod's pair label; the original physical CR name remains unchanged.
319+
320+
Development deployments using the earlier Secret-backed claim format must finish
321+
pending claims with that gateway before upgrading. The driver rejects those
322+
references explicitly; it does not read legacy claim Secrets or discard a
323+
potentially activated workload.
310324

311325
The focused gateway-backed claim E2E uses fresh branch images and checks physical
312-
Pod reuse, refill, exec, and stop/start with a new identity:
326+
Pod reuse, gateway restart recovery before and after claiming, refill, exec,
327+
stop/start with a new identity, and draining without workspace Secret reads:
313328

314329
```shell
315330
OPENSHELL_E2E_KUBE_TLS=1 \
@@ -318,6 +333,12 @@ e2e/with-kube-gateway.sh cargo test --manifest-path e2e/rust/Cargo.toml \
318333
--features e2e-kubernetes-shared-supervisor --test kubernetes_warm_pool -- --ignored --nocapture
319334
```
320335

336+
Add `ci/values-workspace-managed.yaml` to the values list to exercise managed
337+
namespaces and generation image-pull copies. For operator workspaces, add
338+
`ci/values-workspace-operator.yaml` and set `OPENSHELL_E2E_WARM_OPERATOR=1`; the
339+
test installs the workspace chart in the test cluster's default namespace.
340+
Omit `ci/values-supervisor.yaml` to test dedicated supervisors.
341+
321342
The Kubernetes API integration test exercises real Sandbox CRD defaulting, Pod
322343
creation, Secret ownership, gate release, journal recovery and conditional
323344
retirement. It uses an

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

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1382,9 +1382,7 @@ impl KubernetesComputeDriver {
13821382
.as_ref()
13831383
.is_some_and(|labels| labels.contains_key("openshell.ai/warm-pool"))
13841384
{
1385-
return Err(tonic::Status::permission_denied(
1386-
"unclaimed supervisors may only register",
1387-
));
1385+
warm_pool::validate_restarted_supervisor(&pod, &sandbox, &self.config.gateway_id)?;
13881386
}
13891387
require_proxy_control_authentication(via_proxy_control)?;
13901388
let resource_uid = sandbox
@@ -5442,6 +5440,7 @@ impl KubernetesComputeDriver {
54425440
namespace,
54435441
sandbox_id,
54445442
generation,
5443+
warm: warm_pool::requires_gateway_recovery(object),
54455444
},
54465445
})
54475446
})
@@ -5463,6 +5462,13 @@ impl KubernetesComputeDriver {
54635462
&self,
54645463
record: SharedInstanceSecretRecord,
54655464
) -> Result<Option<Vec<u8>>, KubernetesDriverError> {
5465+
if record.warm {
5466+
// Warm claims are committed to gateway storage before completion.
5467+
// Missing gateway state is an error, never a workspace Secret fallback.
5468+
return Err(KubernetesDriverError::Precondition(
5469+
"warm runtime assignment is missing from gateway persistence".into(),
5470+
));
5471+
}
54665472
let names = SandboxRuntimeNames::for_generation(&record.sandbox_id, &record.generation);
54675473
let secrets = Api::<Secret>::namespaced(self.client.clone(), &record.namespace);
54685474
let secret =
@@ -5510,7 +5516,7 @@ impl KubernetesComputeDriver {
55105516
}
55115517
if let Err(error) = self
55125518
.delete_sandbox_runtime_supervisor(
5513-
sandbox_id,
5519+
&warm_pool::physical_resource_id(object, sandbox_id),
55145520
namespace,
55155521
sandbox_runtime_generation(object).as_slice(),
55165522
)
@@ -6038,6 +6044,7 @@ struct SharedInstanceSecretRecord {
60386044
namespace: String,
60396045
sandbox_id: String,
60406046
generation: String,
6047+
warm: bool,
60416048
}
60426049

60436050
/// Launch material of one shared-supervisor sandbox instance, taken from the
@@ -7094,8 +7101,15 @@ async fn generation_control_availability(
70947101
.await
70957102
}
70967103
Ok(SupervisorPlacement::Shared { route }) => {
7097-
shared_instance_control_availability(client, shared, namespace, sandbox_id, &route)
7098-
.await
7104+
shared_instance_control_availability(
7105+
client,
7106+
shared,
7107+
namespace,
7108+
sandbox_id,
7109+
&warm_pool::physical_resource_id(object, sandbox_id),
7110+
&route,
7111+
)
7112+
.await
70997113
}
71007114
Err(error) => {
71017115
warn!(sandbox_id, %error, "sandbox-runtime supervisor placement is invalid");
@@ -7112,6 +7126,7 @@ async fn shared_instance_control_availability(
71127126
shared: Option<&SharedSupervisor>,
71137127
namespace: &str,
71147128
sandbox_id: &str,
7129+
physical_id: &str,
71157130
route: &str,
71167131
) -> SandboxRuntimeControlAvailability {
71177132
let Some(shared) = shared else {
@@ -7121,7 +7136,7 @@ async fn shared_instance_control_availability(
71217136
);
71227137
return SandboxRuntimeControlAvailability::Unavailable;
71237138
};
7124-
let names = SandboxRuntimeNames::new(sandbox_id);
7139+
let names = SandboxRuntimeNames::new(physical_id);
71257140
let policies = Api::<NetworkPolicy>::namespaced(client.clone(), namespace);
71267141
let exists = |result: Result<Result<Option<NetworkPolicy>, KubeError>, _>, what: &str| {
71277142
match result {

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

Lines changed: 31 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use kube::api::{ObjectMeta, PostParams};
1818
use openshell_core::SandboxSessionId;
1919
use openshell_isolation_interface::contract::BackendError;
2020
use openshell_sandbox_backend::boundary_protocol::{
21-
BoundaryConfig, BoundaryListener, SandboxTlsClientConfig, SandboxTlsMaterial, SandboxTransport,
21+
BoundaryListener, SandboxTlsClientConfig, SandboxTlsMaterial, SandboxTransport,
2222
generate_sandbox_tls_material,
2323
};
2424
use openshell_supervisor_control::{
@@ -53,69 +53,51 @@ pub struct PreparedRuntimeBootstrap {
5353
}
5454

5555
impl PreparedRuntimeBootstrap {
56-
/// Persist (or recover) per-Pod bootstrap material, then reserve host capacity.
57-
///
58-
/// `provision` builds both protocol endpoints using the supplied TLS pin and
59-
/// freshly verified Kubernetes resource coordinates. It must be deterministic
60-
/// for those inputs and call `provision_prepared`. After a concurrent Secret
61-
/// creation it may be called again with the winner's pin.
62-
///
63-
/// This operation never removes the Pod's gate. Retry with the same coordinates: an API
64-
/// timeout may have committed either the Secret or the reservation. Never
65-
/// delete material or withdraw a route unconditionally on an error. Only the
66-
/// controller may release the gate, after revalidating the current Pod UID,
67-
/// admission and fences. The returned registration contains no private key.
68-
pub async fn prepare<F>(
56+
/// Complete all bootstrap writes before recording the public preparation.
57+
/// A completed preparation needs no Secret reads. An incomplete attempt is
58+
/// disposable: conflicts and ambiguous creates must never adopt another key.
59+
pub async fn prepare<F, C, Fut>(
6960
&self,
7061
client: kube::Client,
7162
supervision: &SharedSupervision,
7263
provision: F,
64+
complete: C,
7365
) -> Result<PreparedRuntimeRegistration, KubernetesDriverError>
7466
where
7567
F: Fn(
7668
SandboxTlsClientConfig,
7769
) -> Result<KubernetesSandboxRuntimeBoundaryProvisioning, BackendError>,
70+
C: FnOnce(PreparedRuntimeRegistration) -> Fut,
71+
Fut: Future<Output = Result<(), KubernetesDriverError>>,
7872
{
7973
self.validate()?;
80-
let secrets = Api::<Secret>::namespaced(client, &self.namespace);
81-
let secret = if let Some(secret) = secrets
82-
.get_opt(&self.secret_name)
74+
let route = format!("rt-{}", self.session_id);
75+
if let Some(assignment) = supervision
76+
.runtime_assignment(&self.workspace, &route)
8377
.await
84-
.map_err(KubernetesDriverError::from_kube)?
78+
.map_err(KubernetesDriverError::Precondition)?
8579
{
86-
secret
87-
} else {
88-
let material = generate_sandbox_tls_material(self.session_id).map_err(backend_error)?;
89-
let provisioning = provision(tls_pin(&material)).map_err(backend_error)?;
90-
let request = self.request(&provisioning)?;
91-
let candidate = self.secret(&provisioning, &request.registration, material)?;
92-
match secrets.create(&PostParams::default(), &candidate).await {
93-
Ok(secret) => secret,
94-
// Another replica won. Its key is authoritative; never replace it.
95-
Err(kube::Error::Api(error)) if error.code == 409 => secrets
96-
.get(&self.secret_name)
97-
.await
98-
.map_err(KubernetesDriverError::from_kube)?,
99-
Err(error) => return Err(KubernetesDriverError::from_kube(error)),
80+
let registration = PreparedRuntimeRegistration::from_assignment(&assignment)
81+
.map_err(|_| invalid("runtime is no longer an unclaimed preparation"))?;
82+
let expected =
83+
provision(registration.runtime_descriptor.tls.clone()).map_err(backend_error)?;
84+
if self.request(&expected)?.registration != registration {
85+
return Err(invalid(
86+
"prepared bootstrap no longer matches observed runtime coordinates",
87+
));
10088
}
101-
};
102-
let registration = self.read_registration(&secret)?;
103-
let expected =
104-
provision(registration.runtime_descriptor.tls.clone()).map_err(backend_error)?;
105-
let request = self.request(&expected)?;
106-
let stored_config: BoundaryConfig =
107-
serde_json::from_slice(secret_value(&secret, BOUNDARY_CONFIG_KEY)?)
108-
.map_err(|_| invalid("invalid prepared boundary configuration"))?;
109-
if request.registration != registration
110-
|| serde_json::to_value(stored_config)
111-
.map_err(|_| invalid("invalid boundary configuration"))?
112-
!= serde_json::to_value(&expected.boundary_config)
113-
.map_err(|_| invalid("invalid boundary configuration"))?
114-
{
115-
return Err(invalid(
116-
"prepared bootstrap no longer matches observed runtime coordinates",
117-
));
89+
return Ok(registration);
11890
}
91+
let material = generate_sandbox_tls_material(self.session_id).map_err(backend_error)?;
92+
let provisioning = provision(tls_pin(&material)).map_err(backend_error)?;
93+
let request = self.request(&provisioning)?;
94+
let candidate = self.secret(&provisioning, &request.registration, material)?;
95+
Api::<Secret>::namespaced(client, &self.namespace)
96+
.create(&PostParams::default(), &candidate)
97+
.await
98+
.map_err(KubernetesDriverError::from_kube)?;
99+
complete(request.registration.clone()).await?;
100+
let registration = request.registration.clone();
119101
supervision
120102
.prepare(request)
121103
.await

0 commit comments

Comments
 (0)