Skip to content

Commit 47f009b

Browse files
committed
feat(kubernetes): warm pool support
Signed-off-by: Gordon Sim <gsim@redhat.com>
1 parent 5023061 commit 47f009b

74 files changed

Lines changed: 9247 additions & 1791 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎architecture/compute-runtimes.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,66 @@ credentials. The driver removes its scheduling gate only after the companions
401401
exist; measured confirmation and supervisor-session registration gate public
402402
readiness.
403403

404+
Kubernetes supervisor startup uses `RegisterSupervisor` before any tenant RPC.
405+
The driver validates the projected token, live proxy/workload Pods and Sandbox
406+
ownership, and returns the prepared runtime coordinates to the gateway. The
407+
driver requires Secret read permission in sandbox namespaces to validate the
408+
proxy descriptor and its owner UID during registration, plus list/delete
409+
permission for generation Secret cleanup during stop and rollback. The
410+
gateway checks the persisted runtime generation and delivers the operational
411+
authentication bundle and launch configuration. Proxy Secrets retain physical
412+
transport and proxy-CA material, but contain no operational auth bundle.
413+
414+
The workload listener can wait without a logical sandbox ID. Its first token
415+
must carry a signed binding matching all protected runtime resource claims;
416+
only then does it pin the logical sandbox identity. Later tokens must match that
417+
identity, generation and epoch. Transport retries preserve assignment and the
418+
existing agent-launch replay protection. Other compute drivers retain their
419+
file-provisioned authentication path.
420+
421+
Optional Kubernetes warm pooling uses the same provisioning path.
422+
The gateway periodically supplies complete template snapshots and public trust;
423+
the driver elects a controller using a Kubernetes Lease. Templates from unavailable
424+
operator workspaces are excluded without blocking snapshot refreshes for eligible
425+
workspaces. Template startup hints set desired spare capacity, bounded by a
426+
driver-wide spare-pair cap. Preparing and ready pairs count toward capacity.
427+
A Kubernetes Sandbox owns each pair and
428+
records its physical identity, preparation revision and state without a logical
429+
sandbox ID. Pool inventory selects managed resources by gateway and pool labels;
430+
it must not require the logical sandbox-ID label. Ordinary sandbox listing and lifecycle reconciliation exclude it.
431+
An immutable parent-owned Secret journals both bootstrap Secrets so interrupted
432+
preparation preserves TLS material. Recovery accepts an already released workload
433+
only when its recorded Pod, Service and network-policy identities still match;
434+
it requires the existing journal and validates both bootstrap Secrets before
435+
finishing release. Generation cleanup also removes this journal.
436+
The authentication generation is also used in Sandbox metadata and generation-scoped
437+
resource names, so allocation and proxy registration refer to the same runtime.
438+
439+
Standby readiness requires a local workload-listener probe, a live paired proxy
440+
with recent authenticated registration, the boundary Service and network fence.
441+
It does not mean the agent has started. The leader conditionally retires spare
442+
pairs when preparation stalls, standby age expires, templates or trust change,
443+
or pooling is disabled. Retirement competes with allocation through resource
444+
versions. Claimed resources remain under ordinary lifecycle management.
445+
446+
Template-based creation selects a compatible ready pair and persists its Sandbox
447+
UID and prepared generation in the logical record before attempting a conditional
448+
claim. The claim removes availability and records the logical ID and command on
449+
the parent Sandbox. Registration checks that parent UID against the persisted
450+
assignment before delivering credentials. Both Pods retain their physical identity;
451+
stop/start and cleanup derive companion names from that identity.
452+
453+
Uncertain claims remain pending against the same candidate across gateway restarts.
454+
Recovery fences a rejected, still-unassigned candidate before recording another;
455+
it adopts an already committed claim instead of retiring it. With no eligible
456+
candidate, creation uses the cold path. Readiness and terminal main-process results
457+
finalize claim recovery. Explicit restart also clears pending claim recovery
458+
atomically with the new provisioning attempt, retaining the physical assignment
459+
and its reservation so recovery cannot replace a restarting runtime's identity.
460+
Pending deletion fences allocation before removing the logical record. Assigned
461+
pairs are single-use and are deleted with the sandbox; template changes or removal
462+
retire only spare inventory.
463+
404464
## Images
405465

406466
The gateway image and Helm chart are built from this repository. Users supply

‎architecture/gateway.md‎

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ attachments; and asks compute runtimes to create or delete sandbox workloads.
77
## Responsibilities
88

99
- Authenticate clients and sandbox supervisor sessions.
10+
- Authorize Kubernetes proxy registration against driver-verified physical
11+
runtime identity and persisted logical assignment. `RegisterSupervisor`
12+
waits while a provisioning or starting runtime binding is being persisted,
13+
then requires an exact identity match. It supplies initial credentials; it
14+
does not bypass generation checks or recover a credential lineage that has
15+
already advanced through refresh.
1016
- Serve gRPC APIs for sandbox lifecycle, provider management, policy updates,
1117
settings, logs, watch streams, and relay forwarding.
1218
- Serve HTTP endpoints for health, WebSocket tunnels, and edge-auth flows.
@@ -316,19 +322,18 @@ identity inspection without client-side token decoding.
316322
Sandbox secrets are gateway-signed JWTs bound to a single sandbox ID. Docker,
317323
Podman, and VM drivers deliver the initial token through supervisor-only
318324
runtime material; Kubernetes supervisors exchange a projected ServiceAccount
319-
token through `IssueSandboxToken`. The gateway delegates that opaque credential
320-
to the selected compute driver's `AuthenticateSandbox` RPC. A capable driver
321-
returns the authenticated sandbox ID and an opaque runtime identity. The
322-
gateway requires both a matching durable sandbox record and the exact
323-
driver/runtime identity recorded at provisioning before returning the current
324-
generation-bound session JWT. Session authentication checks the durable runtime
325-
generation and token lineage for every sandbox RPC, so a replaced runtime and
326-
legacy unbound tokens cannot retain provider or control-plane access. The
327-
Kubernetes driver uses its own named configuration to run TokenReview and
328-
verify the live pod and controlling Sandbox CR. Its runtime identity binds the
329-
namespace, immutable Sandbox CR UID, and supervisor Pod UID. Restart preserves
330-
the namespace and CR UID, rejects ambiguous label matches, and rotates only the
331-
Pod-bound portion of the identity. The bootstrap path accepts
325+
token through `RegisterSupervisor` to receive their runtime assignment and
326+
in-memory authentication bundle. `IssueSandboxToken` remains available for
327+
existing bootstrap clients. The gateway delegates that opaque credential
328+
to the selected compute driver's `AuthenticateSandbox` RPC. The gateway requires
329+
a matching durable sandbox record and the exact driver/runtime assignment
330+
recorded at provisioning before returning operational credentials. Session
331+
authentication checks the durable runtime generation and token lineage for every
332+
sandbox RPC, so a replaced runtime and legacy unbound tokens cannot retain
333+
provider or control-plane access. The Kubernetes driver uses its own named
334+
configuration to run TokenReview and verify the live proxy Pod, workload Pod,
335+
and controlling Sandbox CR. The runtime assignment binds their immutable
336+
Kubernetes identities. The bootstrap path accepts
332337
both `agents.x-k8s.io/v1beta1` ownerReferences from newer Agent Sandbox
333338
controllers and `agents.x-k8s.io/v1alpha1` ownerReferences from existing
334339
deployments. Supervisors renew gateway JWTs in memory before expiry only while
@@ -470,6 +475,11 @@ The storage schema is intentionally narrow:
470475

471476
Public RPC contracts and durable protobuf formats have separate ownership. The `openshell.v1.OpenShell` service's request and response roots, streaming flags, and transitive message closure come from the public descriptor set generated by `openshell-core`. The `public_and_durable_schema_inventories_are_complete` test in `openshell-server` owns the counts and fingerprints and requires this inventory to be reviewed whenever it changes. Compute-driver, credential-driver, gateway-interceptor, and supervisor-middleware services are compiled contracts for internal extension boundaries.
472477

478+
`RegisterSupervisor` adds request and response messages to the public closure.
479+
Its assignment response carries initial runtime credentials but is not persisted
480+
as a protobuf storage root. Warm-pool selection and synchronization extend the
481+
internal compute-driver contract; neither changes the durable schema inventory.
482+
473483
`ReportEndpointStatus` is a sandbox-authenticated public gateway RPC. Its request, response, and `EndpointObservation` messages belong only to the public closure. `EndpointStatus` and `EndpointResult` also belong to the durable closure because `Sandbox.status.endpoint_statuses` persists them. The repeated status field uses a new wire tag; stored sandboxes without it decode with an empty endpoint list and retain their lifecycle fields. A fixed payload encoded with the earlier sandbox schema verifies that no database rewrite is required.
474484

