Skip to content

fix(kubernetes): keep HA reconciliation from deleting a restarting supervisor - #6103

Open
matthewgrossman wants to merge 7 commits into
mainfrom
fix/5781-ha-restart-supervisor-race/matthewgrossman
Open

matthewgrossman wants to merge 7 commits into
mainfrom
fix/5781-ha-restart-supervisor-race/matthewgrossman

Conversation

@matthewgrossman

@matthewgrossman matthewgrossman commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR is an interim, driver-only fix for an HA restart flake. It stops the lease holder's runtime reconciliation from deleting a supervisor Pod that a restart on another replica has just created.

Investigating the flake turned up a broader set of races in HA lifecycle coordination between gateway replicas and the Kubernetes driver. The driver's per-sandbox lifecycle lock works only within one process. The driver's repair loop acts on its own read of the Sandbox CR, outside the order the gateway gives transitions. And stop/suspend requests carry nothing that says which action is newer. #6110 tracks the long-term fix: a gateway-issued lifecycle epoch that every driver write, child resource and cleanup is fenced against.

Until then, this PR has a restart claim the Sandbox CR before it creates the supervisor Pod, and has reconciliation respect that claim.

Related Issue

Fixes the IPv6 k3s-ha conformance flake seen while porting the restart test for #5781: cli::cli_stop_start_delete failed with start sandbox failed: sandbox not found right after Stopped (job). There is no closing issue. The long-term fix is #6110, which also replaces #6108 and #6109.

Root cause

Only the lease holder reconciles, but any replica serves lifecycle RPCs. Restart created the supervisor Pod os-supervisor-<id> while the CR still read as stopped. A reconciliation pass that had refreshed the stopped CR then deleted that Pod by its new UID. The restart's schedulingGates patch on the Pod got a 404, which from_kube reports as NotFound. In the failing run, the controller log shows the Running patch and the rollback 127 ms apart, and the holder's 30 s reconcile tick landed between them.

Changes

  • Restart claims the CR first. Restart writes a Preparing restart bootstrap before it creates the supervisor Pod, and Pod creation moved inside the rollback-guarded block. The later Running patch adds only the generation's bindings, so the bootstrap's grace clock starts once. One helper builds the claim annotations for create, stop and restart.
  • Reconciliation respects the claim. It dispatches on the bootstrap phase once, after resource admission. A Preparing bootstrap belongs to its lifecycle request, possibly on another replica, and is reaped only after the grace period. This also closes a second window: between the Running patch and install recording the fence bindings, reconciliation saw a fence mismatch and suspended the workload.
  • The namespace workload fence is still enforced during Preparing. It doesn't depend on the claim, so a deleted fence is restored and an altered one suspends the sandbox, as on main.
  • Safer stopped-supervisor cleanup. Reconciliation rereads the CR and skips the deletion if the CR changed after its refresh. The delete is pinned to the Pod's UID and errors if there is none, and the wait tracks that UID, so a replacement Pod with the same name neither gets deleted nor stalls reconciliation.
  • Docs. crates/openshell-driver-kubernetes/README.md describes how reconciliation respects the claim and what remains open. docs/how-it-works/gateways/configuration.mdx explains what runtime_bootstrap_grace_seconds defers.

Behaviour changes

  • While a bootstrap is Preparing, reconciliation defers the generation fence and control-path drift checks. Resource admission and the namespace workload fence still run. The workload Pod stays behind its scheduling gate throughout. The deferred checks resume when the bootstrap is released, or the bootstrap is reaped after the grace period (300 s by default).
  • A stale Preparing create is reaped (CR deleted) instead of first being suspended on a generation-fence mismatch. main already deleted stale creates without drift. A stale restart is still suspended.
  • The shared-control-policy exception for a missing policy during Preparing became unreachable and was removed.

Known gaps (tracked in #6110)

  • Lifecycle writes to the CR retry on resourceVersion conflicts without checking for another replica's transition. A restart can still overwrite a suspension the lease holder started (bug: HA lifecycle writes can overwrite a suspension started by another gateway replica #6108); here the sandbox is left Released with operation stop until the grace period reaps it.
  • Stop and suspend aren't fenced, so a late stop can tear down a newer start.
  • A reaped create disappears from the gateway, and the reason is only in the driver's log.

Testing

  • cargo test -p openshell-driver-kubernetes (346 passed), and cargo clippy -p openshell-driver-kubernetes --all-targets -- -D warnings is clean.

  • Unit tests added or updated. These fail against main's driver, or the previous commit, and pass here:

    • reconciliation_preserves_a_supervisor_another_replica_is_restarting and reconciliation_leaves_a_fresh_bootstrap_to_its_lifecycle_request reproduce both race windows.
    • reconciliation_reaps_a_stale_bootstrap checks that the freshness check, not an incidental read failure, prevents the writes.
    • reconciliation_enforces_the_namespace_fence_during_a_fresh_bootstrap checks that an altered namespace fence still suspends a Preparing sandbox.

    Also new or updated:

    • supervisor_deletion_does_not_wait_for_a_replacement_pod covers the UID wait.
    • reconciliation_deletes_the_supervisor_of_an_unchanged_stopped_sandbox covers normal cleanup.
  • E2E tests added/updated (if applicable): the race needs a reconcile tick inside a ~100 ms window, so there's no deterministic e2e repro. The k3s-ha conformance lanes exercise the path.

Checklist

  • Follows Conventional Commits
  • Commits are signed off (DCO)
  • Architecture docs updated (if applicable)

…pervisor

Only the lease holder reconciles sandbox runtimes, while any gateway
replica can serve a lifecycle RPC, so the driver's process-local
lifecycle gate does not exclude a restart on another replica. A
reconciliation that refreshed a stopped Sandbox could delete the
supervisor Pod the restart had just created under the same name, and the
restart then failed with "sandbox not found" when it ungated that Pod.
Reconciliation could also suspend a bootstrap whose fence bindings the
lifecycle request had not recorded yet.

Restart now marks the Sandbox Preparing before it creates the
supervisor Pod. Reconciliation leaves a fresh Preparing bootstrap to its
request until the bootstrap grace period expires, and rereads the
Sandbox before deleting a stopped sandbox's supervisor Pod, skipping the
deletion if the Sandbox changed.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
@matthewgrossman matthewgrossman added area:drivers Compute and secret drivers, host OS/architecture support, backend isolation, and lifecycle. topic:kubernetes Kubernetes operators, CRDs, deployment controllers, and native Kubernetes API integration. topic:reliability High availability, recovery, retries, graceful degradation, and correctness across restarts. labels Nov 30, 2026
@github-actions github-actions Bot added the state:accepted A maintainer decided OpenShell should pursue this issue label Nov 30, 2026
TaylorMutch
TaylorMutch previously approved these changes Nov 30, 2026
Address review of the HA restart race fix:

- Dispatch on the bootstrap phase once, after resource admission. A
  Preparing bootstrap is left to its lifecycle request and only reaped
  once stale, so the shared-control-policy exception for Preparing is
  no longer reachable and is removed.
- Build bootstrap claim annotations in one helper for create, stop and
  restart. The restart Running patch no longer rewrites the claim or
  resets its grace clock.
- Return unit from supervisor reconciliation; later writes are already
  pinned to the Sandbox resourceVersion.
- Wait for the deleted supervisor Pod by UID so a replacement Pod with
  the same name does not stall reconciliation.
- Share test fixtures and cover stale-bootstrap reaping and the UID wait.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
@matthewgrossman
matthewgrossman force-pushed the fix/5781-ha-restart-supervisor-race/matthewgrossman branch from 54af099 to 447f041 Compare December 1, 2026 00:08
…write race

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
The reconcile loop already has the Sandbox CR name, so take it from the
caller instead of re-deriving it from the object. Document that the
resourceVersion check before the UID-preconditioned Pod delete is best
effort, not atomic.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
TaylorMutch
TaylorMutch 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.

  • Skipping fence and control-path drift checks for up to 300 s during Preparing is a real tradeoff for a security boundary. Can we call it out in the user docs, or use a shorter window for restarts?
  • A stale create now deletes the CR instead of suspending it, so from the user's side the sandbox just disappears. Is the reason surfaced anywhere besides the warn! log?

// not cover requests served by other replicas. Mark the Sandbox
// Preparing before creating the supervisor Pod so reconciliation
// that refreshed the stopped Sandbox cannot delete the new Pod.
patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| {

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.

This goes through the resourceVersion retry, so on a conflict it reclaims without checking whether the lease holder just moved the CR to Suspending/Releasing. I know that's #6108; could we leave a TODO(#6108) here so it's easy to find?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added in f5daf8b: the retry is now marked TODO(#6108).

For context, we now plan to fix this in a different way from #6109. The idea is a lifecycle epoch issued by the gateway and fenced on every CR write, instead of claim compare-and-swap. #6109 is on hold until that's written up.

Comment on lines +5699 to +5711
if let Some(pod) = pods
.get_opt(&names.supervisor_pod)
.await
.map_err(KubernetesDriverError::from_kube)?
{
let current = sandbox_api
.get_opt(cr_name)
.await
.map_err(KubernetesDriverError::from_kube)?;
let unchanged = current.is_some_and(|current| {
current.metadata.uid == object.metadata.uid
&& current.metadata.resource_version == object.metadata.resource_version
});

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.

The order matters here: Pod read first, then the CR reread. Swapping them quietly brings the race back, so maybe add a line to the doc comment saying not to reorder them.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in f5daf8b. The doc comment now says to keep the Pod read before the Sandbox reread, and why.

This ordering rule is part of the stopgap. With the epoch design, the delete checks the Pod's own epoch label under a UID and resourceVersion precondition, so the ordering no longer matters.

.get_opt(&name)
.await
.map_err(KubernetesDriverError::from_kube)?;
if current.is_none_or(|current| current.metadata.uid != uid) {

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.

Low priority: if uid were None, current.metadata.uid != uid would be false and this would spin until the timeout. Can that actually happen here, given the API server always sets a UID on stored Pods?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It can't happen for a Pod we read from the API server, but I didn't want correctness to depend on that. In ca8e42f, delete_supervisor_pod_and_wait returns an error if the Pod has no name or UID. The delete is now always UID-preconditioned, and the wait compares against a concrete UID, so it can no longer spin.

let (driver, requests) =
other_replica_driver(version, vec![fresh_claim(version, operation)]);
driver.reconcile_sandbox_runtime_resources().await;
assert_eq!(mutations(&requests), vec![], "{version} {operation}");

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.

The fixture 404s anything it doesn't model (L410), so zero mutations could also mean reconcile bailed early. The first test asserts the two Sandbox GETs; can we assert this one got as far as the Preparing arm too?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch. In f5daf8b, the fresh-claim test runs the same claim a second time with a stale timestamp. It checks that the stale run makes exactly the same requests and then one write. So the fresh run must have reached the Preparing arm and stopped only because the claim was fresh, not on a request the fixture doesn't model.

Without a UID the delete precondition was empty, so the delete could
remove a replacement Pod created under the same name, and the wait
returned immediately. A Pod read from the API server always has a name
and UID, so treat a missing one as an error.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
…hecks

- Mark the blind restart claim retry with TODO(#6108).
- Note that the stopped-supervisor cleanup must read the Pod before
  rereading the Sandbox.
- State in the README that drift checks are deferred while a claim
  holds and that the workload Pod stays gated until release.
- Assert that the fresh-claim test reaches the Preparing arm by
  comparing its requests with the stale claim's.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
The Preparing arm skipped create_sandbox_runtime_fence, which main ran
for every phase before bootstrap dispatch. The namespace fence does not
depend on the bootstrap claim, so a deleted or altered fence went
unrestored for up to the bootstrap grace period while the supervisor
Pod ran. Check it before deferring to the claim holder, and document
what the grace period defers.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

@matthewgrossman

Copy link
Copy Markdown
Member Author

Thanks for the review. Replies to the two general points:

The 300 s without drift checks during Preparing. You were right, and the gap was bigger than the docs said: the Preparing arm also skipped create_sandbox_runtime_fence, which main ran for every phase. 1d9fc74 makes it run for Preparing too, so a deleted namespace fence is restored and an altered one suspends the sandbox, as on main. A new test covers this: reconciliation_enforces_the_namespace_fence_during_a_fresh_bootstrap. The checks that stay deferred are the per-generation fence and control-path checks. They can't pass until the lifecycle request records its bindings, and running them early is the false suspension this PR fixes. The workload Pod stays behind its scheduling gate the whole time. configuration.mdx now documents this under runtime_bootstrap_grace_seconds.

I didn't add a shorter window for restarts. A restart does the same Pod scheduling and image pulls as a create, so a shorter grace period would reap slow restarts that are still running. The longer-term fix (an epoch issued by the gateway and fenced in the driver) lets every drift check run in every phase, because a drift suspension then races the start's final write through a single compare-and-swap. I'll link the RFC or issue here once it's filed.

A stale create's CR is deleted. That isn't new in this PR: main already deleted a stale fail-closed create (rolled back stale fail-closed sandbox-runtime bootstrap). The only change is the case where main would first have suspended on a generation-fence mismatch. But you're right that it isn't surfaced. The Kubernetes create_sandbox returns while the CR is still bootstrapping, so by the time the driver reaps the create at 300 s, the gateway has already cleared driver_operation_pending. Its start deadline (image_preparation_timeout_seconds, 1800 s by default) hasn't expired either. So apply_deleted removes the sandbox record, and the only trace is the driver's warn!. The mismatch between the two defaults also means the driver can reap a slow create that the gateway would still allow. I'd rather fix both in a follow-up than here: record the reap reason on the sandbox and keep the record in Error, and line up the two windows. OK with that?

@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

/ok to test 1d9fc74

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

area:drivers Compute and secret drivers, host OS/architecture support, backend isolation, and lifecycle. state:accepted A maintainer decided OpenShell should pursue this issue topic:kubernetes Kubernetes operators, CRDs, deployment controllers, and native Kubernetes API integration. topic:reliability High availability, recovery, retries, graceful degradation, and correctness across restarts.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants