Clone an agent sandbox with Checkpoint

Updated at:

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

  1. Upgrade theacs-virtual-node component to v2.17.0 or later.

  2. Install related components.

Limitations

  1. You can use the Checkpoint feature only with ACS Agent Sandbox computing resources.

  2. You can submit a Checkpoint only after the Pod is Running and Ready.

  3. 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.

  4. After a Checkpoint task enters the Running state, 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 thanfilesystem, 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.

Inherit the filesystem retention configuration

# Original Sandbox configuration
apiVersion: agents.kruise.io/v1alpha1
kind: Sandbox
spec:
  persistentContents:
    - filesystem
  ...
---
# Final generated Checkpoint configuration
apiVersion: agents.kruise.io/v1alpha1
kind: Checkpoint
spec:
  persistentContents: # Automatically inherits the original configuration
    - filesystem
  ...

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.

  1. Deploy the SandboxSet. Save the following content as a YAML file and run thekubectl apply -f <YAML_FILE> command.

    code-interpreter-fs.yaml

    apiVersion: agents.kruise.io/v1alpha1
    kind: SandboxSet
    metadata:
      name: code-interpreter-fs
      namespace: default
    spec:
      # The size of the warm pool. We recommend setting this value slightly larger than the estimated request burst.
      replicas: 2
      persistentContents: # Retain only the filesystem.
        - filesystem
      template:
        metadata:
          labels:
            # Optional. Schedules the sandbox Pod to ACS in an ACK cluster.
            alibabacloud.com/acs: "true"
            alibabacloud.com/compute-class: agent-sandbox # The Agent Sandbox instance type.
        spec:
          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: sandbox
            # The E2B code-interpreter image. Replace cn-zhangjiakou with the actual region ID.
            image: registry-cn-zhangjiakou-vpc.ack.aliyuncs.com/acs/code-interpreter:v1.6
            imagePullPolicy: IfNotPresent
            # We recommend that you set resource requirements. Otherwise, a very small specification is assigned in the ACS environment, which can affect performance.
            resources:
              limits:
                cpu: 1
                memory: 1Gi
              requests:
                cpu: 1
                memory: 1Gi
            startupProbe:
              failureThreshold: 10
              httpGet:
                path: /health
                port: 49999
              initialDelaySeconds: 1
              periodSeconds: 2
              timeoutSeconds: 1
            env:
              # Specify the location of the envd component injected by the runtime.
              - name: ENVD_DIR
                value: /mnt/envd
            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" ]
          # Ensures that the container is destroyed quickly to increase the probability of reuse.
          terminationGracePeriodSeconds: 1
          volumes:
            - name: envd-volume
              emptyDir: { }
  2. 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}")
  3. 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()

Header parameters

ack-sandbox-manager supports extending Checkpoint capabilities through custom headers:

Parameter

Description

Default

x-e2b-kruise-snapshot-keep-running

Specifies whether the sandbox continues to run after the Checkpoint is created. If set to false, the Pod's status changes to Succeeded.

true

x-e2b-kruise-snapshot-ttl

The time-to-live (TTL) of the Checkpoint. The Checkpoint is automatically deleted after the specified duration, such as 30m. If not set, it persists until you delete it manually.

None

x-e2b-kruise-snapshot-persistent-contents

Manually overrides the content retained by the Checkpoint. Only filesystem is supported.

Inherits the Sandbox configuration

x-e2b-kruise-snapshot-wait-success-seconds

The server-side timeout in seconds for waiting for the Checkpoint to complete.

60

Clone a sandbox from a Checkpoint

  1. Replace <YOUR_SNAPSHOT_ID> with the Snapshot ID returned in the previous step, and pass it as the template parameter to the create interface to perform the clone. Standard extension parameters such as timeout, auto_pause, and CSI mounting 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.
  2. 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-file file 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

  1. Create a Checkpoint CR to take a snapshot of the target sandbox. Save the following content as thesandbox-checkpoint.yaml file and run thekubectl apply -f sandbox-checkpoint.yaml command.

    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.
      - filesystem
  2. View thecheckpointId.

    kubectl get checkpoint checkpoint-code-demo -n default -o jsonpath='{.status.checkpointId}'

Clone a new sandbox

  1. Replace<YOUR_CHECKPOINT_ID> with thecheckpointId from the previous step. Save the content as thesandbox-clone.yaml file and run thekubectl apply -f sandbox-clone.yaml command.

    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: { }
  2. View the Sandbox resource and its corresponding Pod.

    kubectl get sandbox/code-demo-clone pod/code-demo-clone -o wide

    Expected 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>

Related documentation