475485
Allow and deny append requests carry `L7RuleTarget` to declare the rule, endpoint, and complete affected scope. The removed `host` and `port` fields remain reserved by number and name, and requests without a target are rejected. These mutation requests are not persisted formats.
@@ -621,6 +631,20 @@ revisions commit in one database transaction. SQLite serializes this operation
621631
with an immediate transaction, while Postgres locks the sandbox row. A failed
622632
resource-version check or revision insert rolls back the entire operation.
623633

634+
Warm allocation intent and its exclusive target reservation commit in one
635+
transaction. The `allocation_claims` table keys ownership by configured driver,
636+
namespace, and physical UID; the owner is a sandbox provisioning attempt and
637+
runtime generation. A uniqueness conflict rolls back the sandbox write and
638+
allows immediate selection of another target. Reservations have no TTL and
639+
survive ambiguous driver outcomes and gateway restart. Only fenced or reclaimed
640+
allocations release ownership; deleting the owning sandbox cascades its claims.
641+
The driver's resource CAS still arbitrates physical assignment and retirement.
642+
Creates with attached providers hold the gateway-wide sandbox lock from provider
643+
validation through the sandbox and reservation commit, including reservation
644+
retries. They release it before submitting creation to the driver. Allocation
645+
completion and recovery then acquire their own synchronization and lifecycle
646+
locks.
647+
624648
SQLite is the default local store; Postgres is supported for deployments that
625649
need an external database or multi-replica coordination. Both backends expose
626650
the same `Store` API and the same logical schema. Backend differences stay

‎architecture/sandbox.md‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,28 @@ A sandbox is the runtime boundary where agent code executes. A compute driver
44
creates it and connects two dedicated components: `openshell-sandbox` inside
55
the workload boundary and `openshell-supervisor` outside it.
66

7+
Kubernetes warm pooling is enabled by default, but only templates with startup
8+
hints request spare workload/supervisor pairs. The driver caps total unassigned
9+
inventory; operators can disable pooling through driver configuration or Helm.
10+
Each claimed pair belongs to one logical sandbox and is never returned to the pool.
11+
The gateway reserves each physical target in its database atomically with the
12+
logical allocation intent before sending a claim to the driver. Concurrent
13+
requests that lose the reservation immediately select another candidate without
14+
retiring the winner's pair. Create and recovery use bounded retries for definite
15+
claim rejection and persist each replacement before claiming it. Exhausted warm
16+
capacity falls back to cold creation in the same invocation. Uncertain claims
17+
retain their target and generation for idempotent recovery. If cold creation
18+
succeeds but its response is lost, recovery reads the driver-validated live
19+
runtime identity and persists that binding before completing the allocation.
20+
The Sandbox resource owns the assignment. Reconciliation copies its logical
21+
sandbox name and ID onto both Pods as display labels and updates their sandbox-ID
22+
annotations for SPIFFE identity. Physical pair selectors and registration
23+
bindings remain stable. A successful claim wakes
24+
registration waiters on the same gateway replica; polling durable state remains
25+
the fallback for other replicas and recovery. Every wake revalidates identity.
26+
Prepared pairs also carry template name and ID labels on their parent and both
27+
Pods. These display labels survive assignment and do not affect pool compatibility.
28+
729
## Runtime Model
830

