Skip to content

feat(kubernetes): add template-driven sandbox warm pools - #5518

Open
grs wants to merge 18 commits into
ai-openshell:mainfrom
grs:warm-pooling-2
Open

grs wants to merge 18 commits into
ai-openshell:mainfrom
grs:warm-pooling-2

Conversation

@grs

@grs grs commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Summary

Add template-driven warm pooling for Kubernetes sandboxes with dedicated or shared supervisors. Prepared runtimes wait for a claim, then receive their sandbox identity and credentials over existing supervisor connections, avoiding cold startup and claim-time Secret projection delays.

Related Issue

Closes #2157

Changes

  • Derive warm pools from template startup tuning (ready_within and max_burst), with pooling enabled by default and operator-configurable limits.
  • Coordinate preparation, capacity reservation, claims, refill, and retirement through durable records shared across gateway replicas.
  • Hold dedicated supervisors’ asynchronous RegisterSupervisor responses until claim; deliver shared-supervisor claims through the existing assignment stream.
  • Preserve physical runtime identity and validate credentials before activation, without adding a runtime-to-gateway bootstrap connection.
  • Restrict claims to the originating template and drain unclaimed capacity when a template is deleted or pooling is disabled.
  • Update Helm permissions, configuration documentation, and lifecycle coverage.

Release Notes

Kubernetes sandbox templates can request warm capacity using --ready-within and --max-burst. Pooling supports dedicated and shared supervisors and creates no spares for templates without startup tuning. Sandbox creation falls back to cold provisioning when no compatible spare is available.

Testing

  • Checks appropriate to the affected code and behavior pass

  • Unit tests added/updated

  • E2E tests added/updated

  • Manual basic operation verified with both supervisor topologies.

Checklist

@copy-pr-bot

copy-pr-bot Bot commented Nov 12, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@grs
grs force-pushed the warm-pooling-2 branch 2 times, most recently from 7ad90b9 to 5bde8ea Compare November 16, 2026 16:19
@FrostGod

Copy link
Copy Markdown
Contributor

taking a look!

@FrostGod
FrostGod self-requested a review November 16, 2026 18:46
Comment thread crates/openshell-supervisor/src/main.rs Resolved
@grs
grs force-pushed the warm-pooling-2 branch 2 times, most recently from 4f8dd24 to 810e1e5 Compare November 19, 2026 22:17
@grs
grs requested a review from FrostGod November 19, 2026 22:18
grs added 12 commits November 23, 2026 08:54
Signed-off-by: Gordon Sim <gsim@redhat.com>
…ce Secret reads

Signed-off-by: Gordon Sim <gsim@redhat.com>
Fingerprint effective runtime inputs and retain compatible spares across
revision changes. Preserve cleanup during configuration mismatches and
persist drain decisions across replicas.

Update regression tests, operator guidance, and the stale packaging
driver-selection assertion.

Signed-off-by: Gordon Sim <gsim@redhat.com>
…fails

Signed-off-by: Gordon Sim <gsim@redhat.com>
Signed-off-by: Gordon Sim <gsim@redhat.com>
Signed-off-by: Gordon Sim <gsim@redhat.com>
Signed-off-by: Gordon Sim <gsim@redhat.com>
Signed-off-by: Gordon Sim <gsim@redhat.com>
Signed-off-by: Gordon Sim <gsim@redhat.com>
…nciliation

Signed-off-by: Gordon Sim <gsim@redhat.com>
Signed-off-by: Gordon Sim <gsim@redhat.com>
Signed-off-by: Gordon Sim <gsim@redhat.com>
- Add warm_pool.refill_per_pass (default 4, 1..=64) to replace the fixed
  per-pass refill and operation burst.
- Record whether a pool is suspended in the journal and report target,
  ready, pending, retiring, revision, and suspended through
  GetSandboxTemplate and `openshell sandbox template get`.
- Export openshell_warm_pool_claims_total{outcome},
  openshell_warm_pool_claim_duration_seconds{outcome},
  openshell_warm_pool_spares{state}, and
  openshell_warm_pool_suspended_pools.

Signed-off-by: divesh <dgude@nvidia.com>
Signed-off-by: divesh <dgude@nvidia.com>
Default warm_pool.enabled to false. A disabled reconciler drains only
pools that already have a journal and no longer writes journals for
templates that were never pooled. Once a disabled pass finds no
recorded pool, sandbox creates skip warm claim lookups and the cold
launch fence, so gateways that never enable pooling keep the existing
create path.

