Skip to content

An open-source, faster Devin alternative

TypeScript

Add checkpoint retention policy (#421)

Mohamed Habib7ee32b2b47d9
diff --git a/cmd/oc/internal/commands/checkpoint.go b/cmd/oc/internal/commands/checkpoint.go
index 1cd60c5e..d1f399ea 100644
--- a/cmd/oc/internal/commands/checkpoint.go
+++ b/cmd/oc/internal/commands/checkpoint.go
@@ -11,16 +11,16 @@ import (
// CheckpointInfo matches the API response for checkpoints.
type CheckpointInfo struct {
- ID string `json:"id"`
- SandboxID string `json:"sandboxId"`
- OrgID string `json:"orgId"`
- Name string `json:"name"`
- Status string `json:"status"`
- RootfsS3Key string `json:"rootfsS3Key,omitempty"`
- WorkspaceS3Key string `json:"workspaceS3Key,omitempty"`
- SizeBytes int64 `json:"sizeBytes"`
- IsPublic bool `json:"isPublic"`
- CreatedAt time.Time `json:"createdAt"`
+ ID string `json:"id"`
+ SandboxID string `json:"sandboxId"`
+ OrgID string `json:"orgId"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ RootfsS3Key string `json:"rootfsS3Key,omitempty"`
+ WorkspaceS3Key string `json:"workspaceS3Key,omitempty"`
+ SizeBytes int64 `json:"sizeBytes"`
+ IsPublic bool `json:"isPublic"`
+ CreatedAt time.Time `json:"createdAt"`
}
var checkpointCmd = &cobra.Command{
@@ -36,8 +36,20 @@ var checkpointCreateCmd = &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
c := client.FromContext(cmd.Context())
name, _ := cmd.Flags().GetString("name")
+ retentionPolicy, _ := cmd.Flags().GetString("retention-policy")
+ retentionMaxCount, _ := cmd.Flags().GetInt("retention-max-count")
- req := map[string]string{"name": name}
+ req := map[string]any{"name": name}
+ if retentionPolicy != "" && retentionPolicy != "none" {
+ if retentionPolicy != "delete_oldest" {
+ return fmt.Errorf("unsupported retention policy %q; expected none or delete_oldest", retentionPolicy)
+ }
+ policy := map[string]any{"mode": retentionPolicy}
+ if retentionMaxCount > 0 {
+ policy["maxCount"] = retentionMaxCount
+ }
+ req["retentionPolicy"] = policy
+ }
var cp CheckpointInfo
if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints", args[0]), req, &cp); err != nil {
return err
@@ -185,6 +197,8 @@ func setCheckpointPublic(cmd *cobra.Command, id string, isPublic bool) error {
func init() {
checkpointCreateCmd.Flags().String("name", "", "Checkpoint name (required)")
+ checkpointCreateCmd.Flags().String("retention-policy", "none", "Retention policy for automatic checkpoint cleanup (none, delete_oldest)")
+ checkpointCreateCmd.Flags().Int("retention-max-count", 0, "Maximum checkpoints to keep when --retention-policy=delete_oldest (1-10, default server limit)")
checkpointCreateCmd.MarkFlagRequired("name")
checkpointSpawnCmd.Flags().Int("timeout", 0, "Idle timeout in seconds before auto-hibernate (0 = never hibernate)")
diff --git a/docs/api-reference/checkpoints/create.mdx b/docs/api-reference/checkpoints/create.mdx
index e534e147..ce639417 100644
--- a/docs/api-reference/checkpoints/create.mdx
+++ b/docs/api-reference/checkpoints/create.mdx
@@ -4,6 +4,9 @@ api: 'POST /api/sandboxes/{id}/checkpoints'
---
Create a checkpoint of the sandbox state. Maximum 10 checkpoints per sandbox.
+By default, creating an 11th checkpoint returns an error. Set
+`retentionPolicy.mode` to `delete_oldest` to delete the oldest eligible
+checkpoint first so the new checkpoint can be created.
<ParamField path="id" type="string" required>
Sandbox ID
@@ -13,6 +16,12 @@ Create a checkpoint of the sandbox state. Maximum 10 checkpoints per sandbox.
Checkpoint name (unique per sandbox)
</ParamField>
+<ParamField body="retentionPolicy" type="object">
+ Optional retention policy. Use `{ "mode": "delete_oldest", "maxCount": 10 }`
+ to keep at most 10 checkpoints by deleting the oldest eligible checkpoint
+ before creating a new one.
+</ParamField>
+
<ResponseExample>
```json 201
{
diff --git a/docs/cli/checkpoint.mdx b/docs/cli/checkpoint.mdx
index 2932e161..43fbde3f 100644
--- a/docs/cli/checkpoint.mdx
+++ b/docs/cli/checkpoint.mdx
@@ -54,6 +54,17 @@ oc cp delete sb-abc123 cp-7f3a1b2c
Maximum 10 checkpoints per sandbox.
+To create a new checkpoint at the limit, opt into automatic deletion of the oldest eligible checkpoint:
+
+```bash
+oc cp create sb-abc123 \
+ --name autosave \
+ --retention-policy delete_oldest \
+ --retention-max-count 10
+```
+
+Retention skips public checkpoints, patched checkpoints, and checkpoints that are still referenced by forked sandboxes.
+
## Checkpoint vs Hibernate
| | Checkpoint | Hibernate |
diff --git a/docs/reference/cli/checkpoint.mdx b/docs/reference/cli/checkpoint.mdx
index 96bd283d..ae885ef7 100644
--- a/docs/reference/cli/checkpoint.mdx
+++ b/docs/reference/cli/checkpoint.mdx
@@ -13,10 +13,25 @@ Create a named checkpoint of a running sandbox. [HTTP API →](/api-reference/ch
Checkpoint name
</ParamField>
+<ParamField query="--retention-policy" type="string" default="none">
+ Optional retention policy. Use `delete_oldest` to delete the oldest eligible checkpoint before creating this one.
+</ParamField>
+
+<ParamField query="--retention-max-count" type="int" default="10">
+ Maximum checkpoints to keep when `--retention-policy delete_oldest` is set. Must be between 1 and 10.
+</ParamField>
+
```bash
oc cp create sb-abc --name before-migration
```
+```bash
+oc cp create sb-abc \
+ --name autosave \
+ --retention-policy delete_oldest \
+ --retention-max-count 10
+```
+
---
## `oc checkpoint list <sandbox-id>`
diff --git a/docs/reference/python-sdk.mdx b/docs/reference/python-sdk.mdx
index 01c397ae..db410b63 100644
--- a/docs/reference/python-sdk.mdx
+++ b/docs/reference/python-sdk.mdx
@@ -121,9 +121,9 @@ Update idle timeout.
| --- | --- | --- |
| `timeout` | int | New timeout in seconds |
-#### `await sandbox.create_checkpoint(name): dict`
+#### `await sandbox.create_checkpoint(name, retention_policy=None): dict`
-Create a named checkpoint. Returns checkpoint info as a dictionary.
+Create a named checkpoint. Pass `retention_policy={"mode": "delete_oldest", "maxCount": 10}` to delete the oldest eligible checkpoint before creating a new one when the sandbox already has 10 checkpoints. Returns checkpoint info as a dictionary.
#### `await sandbox.list_checkpoints(): list[dict]`
diff --git a/docs/reference/python-sdk/sandbox.mdx b/docs/reference/python-sdk/sandbox.mdx
index 7a0855da..685ce5ed 100644
--- a/docs/reference/python-sdk/sandbox.mdx
+++ b/docs/reference/python-sdk/sandbox.mdx
@@ -175,10 +175,16 @@ Update idle timeout. [HTTP API →](/api-reference/sandboxes/set-timeout)
**Returns:** `None`
-### `await sandbox.create_checkpoint(name)`
+### `await sandbox.create_checkpoint(name, retention_policy=None)`
Create a named checkpoint. [HTTP API →](/api-reference/checkpoints/create)
+<ParamField body="retention_policy" type="dict">
+ Optional retention policy. Use `{"mode": "delete_oldest", "maxCount": 10}` to
+ delete the oldest eligible checkpoint before creating a new one when the
+ sandbox already has 10 checkpoints.
+</ParamField>
+
**Returns:** `dict`
### `await sandbox.list_checkpoints()`
diff --git a/docs/reference/typescript-sdk.mdx b/docs/reference/typescript-sdk.mdx
index e5c2584a..38b5799f 100644
--- a/docs/reference/typescript-sdk.mdx
+++ b/docs/reference/typescript-sdk.mdx
@@ -130,9 +130,9 @@ Update the idle timeout.
| --- | --- | --- |
| `timeout` | number | New timeout in seconds |
-#### `sandbox.createCheckpoint(name): Promise<CheckpointInfo>`
+#### `sandbox.createCheckpoint(name, opts?): Promise<CheckpointInfo>`
-Create a named checkpoint.
+Create a named checkpoint. Pass `retentionPolicy: { mode: "delete_oldest", maxCount: 10 }` to delete the oldest eligible checkpoint before creating a new one when the sandbox already has 10 checkpoints.
#### `sandbox.listCheckpoints(): Promise<CheckpointInfo[]>`
diff --git a/docs/reference/typescript-sdk/sandbox.mdx b/docs/reference/typescript-sdk/sandbox.mdx
index 4d793937..75472a7b 100644
--- a/docs/reference/typescript-sdk/sandbox.mdx
+++ b/docs/reference/typescript-sdk/sandbox.mdx
@@ -208,7 +208,7 @@ Update the idle timeout. [HTTP API →](/api-reference/sandboxes/set-timeout)
**Returns:** `Promise<void>`
-### `sandbox.createCheckpoint(name)`
+### `sandbox.createCheckpoint(name, opts?)`
Create a named checkpoint. [HTTP API →](/api-reference/checkpoints/create)
@@ -216,6 +216,12 @@ Create a named checkpoint. [HTTP API →](/api-reference/checkpoints/create)
Checkpoint name (unique per sandbox)
</ParamField>
+<ParamField body="opts.retentionPolicy" type="object">
+ Optional retention policy. Use `{ mode: "delete_oldest", maxCount: 10 }` to
+ delete the oldest eligible checkpoint before creating a new one when the
+ sandbox already has 10 checkpoints.
+</ParamField>
+
**Returns:** `Promise<CheckpointInfo>`
### `sandbox.listCheckpoints()`
diff --git a/docs/sandboxes/checkpoints.mdx b/docs/sandboxes/checkpoints.mdx
index c9f05b91..f2880e6e 100644
--- a/docs/sandboxes/checkpoints.mdx
+++ b/docs/sandboxes/checkpoints.mdx
@@ -48,7 +48,7 @@ await b.exec.run("npm run test:e2e", cwd="/app")
| Purpose | Fork new sandboxes from saved state | Pause and resume the **same** sandbox |
| Original sandbox | Keeps running | Stopped |
| Can fork | Yes — unlimited new sandboxes | No |
-| Count | Up to 10 per sandbox | One hibernation state |
+| Count | Up to 10 per sandbox, with optional oldest-checkpoint cleanup | One hibernation state |
| Use case | Parallel testing, branching experiments | Cost savings, idle timeout |
## What Gets Preserved
@@ -71,10 +71,42 @@ checkpoint = await sandbox.create_checkpoint("before-migration")
# checkpoint["id"], checkpoint["status"]
```
+```bash CLI
+oc cp create sb-abc123 --name before-migration
+```
+
</CodeGroup>
Checkpoint name must be unique within the sandbox. Status transitions from `processing` to `ready` (or `failed`).
+Each sandbox can have up to 10 checkpoints. To create a new checkpoint without failing at the limit, pass a retention policy that deletes the oldest eligible checkpoint first:
+
+<CodeGroup>
+
+```typescript TypeScript
+const checkpoint = await sandbox.createCheckpoint("autosave", {
+ retentionPolicy: { mode: "delete_oldest", maxCount: 10 },
+});
+```
+
+```python Python
+checkpoint = await sandbox.create_checkpoint(
+ "autosave",
+ retention_policy={"mode": "delete_oldest", "maxCount": 10},
+)
+```
+
+```bash CLI
+oc cp create sb-abc123 \
+ --name autosave \
+ --retention-policy delete_oldest \
+ --retention-max-count 10
+```
+
+</CodeGroup>
+
+Retention skips checkpoints that are public, have patches, or are still referenced by forked sandboxes. If no eligible checkpoint can be deleted, creation fails instead of deleting protected state.
+
### List Checkpoints
<CodeGroup>
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 6328c48e..af88f8c7 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -22,6 +22,18 @@ import (
pb "github.com/opensandbox/opensandbox/proto/worker"
)
+const maxCheckpointsPerSandbox = 10
+
+type createCheckpointRequest struct {
+ Name string `json:"name"`
+ RetentionPolicy checkpointRetentionPolicy `json:"retentionPolicy"`
+}
+
+type checkpointRetentionPolicy struct {
+ Mode string `json:"mode"`
+ MaxCount int `json:"maxCount"`
+}
+
func (s *Server) createSandbox(c echo.Context) error {
var cfg types.SandboxConfig
if err := c.Bind(&cfg); err != nil {
@@ -2161,9 +2173,7 @@ func (s *Server) createCheckpoint(c echo.Context) error {
}
// Parse request body
- var req struct {
- Name string `json:"name"`
- }
+ var req createCheckpointRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})
}
@@ -2176,7 +2186,37 @@ func (s *Server) createCheckpoint(c echo.Context) error {
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to count checkpoints"})
}
- if count >= 10 {
+
+ if req.RetentionPolicy.Mode != "" && req.RetentionPolicy.Mode != "none" {
+ if req.RetentionPolicy.Mode != "delete_oldest" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "unsupported checkpoint retention policy"})
+ }
+ maxCount := req.RetentionPolicy.MaxCount
+ if maxCount == 0 {
+ maxCount = maxCheckpointsPerSandbox
+ }
+ if maxCount < 1 || maxCount > maxCheckpointsPerSandbox {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "retentionPolicy.maxCount must be between 1 and 10"})
+ }
+ if count >= maxCount {
+ deleteCount := count - maxCount + 1
+ candidates, err := s.store.ListCheckpointRetentionCandidates(ctx, sandboxID, orgID, deleteCount)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to find checkpoints for retention"})
+ }
+ if len(candidates) < deleteCount {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "maximum 10 checkpoints per sandbox; no eligible checkpoint can be deleted by retention policy"})
+ }
+ for _, oldCP := range candidates {
+ if err := s.deleteCheckpointRecordAndObjects(ctx, &oldCP, orgID); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to apply checkpoint retention policy: " + err.Error()})
+ }
+ }
+ count -= len(candidates)
+ }
+ }
+
+ if count >= maxCheckpointsPerSandbox {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "maximum 10 checkpoints per sandbox"})
}
@@ -2878,12 +2918,21 @@ func (s *Server) deleteCheckpoint(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint does not belong to this sandbox"})
}
- // Delete from DB (enforces org ownership)
- if err := s.store.DeleteCheckpoint(ctx, orgID, checkpointID); err != nil {
+ if err := s.deleteCheckpointRecordAndObjects(ctx, cp, orgID); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
+
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *Server) deleteCheckpointRecordAndObjects(ctx context.Context, cp *db.Checkpoint, orgID uuid.UUID) error {
+ // Delete from DB (enforces org ownership)
+ if err := s.store.DeleteCheckpoint(ctx, orgID, cp.ID); err != nil {
+ return err
+ }
+
// Mirror the deletion to D1 checkpoints_index via events-ingest.
- s.publishCheckpointEvent(ctx, "checkpoint_deleted", checkpointID, sandboxID, orgID, "", nil)
+ s.publishCheckpointEvent(ctx, "checkpoint_deleted", cp.ID, cp.SandboxID, cp.OrgID, "", nil)
// Best-effort: delete S3 objects if checkpoint store is configured
if s.checkpointStore != nil && cp.RootfsS3Key != nil && cp.WorkspaceS3Key != nil {
@@ -2898,7 +2947,7 @@ func (s *Server) deleteCheckpoint(c echo.Context) error {
}()
}
- return c.NoContent(http.StatusNoContent)
+ return nil
}
// --- Checkpoint Patch handlers ---
diff --git a/internal/db/store.go b/internal/db/store.go
index ce1c0d73..1dd50aab 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -2175,6 +2175,48 @@ func (s *Store) CountCheckpoints(ctx context.Context, sandboxID string) (int, er
return count, err
}
+// ListCheckpointRetentionCandidates returns the oldest checkpoints that can be
+// deleted by an automatic retention policy. It deliberately skips public
+// checkpoints, patched checkpoints, and checkpoints that are still referenced
+// by forked sandboxes.
+func (s *Store) ListCheckpointRetentionCandidates(ctx context.Context, sandboxID string, orgID uuid.UUID, limit int) ([]Checkpoint, error) {
+ if limit <= 0 {
+ return nil, nil
+ }
+ rows, err := s.pool.Query(ctx,
+ `SELECT c.id, c.sandbox_id, c.org_id, c.name, c.rootfs_s3_key, c.workspace_s3_key,
+ c.sandbox_config, c.status, c.size_bytes, c.is_public, c.created_at,
+ c.error_msg, c.failed_at
+ FROM sandbox_checkpoints c
+ WHERE c.sandbox_id = $1
+ AND c.org_id = $2
+ AND c.is_public = false
+ AND NOT EXISTS (
+ SELECT 1 FROM checkpoint_patches p WHERE p.checkpoint_id = c.id
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM sandbox_sessions ss WHERE ss.based_on_checkpoint_id = c.id
+ )
+ ORDER BY c.created_at ASC
+ LIMIT $3`, sandboxID, orgID, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var checkpoints []Checkpoint
+ for rows.Next() {
+ var cp Checkpoint
+ if err := rows.Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,
+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt,
+ &cp.ErrorMsg, &cp.FailedAt); err != nil {
+ return nil, err
+ }
+ checkpoints = append(checkpoints, cp)
+ }
+ return checkpoints, rows.Err()
+}
+
// DeleteCheckpoint deletes a checkpoint (only if owned by org).
// Clears any sandbox_sessions FK references first to avoid constraint violations.
func (s *Store) DeleteCheckpoint(ctx context.Context, orgID uuid.UUID, checkpointID uuid.UUID) error {
diff --git a/scripts/qemu-tests/41-checkpoint-retention.sh b/scripts/qemu-tests/41-checkpoint-retention.sh
new file mode 100755
index 00000000..68bafc1c
--- /dev/null
+++ b/scripts/qemu-tests/41-checkpoint-retention.sh
@@ -0,0 +1,131 @@
+#!/usr/bin/env bash
+# 41-checkpoint-retention.sh — Checkpoint create with delete_oldest retention
+source "$(dirname "$0")/common.sh"
+
+TIMEOUT=60
+MAX_COUNT="${MAX_COUNT:-10}"
+READY_TIMEOUT_SECONDS="${READY_TIMEOUT_SECONDS:-900}"
+RETENTION_ONLY="${RETENTION_ONLY:-0}"
+SANDBOXES=()
+
+cleanup() {
+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb"; done
+}
+trap cleanup EXIT
+
+checkpoint_body() {
+ local name="$1"
+ python3 - "$name" "$MAX_COUNT" <<'PY'
+import json
+import sys
+
+name = sys.argv[1]
+max_count = int(sys.argv[2])
+print(json.dumps({
+ "name": name,
+ "retentionPolicy": {
+ "mode": "delete_oldest",
+ "maxCount": max_count,
+ },
+}))
+PY
+}
+
+wait_checkpoint_ready() {
+ local sb="$1" name="$2" deadline=$((SECONDS + READY_TIMEOUT_SECONDS))
+ while [ "$SECONDS" -lt "$deadline" ]; do
+ local body status
+ body=$(api "$API_URL/api/sandboxes/$sb/checkpoints")
+ status=$(CHECKPOINT_NAME="$name" python3 -c '
+import json
+import os
+import sys
+
+name = os.environ["CHECKPOINT_NAME"]
+for cp in json.load(sys.stdin):
+ if cp.get("name") == name:
+ print(cp.get("status", ""))
+ break
+' <<<"$body" 2>/dev/null || true)
+ case "$status" in
+ ready) return 0 ;;
+ failed) return 1 ;;
+ esac
+ sleep 5
+ done
+ return 1
+}
+
+checkpoint_names() {
+ local sb="$1"
+ local body
+ body=$(api "$API_URL/api/sandboxes/$sb/checkpoints")
+ python3 -c '
+import json
+import sys
+
+for cp in json.load(sys.stdin):
+ print(cp.get("name", ""))
+' <<<"$body"
+}
+
+h "Checkpoint retention"
+
+if [ "$MAX_COUNT" -lt 1 ] || [ "$MAX_COUNT" -gt 10 ]; then
+ fail "MAX_COUNT must be between 1 and 10"
+ summary
+fi
+
+SB=$(create_sandbox 3600)
+SANDBOXES+=("$SB")
+wait_for_sandbox "$SB" 30 && pass "Sandbox running: $SB" || { fail "Sandbox not running"; summary; }
+
+PREFIX="retention-$(date +%s)"
+TOTAL=$((MAX_COUNT + 1))
+
+for i in $(seq 1 "$TOTAL"); do
+ name="$PREFIX-$i"
+ body=$(checkpoint_body "$name")
+ result=$(api -X POST "$API_URL/api/sandboxes/$SB/checkpoints" -d "$body")
+ cp_id=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null || true)
+ if [ -z "$cp_id" ]; then
+ fail "Create checkpoint $i failed: $result"
+ summary
+ fi
+ pass "Created checkpoint $i/$TOTAL: $name ($cp_id)"
+
+ if [ "$RETENTION_ONLY" = "1" ] && [ "$i" -eq "$TOTAL" ]; then
+ pass "Retention checkpoint accepted without hard-cap error"
+ break
+ fi
+
+ if wait_checkpoint_ready "$SB" "$name"; then
+ pass "Checkpoint ready: $name"
+ else
+ fail "Checkpoint did not become ready: $name"
+ summary
+ fi
+done
+
+names=$(checkpoint_names "$SB")
+count=$(printf '%s\n' "$names" | sed '/^$/d' | wc -l | tr -d ' ')
+
+if [ "$count" = "$MAX_COUNT" ]; then
+ pass "Checkpoint count retained at $MAX_COUNT"
+else
+ fail "Checkpoint count is $count, expected $MAX_COUNT"
+fi
+
+if printf '%s\n' "$names" | grep -qx "$PREFIX-1"; then
+ fail "Oldest checkpoint still exists after retention"
+else
+ pass "Oldest checkpoint was deleted by retention"
+fi
+
+if printf '%s\n' "$names" | grep -qx "$PREFIX-$TOTAL"; then
+ pass "Newest checkpoint exists after retention"
+else
+ fail "Newest checkpoint missing after retention"
+fi
+
+summary
diff --git a/scripts/qemu-tests/42-checkpoint-retention-sdk.ts b/scripts/qemu-tests/42-checkpoint-retention-sdk.ts
new file mode 100644
index 00000000..cc43574d
--- /dev/null
+++ b/scripts/qemu-tests/42-checkpoint-retention-sdk.ts
@@ -0,0 +1,105 @@
+/**
+ * Checkpoint retention through the TypeScript SDK.
+ *
+ * Usage:
+ * OPENSANDBOX_API_URL=https://mo-oc-dev.com OPENSANDBOX_API_KEY=... \
+ * npx tsx scripts/qemu-tests/42-checkpoint-retention-sdk.ts
+ */
+
+import { Sandbox } from "../../sdks/typescript/src/index.ts";
+
+const MAX_COUNT = Number(process.env.MAX_COUNT || "3");
+const READY_TIMEOUT_SECONDS = Number(process.env.READY_TIMEOUT_SECONDS || "900");
+const RETENTION_ONLY = process.env.RETENTION_ONLY === "1";
+const API_URL = process.env.OPENCOMPUTER_API_URL || process.env.OPENSANDBOX_API_URL;
+const API_KEY = process.env.OPENCOMPUTER_API_KEY || process.env.OPENSANDBOX_API_KEY;
+
+let pass = 0;
+let fail = 0;
+
+function ok(message: string) {
+ pass += 1;
+ console.log(`PASS ${message}`);
+}
+
+function bad(message: string) {
+ fail += 1;
+ console.error(`FAIL ${message}`);
+}
+
+function summary() {
+ console.log(`${pass} passed, ${fail} failed`);
+ if (fail > 0) process.exit(1);
+}
+
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function waitForCheckpointReady(sandbox: Sandbox, name: string) {
+ const deadline = Date.now() + READY_TIMEOUT_SECONDS * 1000;
+ while (Date.now() < deadline) {
+ const checkpoints = await sandbox.listCheckpoints();
+ const cp = checkpoints.find((checkpoint) => checkpoint.name === name);
+ if (cp?.status === "ready") return true;
+ if (cp && cp.status !== "processing") return false;
+ await sleep(5000);
+ }
+ return false;
+}
+
+async function main() {
+ if (MAX_COUNT < 1 || MAX_COUNT > 10) {
+ throw new Error("MAX_COUNT must be between 1 and 10");
+ }
+
+ let sandbox: Sandbox | undefined;
+ const prefix = `ts-retention-${Date.now()}`;
+ const total = MAX_COUNT + 1;
+
+ try {
+ sandbox = await Sandbox.create({ apiUrl: API_URL, apiKey: API_KEY, timeout: 3600 });
+ ok(`sandbox running: ${sandbox.sandboxId}`);
+
+ for (let i = 1; i <= total; i += 1) {
+ const name = `${prefix}-${i}`;
+ const cp = await sandbox.createCheckpoint(name, {
+ retentionPolicy: { mode: "delete_oldest", maxCount: MAX_COUNT },
+ });
+ ok(`created checkpoint ${i}/${total}: ${name} (${cp.id})`);
+
+ if (RETENTION_ONLY && i === total) {
+ ok("retention checkpoint accepted without hard-cap error");
+ break;
+ }
+
+ if (await waitForCheckpointReady(sandbox, name)) {
+ ok(`checkpoint ready: ${name}`);
+ } else {
+ bad(`checkpoint did not become ready: ${name}`);
+ summary();
+ }
+ }
+
+ const checkpoints = await sandbox.listCheckpoints();
+ const names = checkpoints.map((checkpoint) => checkpoint.name);
+
+ if (names.length === MAX_COUNT) ok(`checkpoint count retained at ${MAX_COUNT}`);
+ else bad(`checkpoint count is ${names.length}, expected ${MAX_COUNT}`);
+
+ if (!names.includes(`${prefix}-1`)) ok("oldest checkpoint was deleted by retention");
+ else bad("oldest checkpoint still exists after retention");
+
+ if (names.includes(`${prefix}-${total}`)) ok("newest checkpoint exists after retention");
+ else bad("newest checkpoint missing after retention");
+ } finally {
+ if (sandbox) await sandbox.kill().catch(() => undefined);
+ }
+
+ summary();
+}
+
+main().catch((err) => {
+ bad(err instanceof Error ? err.message : String(err));
+ summary();
+});
diff --git a/scripts/qemu-tests/43-checkpoint-retention-sdk.py b/scripts/qemu-tests/43-checkpoint-retention-sdk.py
new file mode 100644
index 00000000..c70c571e
--- /dev/null
+++ b/scripts/qemu-tests/43-checkpoint-retention-sdk.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python3
+"""Checkpoint retention through the Python SDK.
+
+Usage:
+ OPENSANDBOX_API_URL=https://mo-oc-dev.com OPENSANDBOX_API_KEY=... \
+ python3 scripts/qemu-tests/43-checkpoint-retention-sdk.py
+"""
+
+import asyncio
+import os
+import sys
+import time
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "sdks", "python"))
+from opencomputer import Sandbox # noqa: E402
+
+MAX_COUNT = int(os.environ.get("MAX_COUNT", "3"))
+READY_TIMEOUT_SECONDS = int(os.environ.get("READY_TIMEOUT_SECONDS", "900"))
+RETENTION_ONLY = os.environ.get("RETENTION_ONLY") == "1"
+API_URL = os.environ.get("OPENCOMPUTER_API_URL") or os.environ.get("OPENSANDBOX_API_URL")
+API_KEY = os.environ.get("OPENCOMPUTER_API_KEY") or os.environ.get("OPENSANDBOX_API_KEY")
+
+PASS = 0
+FAIL = 0
+
+
+def ok(message: str) -> None:
+ global PASS
+ PASS += 1
+ print(f"PASS {message}")
+
+
+def bad(message: str) -> None:
+ global FAIL
+ FAIL += 1
+ print(f"FAIL {message}", file=sys.stderr)
+
+
+def summary() -> None:
+ print(f"{PASS} passed, {FAIL} failed")
+ raise SystemExit(0 if FAIL == 0 else 1)
+
+
+async def wait_for_checkpoint_ready(sandbox: Sandbox, name: str) -> bool:
+ deadline = time.time() + READY_TIMEOUT_SECONDS
+ while time.time() < deadline:
+ checkpoints = await sandbox.list_checkpoints()
+ cp = next((checkpoint for checkpoint in checkpoints if checkpoint.get("name") == name), None)
+ if cp and cp.get("status") == "ready":
+ return True
+ if cp and cp.get("status") != "processing":
+ return False
+ await asyncio.sleep(5)
+ return False
+
+
+async def main() -> None:
+ if MAX_COUNT < 1 or MAX_COUNT > 10:
+ raise ValueError("MAX_COUNT must be between 1 and 10")
+
+ sandbox = None
+ prefix = f"py-retention-{int(time.time())}"
+ total = MAX_COUNT + 1
+
+ try:
+ sandbox = await Sandbox.create(api_url=API_URL, api_key=API_KEY, timeout=3600)
+ ok(f"sandbox running: {sandbox.sandbox_id}")
+
+ for i in range(1, total + 1):
+ name = f"{prefix}-{i}"
+ cp = await sandbox.create_checkpoint(
+ name,
+ retention_policy={"mode": "delete_oldest", "maxCount": MAX_COUNT},
+ )
+ ok(f"created checkpoint {i}/{total}: {name} ({cp.get('id')})")
+
+ if RETENTION_ONLY and i == total:
+ ok("retention checkpoint accepted without hard-cap error")
+ break
+
+ if await wait_for_checkpoint_ready(sandbox, name):
+ ok(f"checkpoint ready: {name}")
+ else:
+ bad(f"checkpoint did not become ready: {name}")
+ summary()
+
+ checkpoints = await sandbox.list_checkpoints()
+ names = [checkpoint.get("name") for checkpoint in checkpoints]
+
+ if len(names) == MAX_COUNT:
+ ok(f"checkpoint count retained at {MAX_COUNT}")
+ else:
+ bad(f"checkpoint count is {len(names)}, expected {MAX_COUNT}")
+
+ if f"{prefix}-1" not in names:
+ ok("oldest checkpoint was deleted by retention")
+ else:
+ bad("oldest checkpoint still exists after retention")
+
+ if f"{prefix}-{total}" in names:
+ ok("newest checkpoint exists after retention")
+ else:
+ bad("newest checkpoint missing after retention")
+ finally:
+ if sandbox is not None:
+ try:
+ await sandbox.kill()
+ except Exception:
+ pass
+ await sandbox.close()
+
+ summary()
+
+
+if __name__ == "__main__":
+ try:
+ asyncio.run(main())
+ except Exception as exc:
+ bad(str(exc))
+ summary()
diff --git a/scripts/qemu-tests/44-checkpoint-retention-curl.sh b/scripts/qemu-tests/44-checkpoint-retention-curl.sh
new file mode 100644
index 00000000..aa4138b7
--- /dev/null
+++ b/scripts/qemu-tests/44-checkpoint-retention-curl.sh
@@ -0,0 +1,134 @@
+#!/usr/bin/env bash
+# Checkpoint retention through the public HTTP API with curl.
+#
+# Usage:
+# OPENSANDBOX_API_URL=https://mo-oc-dev.com OPENSANDBOX_API_KEY=... \
+# bash scripts/qemu-tests/44-checkpoint-retention-curl.sh
+
+source "$(dirname "$0")/common.sh"
+
+TIMEOUT="${TIMEOUT:-60}"
+MAX_COUNT="${MAX_COUNT:-3}"
+READY_TIMEOUT_SECONDS="${READY_TIMEOUT_SECONDS:-900}"
+RETENTION_ONLY="${RETENTION_ONLY:-0}"
+SANDBOXES=()
+
+cleanup() {
+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb"; done
+}
+trap cleanup EXIT
+
+checkpoint_body() {
+ local name="$1"
+ python3 - "$name" "$MAX_COUNT" <<'PY'
+import json
+import sys
+
+print(json.dumps({
+ "name": sys.argv[1],
+ "retentionPolicy": {
+ "mode": "delete_oldest",
+ "maxCount": int(sys.argv[2]),
+ },
+}))
+PY
+}
+
+wait_checkpoint_ready() {
+ local sb="$1" name="$2" deadline=$((SECONDS + READY_TIMEOUT_SECONDS))
+ while [ "$SECONDS" -lt "$deadline" ]; do
+ local body status
+ body=$(api "$API_URL/api/sandboxes/$sb/checkpoints")
+ status=$(CHECKPOINT_NAME="$name" python3 -c '
+import json
+import os
+import sys
+
+name = os.environ["CHECKPOINT_NAME"]
+for cp in json.load(sys.stdin):
+ if cp.get("name") == name:
+ print(cp.get("status", ""))
+ break
+' <<<"$body" 2>/dev/null || true)
+ case "$status" in
+ ready) return 0 ;;
+ failed) return 1 ;;
+ esac
+ sleep 5
+ done
+ return 1
+}
+
+checkpoint_names() {
+ local sb="$1"
+ local body
+ body=$(api "$API_URL/api/sandboxes/$sb/checkpoints")
+ python3 -c '
+import json
+import sys
+
+for cp in json.load(sys.stdin):
+ print(cp.get("name", ""))
+' <<<"$body"
+}
+
+h "Checkpoint retention via curl"
+
+if [ "$MAX_COUNT" -lt 1 ] || [ "$MAX_COUNT" -gt 10 ]; then
+ fail "MAX_COUNT must be between 1 and 10"
+ summary
+fi
+
+SB=$(create_sandbox 3600)
+SANDBOXES+=("$SB")
+wait_for_sandbox "$SB" 30 && pass "Sandbox running: $SB" || { fail "Sandbox not running"; summary; }
+
+PREFIX="curl-retention-$(date +%s)"
+TOTAL=$((MAX_COUNT + 1))
+
+for i in $(seq 1 "$TOTAL"); do
+ name="$PREFIX-$i"
+ body=$(checkpoint_body "$name")
+ result=$(api -X POST "$API_URL/api/sandboxes/$SB/checkpoints" -d "$body")
+ cp_id=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null || true)
+ if [ -z "$cp_id" ]; then
+ fail "Create checkpoint $i failed: $result"
+ summary
+ fi
+ pass "Created checkpoint $i/$TOTAL: $name ($cp_id)"
+
+ if [ "$RETENTION_ONLY" = "1" ] && [ "$i" -eq "$TOTAL" ]; then
+ pass "Retention checkpoint accepted without hard-cap error"
+ break
+ fi
+
+ if wait_checkpoint_ready "$SB" "$name"; then
+ pass "Checkpoint ready: $name"
+ else
+ fail "Checkpoint did not become ready: $name"
+ summary
+ fi
+done
+
+names=$(checkpoint_names "$SB")
+count=$(printf '%s\n' "$names" | sed '/^$/d' | wc -l | tr -d ' ')
+
+if [ "$count" = "$MAX_COUNT" ]; then
+ pass "Checkpoint count retained at $MAX_COUNT"
+else
+ fail "Checkpoint count is $count, expected $MAX_COUNT"
+fi
+
+if printf '%s\n' "$names" | grep -qx "$PREFIX-1"; then
+ fail "Oldest checkpoint still exists after retention"
+else
+ pass "Oldest checkpoint was deleted by retention"
+fi
+
+if printf '%s\n' "$names" | grep -qx "$PREFIX-$TOTAL"; then
+ pass "Newest checkpoint exists after retention"
+else
+ fail "Newest checkpoint missing after retention"
+fi
+
+summary
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 67579c26..1f385229 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -602,18 +602,30 @@ class Sandbox:
pty_key = self._token or self._api_key
return Pty(self._ops_client, self.sandbox_id, pty_url, pty_key)
- async def create_checkpoint(self, name: str) -> dict:
+ async def create_checkpoint(
+ self,
+ name: str,
+ retention_policy: dict | None = None,
+ ) -> dict:
"""Create a named checkpoint of the running sandbox.
Args:
name: A unique name for this checkpoint.
+ retention_policy: Optional policy such as
+ {"mode": "delete_oldest", "maxCount": 10}. When set, the
+ server may delete older eligible checkpoints before creating
+ this one.
Returns:
Checkpoint info dict with id, sandboxId, name, status, etc.
"""
+ body = {"name": name}
+ if retention_policy is not None:
+ body["retentionPolicy"] = retention_policy
+
resp = await self._client.post(
f"/sandboxes/{self.sandbox_id}/checkpoints",
- json={"name": name},
+ json=body,
)
resp.raise_for_status()
return resp.json()
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index d34e86f5..8792727c 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -5,6 +5,8 @@ export {
SandboxFamilyLimitError,
type SandboxOpts,
type CheckpointInfo,
+ type CheckpointRetentionPolicy,
+ type CreateCheckpointOptions,
type PatchInfo,
type PatchResult,
type ScaleResult,
diff --git a/sdks/typescript/src/sandbox.test.ts b/sdks/typescript/src/sandbox.test.ts
new file mode 100644
index 00000000..21f0c8a0
--- /dev/null
+++ b/sdks/typescript/src/sandbox.test.ts
@@ -0,0 +1,42 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Sandbox } from "./sandbox.js";
+
+describe("Sandbox checkpoint requests", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("sends delete_oldest retention policy when creating a checkpoint", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify({
+ id: "cp_1",
+ sandboxId: "sb_1",
+ orgId: "org_1",
+ name: "autosave",
+ sandboxConfig: {},
+ status: "processing",
+ sizeBytes: 0,
+ createdAt: "2026-01-01T00:00:00Z",
+ }), { status: 201, headers: { "content-type": "application/json" } }),
+ );
+
+ const sandbox = Object.create(Sandbox.prototype) as Sandbox & {
+ apiUrl: string;
+ apiKey: string;
+ sandboxId: string;
+ };
+ sandbox.apiUrl = "https://api.example.test/api";
+ sandbox.apiKey = "osb_test";
+ sandbox.sandboxId = "sb_1";
+
+ await sandbox.createCheckpoint("autosave", {
+ retentionPolicy: { mode: "delete_oldest", maxCount: 3 },
+ });
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(init?.body as string)).toEqual({
+ name: "autosave",
+ retentionPolicy: { mode: "delete_oldest", maxCount: 3 },
+ });
+ });
+});
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index b2b3d26a..08f20edd 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -101,6 +101,14 @@ export interface CheckpointInfo {
createdAt: string;
}
+export type CheckpointRetentionPolicy =
+ | { mode: "none" }
+ | { mode: "delete_oldest"; maxCount?: number };
+
+export interface CreateCheckpointOptions {
+ retentionPolicy?: CheckpointRetentionPolicy;
+}
+
export interface PatchInfo {
id: string;
checkpointId: string;
@@ -693,14 +701,19 @@ export class Sandbox {
}
}
- async createCheckpoint(name: string): Promise<CheckpointInfo> {
+ async createCheckpoint(name: string, opts: CreateCheckpointOptions = {}): Promise<CheckpointInfo> {
+ const body: Record<string, unknown> = { name };
+ if (opts.retentionPolicy) {
+ body.retentionPolicy = opts.retentionPolicy;
+ }
+
const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
},
- body: JSON.stringify({ name }),
+ body: JSON.stringify(body),
});
if (!resp.ok) {