Skip to content

[Bug]: Kubernetes sandbox deletes its SandboxClaim on every call, breaking resume and adding a 30s stall #4251

Open

Description

@iluv7

Describe the bug

The Kubernetes sandbox backend deletes its SandboxClaim at the end of every agent call, and only then persists the claimName into SandboxState. On the next call, resume() tries to reattach to a claim that no longer exists. K8sHelper.resolveSandboxName() sees a null GET result and waits in a watch for the full 30-second resolution timeout before SandboxManager falls back to creating a fresh sandbox.

For a harness-managed Kubernetes sandbox with persisted state, this means:

  • cross-call warm resume never succeeds;
  • every call after the first stalls for ~30 seconds;
  • the PVC-based warm recovery documented in docs/dev/en/docs/harness/sandbox.md is unreachable;
  • a new claim/Sandbox/PVC is created on every call, while the state store keeps pointing at the dead claim until the next successful create overwrites it.

This also makes the shutdownAfterSeconds(...) claim lifetime added in #4170 ineffective for normal use: a claim that is deleted on every release never reaches its configured expiry.

To Reproduce

Prerequisites:

  • a Kubernetes cluster with agent-sandbox CRDs and a SandboxWarmPool named my-pool;
  • a SandboxTemplate whose volumeClaimTemplates mounts /workspace;
  • a HarnessAgent with the Kubernetes filesystem spec and a persisted AgentStateStore.
HarnessAgent agent = HarnessAgent.builder()
    .name("code-agent")
    .model(model)
    .workspace(workspace)
    .filesystem(new KubernetesFilesystemSpec()
        .namespace("default")
        .warmPoolName("my-pool")
        .isolationScope(IsolationScope.SESSION))
    .build();

RuntimeContext ctx = RuntimeContext.builder()
    .userId("alice")
    .sessionId("conv-1")
    .build();

agent.call(msg1, ctx).block(); // creates claim as-sbx-..., then deletes it during release
agent.call(msg2, ctx).block(); // resume(getSandbox(claimName)) -> 30s timeout -> creates another claim

Steps:

  1. Run the first call().
  2. During the call, kubectl get sandboxclaim -n default shows as-sbx-....
  3. After the call, the same claim is gone, but the persisted SandboxState still contains its claimName.
  4. Run the second call() and observe a ~30 second gap before a new claim appears.

Expected behavior

The claim should be treated consistently as either:

  1. a cross-call identity/lease (the behavior documented in sandbox.md): the claim from call 1 remains alive, and call 2 reconnects to the same Sandbox/PVC without a 30-second wait; or
  2. a per-call ephemeral resource: the state must not persist the deleted claimName, and call 2 should cold-create immediately without attempting resume.

In neither case should the next call wait for a claim that is already known to be gone.

Error messages

The resume failure is logged by SandboxManager and wrapped by KubernetesSandboxClient.resume():

WARN  [sandbox] Failed to load persisted state for scope
SandboxIsolationKey{scope=SESSION, value='conv-1'}, falling through to fresh create:
Failed to resume agent-sandbox client: Sandbox claim 'as-sbx-...' not found or
resolution failed in namespace 'default': Timed out waiting for sandbox name
resolution for claim: as-sbx-...

A stack trace is included because SandboxManager logs the caught exception at WARN.

Environment

  • AgentScope-Java Version: 2.1.0-SNAPSHOT (upstream/main c1d482900)
  • Java Version: 17
  • OS: macOS / Linux
  • Kubernetes: agent-sandbox extensions.agents.x-k8s.io/v1beta1
  • fabric8 Kubernetes Client: 7.8.0

Additional context

Current logic

The relevant sequence is:

// SandboxLifecycleMiddleware.releaseForCall()
sandboxManager.release(result);        // stop() + shutdown()
sandboxManager.persistState(...);      // persists the claimName after shutdown deleted it
// SandboxManager.release()
sandbox.stop();                        // persist workspace snapshot
sandbox.shutdown();                    // for K8s: terminate() -> delete claim
// KubernetesSandbox.shutdown()
if (!k8sState.isClaimOwned()) {
    sdkSandbox.closeConnection();
    return;
}
sdkSandbox.terminate();                // closeConnection() + deleteSandboxClaim()
// Sandbox.terminate()
closeConnection();
k8sHelper.deleteSandboxClaim(claimName, namespace);

The next call follows:

// KubernetesSandboxClient.resume()
SandboxClient sdkClient = buildSdkClient(merged);
sdkClient.getSandbox(k8s.getClaimName(), k8s.getNamespace()); // default 30s resolve timeout
// K8sHelper.resolveSandboxName()
SandboxClaim current = ...withName(claimName).get();
if (current != null) {
    ...
    return resolved;
}
// current == null is NOT treated as not-found; a watch is started instead:
try (Watch watch = ...watch(...)) {
    return future.get(timeoutSeconds, TimeUnit.SECONDS); // waits 30s for an absent object
}

Relevant locations:

  • SandboxLifecycleMiddleware.java:281 — release before persist
  • SandboxManager.java:201 — stop() then shutdown()
  • KubernetesSandbox.java:66 — shutdown() deletes the claim
  • SandboxClient.java:184 — getSandbox default 30s
  • K8sHelper.java:224 — null GET falls through to watch
  • KubernetesSandboxClient.java:150 — resume() calls getSandbox

claimOwned is initialized to true in KubernetesSandboxState and is set to true on create; it is never set to false on resume, so the “not owned” branch in shutdown() is effectively dead for harness-created claims.

Inconsistency with the documented contract

docs/dev/en/docs/harness/sandbox.md describes the claim as the identity layer, not a per-call disposable resource:

SandboxState + snapshotSpec (Harness layer) | identity pointer (claimName / namespace) + workspace tarball snapshot | locating the sandbox on resume (always required); cold recovery when the claim was deleted / PVC lost / cross-cluster

Mind the claim lifecycle boundary. Once shutdownTime / shutdownPolicy: Delete removes the Sandbox, PVC-based warm recovery is over — the next resume won't find the claim, and the framework creates a fresh sandbox (with an empty new PVC).

PVC + NoopSnapshotSpec (default): skips the tar-and-upload at the end of every call, at the cost of a cold start once the claim is gone.

The docs assume the claim survives normal calls; only an external expiry/delete ends warm recovery. The current code ends it on every release, which contradicts the documented workflow and makes the default NoopSnapshotSpec paragraph misleading.

This also conflicts with the isolation-scope model: the state slot is keyed by SESSION / USER / AGENT / GLOBAL, so the claim should live for the same scope, not for a single call. Under the default USER scope, one claim is supposed to serve multiple sessions of the same user.

Proposed fix

Step 1 — make “claim missing” fail fast (low risk, immediately removes the 30s stall).

  • In K8sHelper.resolveSandboxName, if the initial GET returns null, throw SandboxNotFoundException immediately instead of starting a watch.
  • Preserve the distinction between “not found” and transient errors; do not wrap every failure as SandboxNotFoundException.
  • In SandboxManager, only fall through to create after a fast, typed not-found; log at INFO/DEBUG rather than WARN-with-stack for the expected “claim expired” case.

Step 2 — align the claim lifecycle with the documented model (recommended option).

Split “release this call” from “destroy this sandbox”:

  • KubernetesSandbox.stop(): persist the workspace/snapshot, keep the claim.
  • KubernetesSandbox.shutdown(): close the client/port-forward only; do not call terminate().
  • Add an explicit destroy path (e.g. implement the existing SandboxClient.delete(Sandbox) for K8s, and call it from SandboxManager/HarnessAgent.close() or a filesystem close hook) that deletes the claim exactly once.

Use agent-sandbox lifecycle as a safety net, not as the primary release mechanism:

  • set spec.lifecycle.shutdownTime from a configurable idle TTL (e.g. claimIdleTtlSeconds);
  • use shutdownPolicy: Delete;
  • extend shutdownTime explicitly on each acquire/release if a session stays active longer than the TTL (it is an absolute deadline and is not auto-renewed by activity);
  • ensure the TTL is longer than the longest single call, or extend the claim before long-running work.

Step 3 — make the state consistent after expiry/deletion.

  • If resume fails because the claim is gone/expired, cold-create and overwrite the persisted state without the 30s delay.
  • Treat Retain-expired claims (Ready=False, underlying Sandbox deleted) as not resumable; they are not “warm”.
  • Consider clearing claimName when the claim is known dead, so the next acquire does not retry a dead identity.

Step 4 — regression tests.

  • Unit: K8sHelper.resolveSandboxName with a null GET returns SandboxNotFoundException without starting a watch and without waiting 30s.
  • Integration: two consecutive call()s with the same (userId, sessionId) reuse the same claimName; the claim is not deleted after the first call; no 30s gap.
  • Lifecycle: explicit destroy deletes the claim once; shutdown() alone does not delete it.
  • Expiry: a claim deleted/expired between calls leads to a fast cold start, not a watch timeout.
  • TTL: an active call longer than the TTL either extends the claim or fails with a clear error, never silently loses the sandbox mid-call.

Related defects

The same missing ownership tracking causes two additional destructive behaviors; they should be fixed in the same change or tracked as follow-ups:

  1. SandboxClient.createSandbox() unconditionally calls deleteSandboxClaim in its catch block. A 409 AlreadyExists for a caller-supplied claimName therefore deletes a pre-existing claim (and cascades to its Sandbox/Pod/PVC). It should track whether this call created the claim and only clean up in that case, ideally with a UID precondition.
  2. SandboxClient.getSandbox() calls existing.terminate() on any resolution/query failure, including transient 503/timeout. A read failure can therefore delete a live claim. It should close only the local connection on transient errors and never terminate remote resources from a query path.

These share the root cause with the main issue: the code has no explicit “created/owned vs resumed” and “release vs destroy” distinction for Kubernetes claims.

Workaround

There is no clean configuration workaround. Setting shutdownPolicy: Retain does not help because the controller still deletes the underlying Sandbox on expiry, and the harness still deletes the claim on every release. A temporary mitigation is to avoid the K8s state-resume path (for example, disable persisted sandbox state), at the cost of cold-starting on every call.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions