Clone an agent sandbox with Checkpoint
When you develop complex AI agents, you may need to preserve their runtime state to quickly reuse a sandbox environment. You can create a point-in-time snapshot of a running container using the E2B SDK or a Checkpoint Custom Resource (CR). This method ensures filesystem consistency and reduces environment initialization costs.
Prerequisites
Upgrade the
acs-virtual-nodecomponent to v2.17.0 or later.
Limitations
You can use the Checkpoint feature only with ACS Agent Sandbox computing resources.
You can submit a Checkpoint only after the Pod is
RunningandReady.A Pod can only have one running Checkpoint at a time. After a Checkpoint reaches a terminal state (Succeeded or Failed), you can submit another Checkpoint.
After a Checkpoint task enters the
Runningstate, you cannot cancel the task by deleting the Checkpoint resource.
Configure Checkpoint content retention
Checkpoints support retaining the following content:
filesystem: Retained by default. If you specify any content to retain other than
filesystem, the Checkpoint creation fails.
By default, if you do not use the Checkpoint interface (E2B SDK) or a CR to explicitly specify the content to persist, the configuration of the Sandbox's spec.persistentContents field is used.
You can also use aSandboxSet to control the content retention for all sandboxes created from the template:
apiVersion: agents.kruise.io/v1alpha1
kind: SandboxSet
metadata:
name: code-interpreter-fs
namespace: default
spec:
replicas: 2
persistentContents:
- filesystem # Retain only the filesystem.
...Create a snapshot and clone a sandbox
E2B SDK
Create the source sandbox
The following example uses a SandboxSet template to demonstrate restoration.
Deploy the SandboxSet. Save the following content as a YAML file and run the
kubectl apply -f <YAML_FILE>command.Create a sandbox using the E2B SDK. For detailed instructions, seeCreate an Agent Sandbox.
# Import the E2B SDK from e2b_code_interpreter import Sandbox # Create a sandbox that retains only the filesystem. sbx_with_fs = Sandbox.create("code-interpreter-fs") print(f"fs-sandbox id: {sbx_with_fs.sandbox_id}")Initialize the state by writing data to the filesystem within the sandbox.
def init_mem_fs(sbx): sbx.files.write("/my-file", "hello") # Write a file. # Verify that the data was written successfully. print(sbx.files.read("/my-file")) init_mem_fs(sbx_with_fs)
Create a Checkpoint
Replace<YOUR_SANDBOX_ID> with your actual sandboxID to create a snapshot of the sandbox's current state.
sbx_with_fs = Sandbox.connect("<YOUR_SANDBOX_ID>")
snapshot_with_fs = sbx_with_fs.create_snapshot(headers={
"x-e2b-kruise-snapshot-keep-running": "true", # Specifies whether the Sandbox continues to run after the Checkpoint is created. If false, the corresponding Pod status changes to Succeeded. Defaults to true.
"x-e2b-kruise-snapshot-ttl": "30m", # The time-to-live (TTL) of the created Checkpoint. It is automatically deleted after this duration. If not set, it persists until manually deleted.
"x-e2b-kruise-snapshot-persistent-contents": "filesystem", # The content to be retained by the Checkpoint. By default, it inherits the retention setting from the Sandbox. Currently, only filesystem is supported.
"x-e2b-kruise-snapshot-wait-success-seconds": "60", # The server-side timeout in seconds for waiting for the Checkpoint creation to complete. Defaults to 60.
})
print(f"Snapshot ID with file system: {snapshot_with_fs.snapshot_id}")
# After the Checkpoint is created, you can safely delete the source sandbox.
sbx_with_fs.kill()Clone a sandbox from a Checkpoint
Replace
<YOUR_SNAPSHOT_ID>with theSnapshot IDreturned in the previous step, and pass it as the template parameter to the create interface to perform the clone. Standard extension parameters such astimeout,auto_pause, andCSImounting are still valid for the clone interface.# Create a new sandbox from a snapshot ID. clone_with_fs = Sandbox.create("<YOUR_SNAPSHOT_ID>") # By default, the E2B client sets a 300-second cleanup timeout, which you can configure.Verify the restoration by checking the data in the cloned sandbox.
# Verify the cloned sandbox with filesystem retention enabled. print(clone_with_fs.files.read("/my-file"))Expected output: The cloned sandbox correctly restores the
/my-filefile from the filesystem.hello
Sandbox CR
Create a sandbox
Save the following content as thesandbox.yaml file and run thekubectl apply -f sandbox.yaml command.
apiVersion: agents.kruise.io/v1alpha1
kind: Sandbox
metadata:
name: code-demo
spec:
template:
metadata:
labels:
agent: code-demo
# Use ACS computing resources.
alibabacloud.com/acs: "true"
alibabacloud.com/compute-class: agent-sandbox # The Agent Sandbox instance type.
spec:
automountServiceAccountToken: false
initContainers:
# Declare agent-runtime as a sidecar to automatically inject runtime components, such as envd, into the sandbox container.
- name: runtime
image: registry-cn-zhangjiakou-vpc.ack.aliyuncs.com/acs/agent-runtime:v0.0.5 # Replace cn-zhangjiakou with the actual region ID.
command: [ "sh", "/workspace/entrypoint_inner.sh" ]
volumeMounts:
# The directory shared with the main container.
- name: envd-volume
mountPath: /mnt/envd
env:
- name: ENVD_DIR
value: /mnt/envd
# This environment variable allows the sidecar to share the resources of the main container without incurring extra costs.
- name: __IGNORE_RESOURCE__
value: "true"
restartPolicy: Always
containers:
- name: my-session
image: registry-ap-southeast-1.ack.aliyuncs.com/acs/code-interpreter:v1.6
env:
- name: GODEBUG
value: multipathtcp=0
# Specify the location of the envd component injected by the runtime.
- name: ENVD_DIR
value: /mnt/envd
resources:
requests:
cpu: 1
memory: 1Gi
ephemeral-storage: "30Gi" #Request 30 GiB of ephemeral storage.
ports:
- containerPort: 49999
name: interpreter
volumeMounts:
# The directory shared with the runtime.
- name: envd-volume
mountPath: /mnt/envd
lifecycle:
postStart:
exec:
command: [ "/bin/bash", "-c", "/mnt/envd/envd-run.sh" ]
terminationGracePeriodSeconds: 1
volumes:
- name: envd-volume
emptyDir: { }Create a Checkpoint
Create a Checkpoint CR to take a snapshot of the target sandbox. Save the following content as the
sandbox-checkpoint.yamlfile and run thekubectl apply -f sandbox-checkpoint.yamlcommand.apiVersion: agents.kruise.io/v1alpha1 kind: Checkpoint metadata: name: checkpoint-code-demo namespace: default spec: # The name of the target Pod. podName: code-demo # Specifies whether the Pod is required to remain in the Running state after the Checkpoint is created. If you set this to false, the Pod status changes to Succeeded. keepRunning: true # The time-to-live for the Checkpoint. The system automatically deletes the Checkpoint resource after the ttlAfterFinished duration. # If this is not configured, the system does not delete the resource by default. The underlying snapshot is deleted when you manually delete the Checkpoint CR. ttlAfterFinished: 30h # Format examples: 30m, 30h, 30d. persistentContents: # Currently, only retaining the filesystem is supported. - filesystemView the
checkpointId.kubectl get checkpoint checkpoint-code-demo -n default -o jsonpath='{.status.checkpointId}'
Clone a new sandbox
Replace
<YOUR_CHECKPOINT_ID>with thecheckpointIdfrom the previous step. Save the content as thesandbox-clone.yamlfile and run thekubectl apply -f sandbox-clone.yamlcommand.apiVersion: agents.kruise.io/v1alpha1 kind: Sandbox metadata: name: code-demo-clone spec: template: metadata: labels: agent: code-demo-clone # Use ACS computing resources. alibabacloud.com/acs: "true" alibabacloud.com/compute-class: agent-sandbox # The Agent Sandbox instance type. annotations: # Replace with the correct Checkpoint ID. checkpoint.alibabacloud.com/restore-from: "<YOUR_CHECKPOINT_ID>" spec: # The spec of the cloned sandbox must be consistent with the spec of the source Pod. automountServiceAccountToken: false initContainers: # Declare agent-runtime as a sidecar to automatically inject runtime components, such as envd, into the sandbox container. - name: runtime image: registry-cn-zhangjiakou-vpc.ack.aliyuncs.com/acs/agent-runtime:v0.0.5 # Replace cn-zhangjiakou with the actual region ID. command: [ "sh", "/workspace/entrypoint_inner.sh" ] volumeMounts: # The directory shared with the main container. - name: envd-volume mountPath: /mnt/envd env: - name: ENVD_DIR value: /mnt/envd # This environment variable allows the sidecar to share the resources of the main container without incurring extra costs. - name: __IGNORE_RESOURCE__ value: "true" restartPolicy: Always containers: - name: my-session image: registry-ap-southeast-1.ack.aliyuncs.com/acs/code-interpreter:v1.6 env: - name: GODEBUG value: multipathtcp=0 # Specify the location of the envd component injected by the runtime. - name: ENVD_DIR value: /mnt/envd resources: requests: cpu: 1 memory: 1Gi ephemeral-storage: "30Gi" #Request 30 GiB of ephemeral storage. ports: - containerPort: 49999 name: interpreter volumeMounts: # The directory shared with the runtime. - name: envd-volume mountPath: /mnt/envd lifecycle: postStart: exec: command: [ "/bin/bash", "-c", "/mnt/envd/envd-run.sh" ] terminationGracePeriodSeconds: 1 volumes: - name: envd-volume emptyDir: { }View the Sandbox resource and its corresponding Pod.
kubectl get sandbox/code-demo-clone pod/code-demo-clone -o wideExpected output:
NAME STATUS AGE SHUTDOWN_TIME PAUSE_TIME MESSAGE sandbox.agents.kruise.io/code-demo-clone Running 71m NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES pod/code-demo-clone 1/1 Running 0 71m 172.16.x.xx virtual-kubelet-cn-hangzhou-h <none> <none>