Signed-off-by: divesh <dgude@nvidia.com>
@FrostGod

FrostGod commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

@grs can you PTAL again, I have added the following things on top of this feature

  • Configurable refill rate: new warm_pool.refill_per_pass setting (default 4, range 1–64) replaces the hardcoded 4 spares per pass. Changing it doesn't need a revision bump.
  • Pool status in CLI and API: openshell sandbox template get <name> now shows a warm pool section with target, ready, pending, retiring, revision, and suspended. The same data is in -o json and GetSandboxTemplate.
  • Metrics:
    • openshell_warm_pool_claims_total{outcome=warm|cold|error}: warm hits vs cold fallbacks
    • openshell_warm_pool_claim_duration_seconds: claim latency
    • openshell_warm_pool_spares{state=ready|pending|retiring}: spare counts
    • openshell_warm_pool_suspended_pools: pools that can't refill
  • Pooling off by default: warm_pool.enabled now defaults to false. A disabled gateway only drains pools that already exist and doesn't create pool journals. Once it confirms no pools exist, sandbox creates skip warm-pool lookups and the cold-launch DB write.
  • Main merged in: the branch is up to date with main via a merge commit; existing commits are not rewritten.
  • Docs, tests, e2e: updated the gateway configuration, templates, and metrics docs, the driver README, and the debug-openshell-cluster skill. Added unit tests for status, metrics, refill pacing, and the disabled path. The warm-pool e2e now asserts pool status, and values-warm-pool.yaml sets enabled: true.

and @drew for viz

@grs grs left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

warm pool status in API/CLI

I don’t think the addition of warm-pool implementation status to GetSandboxTemplate and the associated CLI is the right approach. Templates were deliberately designed to express desired, observable startup characteristics without coupling them to a particular implementation such as warm pooling.

The proposed fields expose pool maintenance and gateway configuration details, but don’t tell the template user whether the requested startup characteristics are being achieved. They belong in operator-facing diagnostics and metrics, rather than the template API.

I’ would prefer this API/CLI addition to be removed from the PR. If we add template status later, it should report observed startup outcomes against the requested characteristics, independently of how the driver delivers them.

skipping warm-pool checks

The cached “no pools” result is local to a replica and can become stale during rolling enablement. Another replica could create a pool and reserve a warm runtime before the cache refreshes; if creation retries on the disabled replica before that runtime is bound to the sandbox, it would skip both claim recovery and the cold-launch fence, potentially creating a second runtime.

If we want to optimise out warm-pooling overhead where it is not needed, it would in my view be safer and more targeted to make those checks conditional on eligibility recorded for the sandbox launch. Launches that cannot use a warm pool could safely skip coordination, provided claim admission enforces that decision. Eligible launches would retain recovery and fencing across retries, even if pooling is subsequently disabled.

metrics

The capacity gauges and suspended-pools gauge look useful. A reconciliation success/error counter would complement them: suspension is a configuration state, while reconciliation can fail independently because of Kubernetes or database errors. That would also help identify incomplete capacity observations, since failed pool passes are omitted from the totals.

I’m less convinced we need claim duration at this stage. End-to-end startup latency split by warm/cold launch would better demonstrate the feature’s benefit; claim duration mainly helps diagnose one stage. I’d prefer to replace it with end-to-end startup latency, or remove it for now if that work is better deferred to a subsequent PR.

For the outcome counters, recording needs to happen after the cold-launch fence and any claim recovery complete—otherwise a recorded cold outcome can subsequently become warm or fail. We should also clarify which creates enter the counters, so the resulting warm-hit rate has a well-defined denominator.

Configurable warm pool refill

I’m not convinced that warm_pool.refill_per_pass should be exposed as configuration at this point. What operational problem would lead someone to change it, and what guidance would we give them for choosing a value? It controls several kinds of work per reconciliation pass, rather than a predictable refill rate, so its effect depends on implementation details and deployment size. I’d prefer to retain the internal limit unless we have a concrete need for tuning it and can offer meaningful guidance. Making a constant configurable creates an interface we then need to support; it isn’t automatically an improvement.

Templates describe desired startup characteristics independent of how a
driver delivers them, so the template API should not expose warm-pool
maintenance state. Remove the SandboxTemplateWarmPoolStatus response
field, its CLI output, and the status-only journal flag. Operators keep
the same visibility through the openshell_warm_pool_* metrics.

Signed-off-by: divesh <dgude@nvidia.com>
Signed-off-by: divesh <dgude@nvidia.com>
@FrostGod

FrostGod commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

@grs Agreed, removed. GetSandboxTemplate and template get no longer return warm-pool status, and the status-only journal flag is gone. Operators keep visibility through the openshell_warm_pool_* metrics. I also merged latest main (c9c33d4) to clear the conflicts.

@FrostGod

Copy link
Copy Markdown
Contributor

/ok to test c9c33d4

@FrostGod
FrostGod requested a review from drew December 1, 2026 07:10
FrostGod
FrostGod previously approved these changes Dec 1, 2026

@FrostGod FrostGod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@FrostGod

FrostGod commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

just waiting for one another +1 review from @drew before merging

@grs

grs commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

LGTM

@drew drew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left inline comments on several bugs found during review, including a permanent pool-capacity leak/drain deadlock on short-lived claimed sandboxes, HA rolling-enablement suspension and split-brain races, dedicated tombstone sweep churn, shared-supervisor activation readiness issues, and a few smaller claim/metrics/supervisor edge cases.

})
.await
.map_err(KubernetesDriverError::Message)?
!= PreparationRelease::Released

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Permanent pool capacity leak & drain deadlock for short-lived claimed sandboxes: plan() only removes a claimed entry from state.entries while the claimed CR is still present in Kubernetes inventory (reconciler.rs:73-77). If a sandbox claims a spare and is deleted before the next 5s reconcile pass, the CR is gone so plan() marks the entry retiring = true, retire_preparation returns PreparationRelease::Changed (because the route was activated with !prepared / non-empty sandbox_id), and execute_warm_action returns early without removing the entry from warm_pool_journal. Meanwhile remove_retired_assignments (supervisor_pool/warm_pool.rs:170-172) refuses to collect the tombstone while its session_id is still referenced in warm_pool_journal. Each fast create+delete permanently consumes a max_size slot and blocks finish_drain on template deletion.

} else if pool.target_size == 0 {
// A same-revision disable is monotonic: enabled replicas cannot undo it.
let stored = state.policy.get_or_insert_with(|| desired_policy.clone());
stored.target_size = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rolling first-time enablement on HA gateways permanently suspends pools: Defaults are enabled = false, revision = 1, and disabled replicas run pools_to_reconcile every 5s. When an operator rolls out enabled = true (keeping the documented default revision = 1), the first new replica creates each template's journal at revision = 1, target_size = N. Before old enabled = false, revision = 1 replicas terminate, they discover the new journal (pools_to_reconcile lines 581-590) and commit policy.target_size = 0 at revision = 1 (permitted by is_drain_of). Once the rollout completes, every enabled replica sees state.policy.target_size (0) != desired_policy.target_size (N) at revision = 1 and stays permanently suspended until an operator manually bumps warm_pool.revision and redeploys.

.state
.entries
.retain(|entry| entry.session_id != action.entry.session_id || !entry.retiring);
supervision

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two smaller reconciler issues:

  1. Retirement CAS cooldown: reconcile_warm_pool_with_claims stamps last_attempt_at_ms = Some(now) (reconciler.rs:172) and runs up to refill_per_pass retirement actions concurrently (buffer_unordered, line 485). Concurrent tasks race on this update_warm_pool CAS and discard Ok(false), pushing losing retirements behind the 30s RETRY_MS cooldown.
  2. Steady-state writes & conflicted gauges: Every 5s pass updates last_ready_at_ms (reconciler.rs:89-91) and writes the journal unconditionally even when idle/disabled; on CAS conflict (reconciler.rs:465-469), report.pending/ready/retiring still reflect uncommitted plan() mutations and are fed into openshell_warm_pool_spares.

.select_warm_runtime(sandbox, namespace, &mut pooled)
.await;
if pooled {
record_claim(&selected, started.elapsed());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claim metrics misclassify fence errors and resumed warm claims as cold: record_claim runs before choose_cold_launch and resume_warm_claim (lines 76-86). If choose_cold_launch errors or returns a pending warm claim intent, openshell_warm_pool_claims_total records outcome="cold" instead of error or warm, and cold-fallback duration omits the choose_cold_launch round trip. Moving record_claim to the final outcome of try_claim_warm_runtime fixes both.

}
if self.warm_pools_inactive() {
return Ok(None);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale warm_pools_absent cache allows warm/cold split-brain during rolling enablement: warm_pools_inactive() relies on the 5s reconciler cache (warm_pools_absent), skipping both warm_claim_for_launch (line 136) and choose_cold_launch (line 72). During a rolling enablement, retries split across a disabled and an enabled replica can create both a cold Sandbox CR and a bound warm CR with the same openshell.ai/sandbox-id, causing subsequent lookups to fail with "multiple physical resources name the sandbox".

match result {
Ok(_) => Ok(intent),
Err(PersistenceError::Conflict { .. }) => {
let previous = self.warm_claim(workspace, route).await?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benign concurrent Sandbox updates during record_warm_claim fail creation instead of retrying: Unlike activate_runtime_attempt, choose_cold_launch, and cancel_warm_claim_inner, record_warm_claim has no CAS retry loop. If a concurrent Sandbox status update causes PersistenceError::Conflict, this assumes another claim won the assignment row and calls self.warm_claim(workspace, route) — which returns Err("warm claim is unavailable") because claim_handle is still empty, aborting CreateSandbox rather than retrying.

}
// Preparation and activation share an ownership term; an older
// PREPARED report cannot render a verdict on the new claim.
if assigned_revision.is_some_and(|revision| revision > status.applied_revision) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shared-supervisor warm activation lag / false Unavailable verdict, and Pending wedging on coalesced snapshots:

  1. SharedSupervision::activate() (coordinator.rs:745-747) omits controller.assign, and place_owner() (controller.rs:748) returns early because InstanceOwner does not distinguish prepared vs. activated ownership terms (pool.view.owners.get(route) == Some(&owner)). Until the next 2s reconcile_once pass (or during any keep_routes cycle), observed() returns the stale PREPARED report (sandbox_id = ""), so supervision() (coordinator.rs:931) returns InstanceSupervision::Unavailable instead of Degraded (causing wait_for_ready() to fail immediately).
  2. Moving assigned_revision > status.applied_revision unconditionally above the status.instances lookup interacts with run_session's snapshot deduplication (controller.rs:1244-1264): if a route is transiently dropped into keep_routes and restored identically before run_session sends, sent_revision advances without sending to the host, leaving observed() stuck in Pending until an unrelated route changes (and leaving the Some(revision) if revision > status.applied_revision arm on line 857 unreachable).

.as_mut()
.expect("metadata")
.annotations
.insert(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Template-based CreateSandbox with 128 caller annotations fails validation: WORKLOAD_TEMPLATE_ID_ANNOTATION is inserted before validate_object_metadata (line 781), whereas other gateway-internal annotations are written afterward. A valid request with MAX_METADATA_ANNOTATIONS_ENTRIES (128) user annotations now fails with INVALID_ARGUMENT (129 > 128). Inserting this after validate_object_metadata avoids the regression.

Comment thread crates/openshell-supervisor/src/main.rs Outdated
console_filter,
Arc::new(AtomicBool::new(false)),
);
Some(tracing::subscriber::with_default(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-claim warm supervisor diagnostics & startup edge cases:

  1. tracing::subscriber::with_default only binds the main thread on the multi-threaded Tokio runtime (main.rs:560), silently dropping RuntimeRouter accept/TLS-rejection warnings emitted on worker threads during warm waiting.
  2. validate_role_arguments(&args)? (main.rs:557) still requires unused --backend-descriptor-file and --auth-bundle-file flags when --warm-prepared-file is set.
  3. warm::wait_for_claim performs TLS before openshell_crypto::tls::ensure_default_provider() is called at line 674 (currently only works incidentally via prepared.validate()).

.register_supervisor(request)
.await?
.into_inner();
accepted.send_replace(true);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retry backoff never resets after stream acceptance: delay grows from 200ms to 10s on retryable errors, but is never reset back to 200ms when register_supervisor succeeds (accepted.send_replace(true)). If transient startup retries push delay to 10s, any later gateway rollout/disconnect stalls the first reconnect for 10s while the spare is unclaimable.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: add warm-pool provisioning for Kubernetes sandboxes

3 participants