931
Each sandbox has three trust levels:
@@ -27,6 +49,10 @@ TCP Service, or VM vsock channel. Independent bidirectional `Exchange` RPCs
2749
carry lifecycle, exec, TCP, and forwarding traffic, while one persistent
2850
bidirectional `Mediate` RPC carries multiplexed DNS traffic. General application
2951
UDP is unsupported; UDP DNS remains mediated by the supervisor.
52+
Boundary connection attempts bound transport establishment and TLS negotiation
53+
to two seconds per attempt within a 30-second retry window. The window also
54+
cancels an in-flight attempt at its deadline. Initial attachment can retry calls
55+
for up to five minutes while the workload boots.
3056
The sandbox probes HTTP/2 connection liveness every five seconds and closes
3157
connections that miss a ten-second acknowledgement deadline. Closing a
3258
connection freezes the owned workload process tree and cancels its stream
@@ -50,9 +76,13 @@ connections, including loopback aliases. Unix control listeners reject workload
5076
descendants using kernel peer credentials and process ancestry, while ordinary
5177
workload loopback and Unix services remain available.
5278
NetworkPolicy is an outer reachability fence, not a confidentiality boundary.
53-
Each sandbox generation receives a fresh CA and distinct server/client leaves;
54-
both endpoints bind the same workload identity and immutable driver resource
55-
claims. Driver crates do not appear in generic process, network, SSH, or
79+
Each sandbox generation receives a fresh CA and server certificate. The
80+
supervisor verifies server TLS; the workload authenticates the supervisor using
81+
a gateway-signed boundary JWT, not a TLS client certificate. Both endpoints bind
82+
the workload identity and immutable driver resource claims. Kubernetes can
83+
prepare the listener before logical assignment: the first JWT must also contain
84+
the exact protected resource binding before the workload accepts its sandbox ID.
85+
Driver crates do not appear in generic process, network, SSH, or
5686
session code.
5787

5888
The supervisor exposes readiness only after the sandbox is confirmed and the
@@ -688,6 +718,14 @@ A leader-owned scan runs independently of driver inventory. Expiry records
688718
`Error`/`ProvisioningTimedOut` before reclaiming compute; cleanup progress and
689719
backoff survive restart. Late runtime reports cannot replace that result. The
690720
record and restartable storage survive cleanup, including for ephemeral creates.
721+
Allocation recovery checks the same persisted deadline before retrying compute.
722+
Timeout cleanup retires an unclaimed warm candidate through the driver's claim
723+
CAS before acknowledging reclamation; a candidate already claimed by the sandbox
724+
uses normal stop semantics to retain storage. Cleanup clears allocation intent
725+
only after retirement and reclamation succeed. Late allocation results are fenced
726+
by provisioning attempt and runtime generation, and cannot rearm an expired
727+
attempt. Records with leftover allocation intent require cleanup even if an older
728+
gateway already recorded cleanup completion.
691729
Explicit start is blocked while cleanup is pending, then creates a fresh attempt
692730
using the latest configuration. Configuration edits alone never restart an
693731
expired sandbox. Legacy provisioning records receive one persisted rollout

‎crates/openshell-cli/tests/ensure_providers_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -698,6 +698,13 @@ impl OpenShell for TestOpenShell {
698698
Err(Status::unimplemented("not implemented in test"))
699699
}
700700

701+
async fn register_supervisor(
702+
&self,
703+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
704+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
705+
Err(Status::unimplemented("not implemented in test"))
706+
}
707+
701708
async fn issue_sandbox_token(
702709
&self,
703710
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-cli/tests/mtls_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,13 @@ impl OpenShell for TestOpenShell {
550550
Err(Status::unimplemented("not implemented in test"))
551551
}
552552

553+
async fn register_supervisor(
554+
&self,
555+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
556+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
557+
Err(Status::unimplemented("not implemented in test"))
558+
}
559+
553560
async fn issue_sandbox_token(
554561
&self,
555562
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-cli/tests/provider_commands_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1493,6 +1493,13 @@ impl OpenShell for TestOpenShell {
14931493
Err(Status::unimplemented("not implemented in test"))
14941494
}
14951495

1496+
async fn register_supervisor(
1497+
&self,
1498+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
1499+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
1500+
Err(Status::unimplemented("not implemented in test"))
1501+
}
1502+
14961503
async fn issue_sandbox_token(
14971504
&self,
14981505
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,6 +1009,13 @@ impl OpenShell for TestOpenShell {
10091009
Err(Status::unimplemented("not implemented in test"))
10101010
}
10111011

1012+
async fn register_supervisor(
1013+
&self,
1014+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
1015+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
1016+
Err(Status::unimplemented("not implemented in test"))
1017+
}
1018+
10121019
async fn issue_sandbox_token(
10131020
&self,
10141021
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-cli/tests/sandbox_name_fallback_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,13 @@ impl OpenShell for TestOpenShell {
641641
Err(Status::unimplemented("not implemented in test"))
642642
}
643643

644+
async fn register_supervisor(
645+
&self,
646+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
647+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
648+
Err(Status::unimplemented("not implemented in test"))
649+
}
650+
644651
async fn issue_sandbox_token(
645652
&self,
646653
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

0 commit comments

Comments
 (0)