Skip to content

An open-source, faster Devin alternative

TypeScript

Add disk-only checkpoints (#423)

Mohamed Habibb584232602ff
diff --git a/.github/workflows/deploy-events-ingest.yml b/.github/workflows/deploy-events-ingest.yml
new file mode 100644
index 00000000..01bf23bb
--- /dev/null
+++ b/.github/workflows/deploy-events-ingest.yml
@@ -0,0 +1,106 @@
+name: Deploy Events Ingest
+
+# Mirrors deploy-api-edge.yml for the events-ingest Worker, which had no CI deploy
+# (it was deployed by hand). On merge to main touching its sources, deploy to prod.
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'cloudflare-workers/events-ingest/**'
+ - 'cloudflare-workers/shared/**'
+ - '.github/workflows/deploy-events-ingest.yml'
+ workflow_dispatch:
+ inputs:
+ target:
+ description: 'Cloudflare Worker target'
+ required: true
+ default: 'prod'
+ type: choice
+ options:
+ - prod
+ - dev
+
+concurrency:
+ group: deploy-events-ingest
+ cancel-in-progress: false
+
+jobs:
+ deploy:
+ name: Deploy Events Ingest
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+
+ - name: Resolve target
+ id: target
+ run: |
+ if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
+ TARGET="${{ inputs.target }}"
+ else
+ TARGET="prod"
+ fi
+
+ case "$TARGET" in
+ prod)
+ echo "config=wrangler.prod.toml" >> "$GITHUB_OUTPUT"
+ echo "name=opencomputer-events-ingest-prod" >> "$GITHUB_OUTPUT"
+ ;;
+ dev)
+ echo "config=wrangler.toml" >> "$GITHUB_OUTPUT"
+ echo "name=opensandbox-events-ingest-dev" >> "$GITHUB_OUTPUT"
+ ;;
+ *)
+ echo "unknown target: $TARGET" >&2
+ exit 1
+ ;;
+ esac
+
+ - name: Install events-ingest dependencies
+ working-directory: cloudflare-workers/events-ingest
+ run: npm ci
+
+ - name: Prepare CI deploy config
+ working-directory: cloudflare-workers/events-ingest
+ run: |
+ # Strip any `routes = [...]` block — the CI token may lack zone perms,
+ # and the worker is reached directly (CP forwarder / custom domain),
+ # not via a route. Mirrors the api-edge deploy.
+ python3 - <<'PY'
+ from pathlib import Path
+
+ src = Path("${{ steps.target.outputs.config }}")
+ dst = Path("wrangler.ci.toml")
+ lines = src.read_text().splitlines()
+
+ out = []
+ skipping_routes = False
+ for line in lines:
+ if line.startswith("routes = ["):
+ skipping_routes = True
+ continue
+ if skipping_routes:
+ if line.strip() == "]":
+ skipping_routes = False
+ continue
+ out.append(line)
+
+ dst.write_text("\n".join(out).rstrip() + "\n")
+ PY
+
+ - name: Deploy ${{ steps.target.outputs.name }}
+ working-directory: cloudflare-workers/events-ingest
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ run: |
+ if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
+ echo "CLOUDFLARE_API_TOKEN GitHub secret is required for Wrangler deploys" >&2
+ exit 1
+ fi
+ npx wrangler deploy -c wrangler.ci.toml
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 369b960a..fd6e4155 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -594,7 +594,7 @@ async function handleListCheckpoints(req: Request, env: DashboardEnv, caller: Ca
const offset = (page - 1) * perPage;
const { results } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, sandbox_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at, expires_at, name, status, error_msg, failed_at
+ `SELECT id, sandbox_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at, expires_at, name, status, error_msg, failed_at, kind
FROM checkpoints_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT ?2 OFFSET ?3`,
).bind(caller.orgID, perPage, offset).all<{
id: string; sandbox_id: string; owner_cell_id: string; s3_url: string | null;
@@ -602,6 +602,7 @@ async function handleListCheckpoints(req: Request, env: DashboardEnv, caller: Ca
created_at: number; expires_at: number | null;
name: string | null;
status: string | null; error_msg: string | null; failed_at: number | null;
+ kind: string | null;
}>();
const totalRow = await env.OPENCOMPUTER_DB.prepare(`SELECT COUNT(*) AS c FROM checkpoints_index WHERE org_id = ?1`).bind(caller.orgID).first<{ c: number }>();
return json({
@@ -621,6 +622,7 @@ async function handleListCheckpoints(req: Request, env: DashboardEnv, caller: Ca
createdAt: epochToISORequired(r.created_at),
errorMsg: r.error_msg ?? undefined,
failedAt: r.failed_at ? epochToISORequired(r.failed_at) : undefined,
+ kind: r.kind === "disk_only" ? "disk_only" : "full",
cellId: r.owner_cell_id ?? "",
goldenHash: r.golden_hash ?? "",
})),
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.ts
index fdcd2248..9d26bec2 100644
--- a/cloudflare-workers/events-ingest/src/index.ts
+++ b/cloudflare-workers/events-ingest/src/index.ts
@@ -249,8 +249,8 @@ export default {
// would rebase the delta onto the wrong base and break restore.
const checkpointUpsert = env.OPENCOMPUTER_DB.prepare(
`INSERT INTO checkpoints_index
- (id, sandbox_id, org_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at, name)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, ?8, ?9)
+ (id, sandbox_id, org_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at, name, kind)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, ?8, ?9, ?10)
ON CONFLICT(id) DO UPDATE SET
sandbox_id = excluded.sandbox_id,
owner_cell_id = excluded.owner_cell_id,
@@ -260,19 +260,21 @@ export default {
error_msg = NULL,
failed_at = NULL,
golden_hash = CASE WHEN checkpoints_index.golden_hash = '' THEN excluded.golden_hash ELSE checkpoints_index.golden_hash END,
- name = CASE WHEN excluded.name IS NULL OR excluded.name = '' THEN checkpoints_index.name ELSE excluded.name END`,
+ name = CASE WHEN excluded.name IS NULL OR excluded.name = '' THEN checkpoints_index.name ELSE excluded.name END,
+ kind = excluded.kind`,
);
const checkpointFailedUpsert = env.OPENCOMPUTER_DB.prepare(
`INSERT INTO checkpoints_index
- (id, sandbox_id, org_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at, name, status, error_msg, failed_at)
- VALUES (?1, ?2, ?3, ?4, '', 0, '', NULL, ?5, ?6, 'failed', ?7, ?8)
+ (id, sandbox_id, org_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at, name, status, error_msg, failed_at, kind)
+ VALUES (?1, ?2, ?3, ?4, '', 0, '', NULL, ?5, ?6, 'failed', ?7, ?8, ?9)
ON CONFLICT(id) DO UPDATE SET
sandbox_id = excluded.sandbox_id,
owner_cell_id = excluded.owner_cell_id,
status = 'failed',
error_msg = excluded.error_msg,
failed_at = excluded.failed_at,
- name = CASE WHEN excluded.name IS NULL OR excluded.name = '' THEN checkpoints_index.name ELSE excluded.name END`,
+ name = CASE WHEN excluded.name IS NULL OR excluded.name = '' THEN checkpoints_index.name ELSE excluded.name END,
+ kind = excluded.kind`,
);
const checkpointDelete = env.OPENCOMPUTER_DB.prepare(
`DELETE FROM checkpoints_index WHERE id = ?1`,
@@ -287,6 +289,7 @@ export default {
size_bytes?: number;
golden_hash?: string;
name?: string;
+ kind?: string;
error_msg?: string;
};
if (!p.checkpoint_id) return [];
@@ -305,6 +308,7 @@ export default {
p.name ?? null,
p.error_msg ?? "checkpoint failed",
tsSec,
+ p.kind === "disk_only" ? "disk_only" : "full",
),
];
}
@@ -324,6 +328,7 @@ export default {
p.golden_hash ?? "",
tsSec,
p.name ?? null,
+ p.kind === "disk_only" ? "disk_only" : "full",
),
];
});
diff --git a/cloudflare-workers/schema_phase8.sql b/cloudflare-workers/schema_phase8.sql
new file mode 100644
index 00000000..50c1e4d3
--- /dev/null
+++ b/cloudflare-workers/schema_phase8.sql
@@ -0,0 +1,15 @@
+-- Phase 8: checkpoint kind in the global D1 checkpoint index.
+--
+-- The dashboard reads /checkpoints from checkpoints_index, not directly from
+-- each cell's Postgres sandbox_checkpoints table. Disk-only checkpoints need
+-- their kind mirrored here so the dashboard can distinguish them from full
+-- checkpoints.
+--
+-- Apply before deploying api-edge/events-ingest code that reads or writes this
+-- column:
+-- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase8.sql
+--
+-- SQLite/D1 has no `ADD COLUMN IF NOT EXISTS`, so this is one-shot like the
+-- earlier phase files.
+
+ALTER TABLE checkpoints_index ADD COLUMN kind TEXT NOT NULL DEFAULT 'full';
diff --git a/cmd/oc/internal/commands/checkpoint.go b/cmd/oc/internal/commands/checkpoint.go
index d1f399ea..adc850b1 100644
--- a/cmd/oc/internal/commands/checkpoint.go
+++ b/cmd/oc/internal/commands/checkpoint.go
@@ -36,10 +36,24 @@ var checkpointCreateCmd = &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
c := client.FromContext(cmd.Context())
name, _ := cmd.Flags().GetString("name")
+ kind, _ := cmd.Flags().GetString("kind")
+ promoteToFull, _ := cmd.Flags().GetBool("promote-to-full")
retentionPolicy, _ := cmd.Flags().GetString("retention-policy")
retentionMaxCount, _ := cmd.Flags().GetInt("retention-max-count")
req := map[string]any{"name": name}
+ if kind != "" && kind != "full" {
+ if kind != "disk_only" {
+ return fmt.Errorf("unsupported checkpoint kind %q; expected full or disk_only", kind)
+ }
+ req["kind"] = kind
+ }
+ if promoteToFull {
+ if kind != "disk_only" {
+ return fmt.Errorf("--promote-to-full requires --kind disk_only")
+ }
+ req["promoteToFull"] = true
+ }
if retentionPolicy != "" && retentionPolicy != "none" {
if retentionPolicy != "delete_oldest" {
return fmt.Errorf("unsupported retention policy %q; expected none or delete_oldest", retentionPolicy)
@@ -197,8 +211,10 @@ func setCheckpointPublic(cmd *cobra.Command, id string, isPublic bool) error {
func init() {
checkpointCreateCmd.Flags().String("name", "", "Checkpoint name (required)")
+ checkpointCreateCmd.Flags().String("kind", "full", "Checkpoint kind (full, disk_only)")
+ checkpointCreateCmd.Flags().Bool("promote-to-full", false, "For disk_only checkpoints, asynchronously create a derived full checkpoint for faster forks")
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.Flags().Int("retention-max-count", 0, "Maximum checkpoints of this kind to keep when --retention-policy=delete_oldest (full: 1-10, disk_only: 1-100, 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 ce639417..8ebc1370 100644
--- a/docs/api-reference/checkpoints/create.mdx
+++ b/docs/api-reference/checkpoints/create.mdx
@@ -3,10 +3,11 @@ title: 'Create Checkpoint'
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.
+Create a checkpoint of the sandbox state. Each sandbox can have up to 10 full
+checkpoints and up to 100 disk-only checkpoints. By default, creating past the
+limit for that checkpoint type returns an error. Set `retentionPolicy.mode` to
+`delete_oldest` to delete the oldest eligible checkpoint of the same type first
+so the new checkpoint can be created.
<ParamField path="id" type="string" required>
Sandbox ID
@@ -16,10 +17,16 @@ checkpoint first so the new checkpoint can be created.
Checkpoint name (unique per sandbox)
</ParamField>
+<ParamField body="kind" type="string" default="full">
+ Checkpoint type. Use `full` to preserve disk, memory, and CPU state, or
+ `disk_only` to preserve only disk state with a larger per-sandbox limit.
+</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.
+ for full checkpoints or `{ "mode": "delete_oldest", "maxCount": 100 }` for
+ disk-only checkpoints to delete the oldest eligible checkpoint of the same
+ type before creating a new one.
</ParamField>
<ResponseExample>
diff --git a/docs/cli/checkpoint.mdx b/docs/cli/checkpoint.mdx
index 43fbde3f..ecce951e 100644
--- a/docs/cli/checkpoint.mdx
+++ b/docs/cli/checkpoint.mdx
@@ -52,15 +52,16 @@ oc cp list sb-abc123
oc cp delete sb-abc123 cp-7f3a1b2c
```
-Maximum 10 checkpoints per sandbox.
+Each sandbox can have up to 10 full checkpoints and up to 100 disk-only checkpoints.
-To create a new checkpoint at the limit, opt into automatic deletion of the oldest eligible checkpoint:
+To create a new checkpoint at the limit, opt into automatic deletion of the oldest eligible checkpoint of the same type:
```bash
oc cp create sb-abc123 \
--name autosave \
+ --kind disk_only \
--retention-policy delete_oldest \
- --retention-max-count 10
+ --retention-max-count 100
```
Retention skips public checkpoints, patched checkpoints, and checkpoints that are still referenced by forked sandboxes.
diff --git a/docs/how-it-works.mdx b/docs/how-it-works.mdx
index 3a1a49a1..c229f8d5 100644
--- a/docs/how-it-works.mdx
+++ b/docs/how-it-works.mdx
@@ -44,7 +44,7 @@ oc checkpoint spawn cp-xyz # → sandbox A
oc checkpoint spawn cp-xyz # → sandbox B
```
-Maximum 10 checkpoints per sandbox.
+Maximum 10 full checkpoints or 100 disk-only checkpoints per sandbox.
## Templates
diff --git a/docs/reference/cli/checkpoint.mdx b/docs/reference/cli/checkpoint.mdx
index ae885ef7..1ea3d949 100644
--- a/docs/reference/cli/checkpoint.mdx
+++ b/docs/reference/cli/checkpoint.mdx
@@ -18,7 +18,7 @@ Create a named checkpoint of a running sandbox. [HTTP API →](/api-reference/ch
</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.
+ Maximum checkpoints of this type to keep when `--retention-policy delete_oldest` is set. Must be between 1 and 10 for full checkpoints, or 1 and 100 for disk-only checkpoints.
</ParamField>
```bash
@@ -28,8 +28,9 @@ oc cp create sb-abc --name before-migration
```bash
oc cp create sb-abc \
--name autosave \
+ --kind disk_only \
--retention-policy delete_oldest \
- --retention-max-count 10
+ --retention-max-count 100
```
---
diff --git a/docs/reference/python-sdk.mdx b/docs/reference/python-sdk.mdx
index db410b63..15fee1ad 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, retention_policy=None): dict`
+#### `await sandbox.create_checkpoint(name, kind=None, promote_to_full=False, retention_policy=None): dict`
-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.
+Create a named checkpoint. Full checkpoints are limited to 10 per sandbox; disk-only checkpoints are limited to 100 per sandbox. Pass `retention_policy={"mode": "delete_oldest", "maxCount": 10}` for full checkpoints or `kind="disk_only", retention_policy={"mode": "delete_oldest", "maxCount": 100}` to delete the oldest eligible checkpoint of the same type before creating a new one. 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 685ce5ed..cf0f132a 100644
--- a/docs/reference/python-sdk/sandbox.mdx
+++ b/docs/reference/python-sdk/sandbox.mdx
@@ -175,14 +175,15 @@ Update idle timeout. [HTTP API →](/api-reference/sandboxes/set-timeout)
**Returns:** `None`
-### `await sandbox.create_checkpoint(name, retention_policy=None)`
+### `await sandbox.create_checkpoint(name, kind=None, promote_to_full=False, 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.
+ Optional retention policy. Use `{"mode": "delete_oldest", "maxCount": 10}`
+ for full checkpoints or `{"mode": "delete_oldest", "maxCount": 100}` with
+ `kind="disk_only"` to delete the oldest eligible checkpoint of the same type
+ before creating a new one.
</ParamField>
**Returns:** `dict`
diff --git a/docs/reference/typescript-sdk.mdx b/docs/reference/typescript-sdk.mdx
index 38b5799f..e70bb90e 100644
--- a/docs/reference/typescript-sdk.mdx
+++ b/docs/reference/typescript-sdk.mdx
@@ -132,7 +132,7 @@ Update the idle timeout.
#### `sandbox.createCheckpoint(name, opts?): Promise<CheckpointInfo>`
-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.
+Create a named checkpoint. Full checkpoints are limited to 10 per sandbox; disk-only checkpoints are limited to 100 per sandbox. Pass `retentionPolicy: { mode: "delete_oldest", maxCount: 10 }` for full checkpoints or `retentionPolicy: { mode: "delete_oldest", maxCount: 100 }` with `kind: "disk_only"` to delete the oldest eligible checkpoint of the same type before creating a new one.
#### `sandbox.listCheckpoints(): Promise<CheckpointInfo[]>`
diff --git a/docs/reference/typescript-sdk/sandbox.mdx b/docs/reference/typescript-sdk/sandbox.mdx
index 75472a7b..e6d9b04b 100644
--- a/docs/reference/typescript-sdk/sandbox.mdx
+++ b/docs/reference/typescript-sdk/sandbox.mdx
@@ -217,9 +217,10 @@ Create a named checkpoint. [HTTP API →](/api-reference/checkpoints/create)
</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.
+ Optional retention policy. Use `{ mode: "delete_oldest", maxCount: 10 }` for
+ full checkpoints or `{ mode: "delete_oldest", maxCount: 100 }` with
+ `kind: "disk_only"` to delete the oldest eligible checkpoint of the same type
+ before creating a new one.
</ParamField>
**Returns:** `Promise<CheckpointInfo>`
diff --git a/docs/sandboxes/checkpoints.mdx b/docs/sandboxes/checkpoints.mdx
index f2880e6e..8ab1eb42 100644
--- a/docs/sandboxes/checkpoints.mdx
+++ b/docs/sandboxes/checkpoints.mdx
@@ -5,6 +5,17 @@ description: "Snapshot and fork sandbox state"
A checkpoint is a named snapshot of a running sandbox. Fork new sandboxes from it to start from a known-good environment — like git branches for VMs.
+## Checkpoint Types
+
+OpenComputer supports two checkpoint modes:
+
+| Type | Preserves | Use when |
+| --- | --- | --- |
+| Full checkpoint | Disk, memory, and CPU state | You want the fastest fork or restore path from an exact running VM state. This is best for templates, important milestones, and branches you expect to fork often. |
+| Disk-only checkpoint | Rootfs and workspace disk state | You want lightweight, frequent snapshots of files, installed packages, and workspace changes. Forks boot from the saved disks, so they are cheaper to keep but may take longer to become ready. |
+
+Full checkpoints are the default. Use `kind: "disk_only"` when creating autosaves or high-frequency checkpoints where disk state is enough.
+
<CodeGroup>
```typescript TypeScript
@@ -79,33 +90,36 @@ oc cp create sb-abc123 --name before-migration
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:
+Each sandbox can have up to 10 full checkpoints and up to 100 disk-only checkpoints. To create a new checkpoint without failing at the limit, pass a retention policy that deletes the oldest eligible checkpoint of the same type first:
<CodeGroup>
```typescript TypeScript
const checkpoint = await sandbox.createCheckpoint("autosave", {
- retentionPolicy: { mode: "delete_oldest", maxCount: 10 },
+ kind: "disk_only",
+ retentionPolicy: { mode: "delete_oldest", maxCount: 100 },
});
```
```python Python
checkpoint = await sandbox.create_checkpoint(
"autosave",
- retention_policy={"mode": "delete_oldest", "maxCount": 10},
+ kind="disk_only",
+ retention_policy={"mode": "delete_oldest", "maxCount": 100},
)
```
```bash CLI
oc cp create sb-abc123 \
--name autosave \
+ --kind disk_only \
--retention-policy delete_oldest \
- --retention-max-count 10
+ --retention-max-count 100
```
</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.
+Retention skips checkpoints that are public, have patches, or are still referenced by forked sandboxes. If no eligible checkpoint of the requested type can be deleted, creation fails instead of deleting protected state.
### List Checkpoints
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index af88f8c7..8e9b8026 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -18,14 +18,27 @@ import (
"github.com/opensandbox/opensandbox/internal/edgeclient"
"github.com/opensandbox/opensandbox/internal/observability"
"github.com/opensandbox/opensandbox/internal/previewauth"
+ "github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/pkg/types"
pb "github.com/opensandbox/opensandbox/proto/worker"
)
-const maxCheckpointsPerSandbox = 10
+const (
+ maxFullCheckpointsPerSandbox = 10
+ maxDiskOnlyCheckpointsPerSandbox = 100
+)
+
+func maxCheckpointsForKind(kind string) int {
+ if kind == "disk_only" {
+ return maxDiskOnlyCheckpointsPerSandbox
+ }
+ return maxFullCheckpointsPerSandbox
+}
type createCheckpointRequest struct {
Name string `json:"name"`
+ Kind string `json:"kind"`
+ PromoteToFull bool `json:"promoteToFull"`
RetentionPolicy checkpointRetentionPolicy `json:"retentionPolicy"`
}
@@ -2180,9 +2193,22 @@ func (s *Server) createCheckpoint(c echo.Context) error {
if req.Name == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})
}
+ kind := req.Kind
+ if kind == "" {
+ kind = "full"
+ }
+ if kind != "full" && kind != "disk_only" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "kind must be full or disk_only"})
+ }
+ if req.PromoteToFull && kind != "disk_only" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "promoteToFull is only supported for disk_only checkpoints"})
+ }
- // Enforce max 10 checkpoints per sandbox
- count, err := s.store.CountCheckpoints(ctx, sandboxID)
+ // Enforce checkpoint limits per kind. Full checkpoints are heavier because
+ // they include memory/CPU state; disk-only checkpoints are cheaper and get
+ // a larger sandbox-local budget.
+ limit := maxCheckpointsForKind(kind)
+ count, err := s.store.CountCheckpointsByKind(ctx, sandboxID, kind)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to count checkpoints"})
}
@@ -2193,19 +2219,19 @@ func (s *Server) createCheckpoint(c echo.Context) error {
}
maxCount := req.RetentionPolicy.MaxCount
if maxCount == 0 {
- maxCount = maxCheckpointsPerSandbox
+ maxCount = limit
}
- if maxCount < 1 || maxCount > maxCheckpointsPerSandbox {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "retentionPolicy.maxCount must be between 1 and 10"})
+ if maxCount < 1 || maxCount > limit {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": fmt.Sprintf("retentionPolicy.maxCount must be between 1 and %d for %s checkpoints", limit, kind)})
}
if count >= maxCount {
deleteCount := count - maxCount + 1
- candidates, err := s.store.ListCheckpointRetentionCandidates(ctx, sandboxID, orgID, deleteCount)
+ candidates, err := s.store.ListCheckpointRetentionCandidatesByKind(ctx, sandboxID, orgID, kind, 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"})
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": fmt.Sprintf("maximum %d %s checkpoints per sandbox; no eligible checkpoint can be deleted by retention policy", limit, kind)})
}
for _, oldCP := range candidates {
if err := s.deleteCheckpointRecordAndObjects(ctx, &oldCP, orgID); err != nil {
@@ -2216,8 +2242,8 @@ func (s *Server) createCheckpoint(c echo.Context) error {
}
}
- if count >= maxCheckpointsPerSandbox {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "maximum 10 checkpoints per sandbox"})
+ if count >= limit {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": fmt.Sprintf("maximum %d %s checkpoints per sandbox", limit, kind)})
}
// Reserve a checkpoint UUID
@@ -2229,9 +2255,17 @@ func (s *Server) createCheckpoint(c echo.Context) error {
SandboxID: sandboxID,
OrgID: orgID,
Name: req.Name,
+ Kind: kind,
Status: "processing",
SandboxConfig: session.Config,
}
+ var promotedArtifactID string
+ if req.PromoteToFull {
+ promotionStatus := "pending"
+ promotedArtifactID = uuid.New().String()
+ cp.PromotionStatus = &promotionStatus
+ cp.PromotedCheckpointID = &promotedArtifactID
+ }
if err := s.store.CreateCheckpoint(ctx, cp); err != nil {
if strings.Contains(err.Error(), "duplicate key") || strings.Contains(err.Error(), "unique constraint") {
return c.JSON(http.StatusConflict, map[string]string{"error": "checkpoint name already exists for this sandbox"})
@@ -2266,6 +2300,7 @@ func (s *Server) createCheckpoint(c echo.Context) error {
grpcResp, err := grpcClient.CreateCheckpoint(grpcCtx, &pb.CreateCheckpointRequest{
SandboxId: sandboxID,
CheckpointId: checkpointID.String(),
+ Kind: kind,
})
// Signal that the sandbox is usable again (VM resumed, agent reconnected).
@@ -2294,6 +2329,9 @@ func (s *Server) createCheckpoint(c echo.Context) error {
s.recordLifecycleID(context.Background(), orgID, sandboxID, types.WebhookEventCheckpointCreated,
sandboxID+":sandbox.checkpoint.created:"+checkpointID.String(),
map[string]any{"checkpointId": checkpointID.String()})
+ if req.PromoteToFull {
+ s.startCheckpointPromotion(context.Background(), checkpointID, promotedArtifactID, sandboxID, req.Name, session.WorkerID, session.Config, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key)
+ }
}
golden := ""
if session.GoldenVersion != nil {
@@ -2311,6 +2349,7 @@ func (s *Server) createCheckpoint(c echo.Context) error {
// fell back to deriving from rootfs_s3_key, which always ends
// in "rootfs.tar.zst" — every row showed the same name.
"name": req.Name,
+ "kind": kind,
})
}()
} else if s.manager != nil {
@@ -2318,7 +2357,22 @@ func (s *Server) createCheckpoint(c echo.Context) error {
bgCtx, cancel := context.WithTimeout(context.Background(), 20*time.Minute)
defer cancel()
- rootfsKey, workspaceKey, sizeBytes, err := s.manager.CreateCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})
+ var rootfsKey, workspaceKey string
+ var sizeBytes int64
+ var err error
+ if kind == "disk_only" {
+ type diskOnlyCheckpointer interface {
+ CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (string, string, int64, error)
+ }
+ diskMgr, ok := s.manager.(diskOnlyCheckpointer)
+ if !ok {
+ err = fmt.Errorf("manager does not support disk-only checkpoints")
+ } else {
+ rootfsKey, workspaceKey, sizeBytes, err = diskMgr.CreateDiskOnlyCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})
+ }
+ } else {
+ rootfsKey, workspaceKey, sizeBytes, err = s.manager.CreateCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})
+ }
// Signal sandbox usable
pending.err = err
@@ -2340,6 +2394,9 @@ func (s *Server) createCheckpoint(c echo.Context) error {
s.recordLifecycleID(context.Background(), orgID, sandboxID, types.WebhookEventCheckpointCreated,
sandboxID+":sandbox.checkpoint.created:"+checkpointID.String(),
map[string]any{"checkpointId": checkpointID.String()})
+ if req.PromoteToFull {
+ s.startCheckpointPromotion(context.Background(), checkpointID, promotedArtifactID, sandboxID, req.Name, session.WorkerID, session.Config, rootfsKey, workspaceKey)
+ }
}
golden := ""
if session.GoldenVersion != nil {
@@ -2351,6 +2408,7 @@ func (s *Server) createCheckpoint(c echo.Context) error {
"size_bytes": sizeBytes,
"golden_hash": golden,
"name": req.Name,
+ "kind": kind,
})
}()
} else {
@@ -2361,6 +2419,107 @@ func (s *Server) createCheckpoint(c echo.Context) error {
return c.JSON(http.StatusCreated, cp)
}
+func (s *Server) startCheckpointPromotion(ctx context.Context, checkpointID uuid.UUID, promotedArtifactID, sourceSandboxID, checkpointName, workerID string, configJSON json.RawMessage, rootfsKey, workspaceKey string) {
+ if promotedArtifactID == "" {
+ promotedArtifactID = uuid.New().String()
+ }
+ go func() {
+ bgCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
+ defer cancel()
+ if err := s.store.SetCheckpointPromotionProcessing(bgCtx, checkpointID); err != nil {
+ log.Printf("api: checkpoint %s promotion status update failed: %v", checkpointID, err)
+ }
+ rootfs, workspace, size, err := s.promoteCheckpointToFull(bgCtx, checkpointID.String(), promotedArtifactID, sourceSandboxID, checkpointName, workerID, configJSON, rootfsKey, workspaceKey)
+ if err != nil {
+ log.Printf("api: checkpoint %s promotion failed: %v", checkpointID, err)
+ _ = s.store.SetCheckpointPromotionFailed(context.Background(), checkpointID, err.Error())
+ return
+ }
+ if err := s.store.SetCheckpointPromotionReady(context.Background(), checkpointID, promotedArtifactID, rootfs, workspace, size); err != nil {
+ log.Printf("api: checkpoint %s promotion ready update failed: %v", checkpointID, err)
+ return
+ }
+ log.Printf("api: checkpoint %s promoted to full artifact %s (size=%d bytes)", checkpointID, promotedArtifactID, size)
+ }()
+}
+
+func (s *Server) promoteCheckpointToFull(ctx context.Context, checkpointID, promotedArtifactID, sourceSandboxID, checkpointName, workerID string, configJSON json.RawMessage, rootfsKey, workspaceKey string) (string, string, int64, error) {
+ var cfg types.SandboxConfig
+ _ = json.Unmarshal(configJSON, &cfg)
+ cfg.SandboxID = "sb-" + uuid.New().String()[:8]
+ cfg.CheckpointID = checkpointID
+ cfg.TemplateRootfsKey = rootfsKey
+ cfg.TemplateWorkspaceKey = workspaceKey
+ cfg.AgentReadyTimeout = 90 * time.Second
+
+ if s.workerRegistry != nil {
+ grpcClient, err := s.workerRegistry.GetWorkerClient(workerID)
+ if err != nil {
+ return "", "", 0, fmt.Errorf("promotion worker unavailable: %w", err)
+ }
+ resp, err := grpcClient.CreateSandbox(ctx, &pb.CreateSandboxRequest{
+ Template: cfg.Template,
+ Timeout: int32(cfg.Timeout),
+ Envs: cfg.Envs,
+ MemoryMb: int32(cfg.MemoryMB),
+ CpuCount: int32(cfg.CpuCount),
+ NetworkEnabled: cfg.IsNetworkEnabled(),
+ Port: int32(cfg.Port),
+ TemplateRootfsKey: rootfsKey,
+ TemplateWorkspaceKey: workspaceKey,
+ CheckpointId: checkpointID,
+ SandboxId: cfg.SandboxID,
+ EgressAllowlist: cfg.EgressAllowlist,
+ SecretAllowedHosts: flattenSecretAllowedHosts(cfg.SecretAllowedHosts),
+ SecretEnvs: cfg.SecretEnvs,
+ DiskMb: int32(cfg.DiskMB),
+ })
+ if err != nil {
+ return "", "", 0, fmt.Errorf("boot promotion VM: %w", err)
+ }
+ promotionSandboxID := cfg.SandboxID
+ if resp != nil && resp.SandboxId != "" {
+ promotionSandboxID = resp.SandboxId
+ }
+ defer func() {
+ dctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ _, _ = grpcClient.DestroySandbox(dctx, &pb.DestroySandboxRequest{SandboxId: promotionSandboxID})
+ }()
+ cpResp, err := grpcClient.CreateCheckpoint(ctx, &pb.CreateCheckpointRequest{
+ SandboxId: promotionSandboxID,
+ CheckpointId: promotedArtifactID,
+ Kind: "full",
+ })
+ if err != nil {
+ return "", "", 0, fmt.Errorf("capture promoted full checkpoint: %w", err)
+ }
+ return cpResp.RootfsS3Key, cpResp.WorkspaceS3Key, cpResp.SizeBytes, nil
+ }
+
+ if s.manager == nil {
+ return "", "", 0, fmt.Errorf("sandbox execution not configured")
+ }
+ forkMgr, ok := s.manager.(interface {
+ ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)
+ })
+ if !ok {
+ return "", "", 0, fmt.Errorf("manager does not support checkpoint forks")
+ }
+ sb, err := forkMgr.ForkFromCheckpoint(ctx, checkpointID, cfg)
+ if err != nil {
+ return "", "", 0, fmt.Errorf("boot promotion VM: %w", err)
+ }
+ defer func() {
+ _ = s.manager.Kill(context.Background(), sb.ID)
+ }()
+ rootfs, workspace, size, err := s.manager.CreateCheckpoint(ctx, sb.ID, promotedArtifactID, s.checkpointStore, func() {})
+ if err != nil {
+ return "", "", 0, fmt.Errorf("capture promoted full checkpoint: %w", err)
+ }
+ return rootfs, workspace, size, nil
+}
+
// listCheckpoints returns all checkpoints for a sandbox.
func (s *Server) listCheckpoints(c echo.Context) error {
sandboxID := c.Param("id")
@@ -2600,6 +2759,19 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st
if cp.RootfsS3Key == nil || cp.WorkspaceS3Key == nil {
return nil, http.StatusBadRequest, fmt.Errorf("checkpoint S3 keys not available")
}
+ forkCheckpointID := checkpointID.String()
+ forkRootfsKey := *cp.RootfsS3Key
+ forkWorkspaceKey := *cp.WorkspaceS3Key
+ if cp.Kind == "disk_only" &&
+ cp.PromotionStatus != nil && *cp.PromotionStatus == "ready" &&
+ cp.PromotedCheckpointID != nil && *cp.PromotedCheckpointID != "" &&
+ cp.PromotedRootfsS3Key != nil && *cp.PromotedRootfsS3Key != "" &&
+ cp.PromotedWorkspaceS3Key != nil && *cp.PromotedWorkspaceS3Key != "" {
+ forkCheckpointID = *cp.PromotedCheckpointID
+ forkRootfsKey = *cp.PromotedRootfsS3Key
+ forkWorkspaceKey = *cp.PromotedWorkspaceS3Key
+ log.Printf("api: fork checkpoint %s using promoted full artifact %s", checkpointID, forkCheckpointID)
+ }
// Parse the original sandbox config to reuse settings
var originalCfg types.SandboxConfig
@@ -2793,9 +2965,9 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st
CpuCount: int32(originalCfg.CpuCount),
NetworkEnabled: originalCfg.IsNetworkEnabled(),
Port: int32(originalCfg.Port),
- TemplateRootfsKey: *cp.RootfsS3Key,
- TemplateWorkspaceKey: *cp.WorkspaceS3Key,
- CheckpointId: checkpointID.String(),
+ TemplateRootfsKey: forkRootfsKey,
+ TemplateWorkspaceKey: forkWorkspaceKey,
+ CheckpointId: forkCheckpointID,
SandboxId: sandboxID,
EgressAllowlist: originalCfg.EgressAllowlist,
SecretAllowedHosts: flattenSecretAllowedHosts(originalCfg.SecretAllowedHosts),
@@ -2809,16 +2981,16 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st
// Combined mode: create locally — no external timeout, same reasoning as above
cfg := originalCfg
cfg.Timeout = timeout
- cfg.TemplateRootfsKey = *cp.RootfsS3Key
- cfg.TemplateWorkspaceKey = *cp.WorkspaceS3Key
+ cfg.TemplateRootfsKey = forkRootfsKey
+ cfg.TemplateWorkspaceKey = forkWorkspaceKey
cfg.SandboxID = sandboxID
- cfg.CheckpointID = checkpointID.String()
+ cfg.CheckpointID = forkCheckpointID
forkMgr, hasFork := s.manager.(interface {
ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)
})
if hasFork {
- sb, err := forkMgr.ForkFromCheckpoint(context.Background(), checkpointID.String(), cfg)
+ sb, err := forkMgr.ForkFromCheckpoint(context.Background(), forkCheckpointID, cfg)
createErr = err
if sb != nil {
effectiveMemoryMB = sb.MemoryMB
@@ -2934,15 +3106,29 @@ func (s *Server) deleteCheckpointRecordAndObjects(ctx context.Context, cp *db.Ch
// Mirror the deletion to D1 checkpoints_index via events-ingest.
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 {
+ // Best-effort: delete S3 objects if checkpoint store is configured.
+ // Disk-only checkpoints may also own a derived full checkpoint artifact used
+ // for faster forks after background promotion.
+ if s.checkpointStore != nil {
+ keys := make([]string, 0, 4)
+ if cp.RootfsS3Key != nil {
+ keys = append(keys, *cp.RootfsS3Key)
+ }
+ if cp.WorkspaceS3Key != nil {
+ keys = append(keys, *cp.WorkspaceS3Key)
+ }
+ if cp.PromotedRootfsS3Key != nil {
+ keys = append(keys, *cp.PromotedRootfsS3Key)
+ }
+ if cp.PromotedWorkspaceS3Key != nil {
+ keys = append(keys, *cp.PromotedWorkspaceS3Key)
+ }
go func() {
bgCtx := context.Background()
- if err := s.checkpointStore.Delete(bgCtx, *cp.RootfsS3Key); err != nil {
- log.Printf("checkpoint: failed to delete S3 rootfs %s: %v", *cp.RootfsS3Key, err)
- }
- if err := s.checkpointStore.Delete(bgCtx, *cp.WorkspaceS3Key); err != nil {
- log.Printf("checkpoint: failed to delete S3 workspace %s: %v", *cp.WorkspaceS3Key, err)
+ for _, key := range keys {
+ if err := s.checkpointStore.Delete(bgCtx, key); err != nil {
+ log.Printf("checkpoint: failed to delete S3 object %s: %v", key, err)
+ }
}
}()
}
diff --git a/internal/db/migrations/050_checkpoint_kind.down.sql b/internal/db/migrations/050_checkpoint_kind.down.sql
new file mode 100644
index 00000000..2d7dfa29
--- /dev/null
+++ b/internal/db/migrations/050_checkpoint_kind.down.sql
@@ -0,0 +1,17 @@
+ALTER TABLE sandbox_checkpoints
+ DROP CONSTRAINT IF EXISTS sandbox_checkpoints_promotion_status_check;
+
+ALTER TABLE sandbox_checkpoints
+ DROP COLUMN IF EXISTS promotion_error,
+ DROP COLUMN IF EXISTS promoted_at,
+ DROP COLUMN IF EXISTS promoted_size_bytes,
+ DROP COLUMN IF EXISTS promoted_workspace_s3_key,
+ DROP COLUMN IF EXISTS promoted_rootfs_s3_key,
+ DROP COLUMN IF EXISTS promoted_checkpoint_id,
+ DROP COLUMN IF EXISTS promotion_status;
+
+ALTER TABLE sandbox_checkpoints
+ DROP CONSTRAINT IF EXISTS sandbox_checkpoints_kind_check;
+
+ALTER TABLE sandbox_checkpoints
+ DROP COLUMN IF EXISTS kind;
diff --git a/internal/db/migrations/050_checkpoint_kind.up.sql b/internal/db/migrations/050_checkpoint_kind.up.sql
new file mode 100644
index 00000000..b5e36091
--- /dev/null
+++ b/internal/db/migrations/050_checkpoint_kind.up.sql
@@ -0,0 +1,19 @@
+ALTER TABLE sandbox_checkpoints
+ ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'full';
+
+ALTER TABLE sandbox_checkpoints
+ ADD CONSTRAINT sandbox_checkpoints_kind_check
+ CHECK (kind IN ('full', 'disk_only'));
+
+ALTER TABLE sandbox_checkpoints
+ ADD COLUMN IF NOT EXISTS promotion_status TEXT,
+ ADD COLUMN IF NOT EXISTS promoted_checkpoint_id TEXT,
+ ADD COLUMN IF NOT EXISTS promoted_rootfs_s3_key TEXT,
+ ADD COLUMN IF NOT EXISTS promoted_workspace_s3_key TEXT,
+ ADD COLUMN IF NOT EXISTS promoted_size_bytes BIGINT,
+ ADD COLUMN IF NOT EXISTS promoted_at TIMESTAMPTZ,
+ ADD COLUMN IF NOT EXISTS promotion_error TEXT;
+
+ALTER TABLE sandbox_checkpoints
+ ADD CONSTRAINT sandbox_checkpoints_promotion_status_check
+ CHECK (promotion_status IS NULL OR promotion_status IN ('pending', 'processing', 'ready', 'failed'));
diff --git a/internal/db/store.go b/internal/db/store.go
index 1dd50aab..04f2ef70 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -197,6 +197,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{47, "migrations/047_orgs_billing_provider.up.sql"},
{48, "migrations/048_orgs_usage_sync_watermark.up.sql"},
{49, "migrations/049_sandbox_webhooks.up.sql"},
+ {50, "migrations/050_checkpoint_kind.up.sql"},
}
for _, m := range migrations {
@@ -1998,17 +1999,25 @@ func (s *Store) UpsertWorkspaceBackup(ctx context.Context, sandboxID string, org
// Checkpoint represents a named checkpoint for a sandbox.
type Checkpoint struct {
- ID uuid.UUID `json:"id"`
- SandboxID string `json:"sandboxId"`
- OrgID uuid.UUID `json:"orgId"`
- Name string `json:"name"`
- RootfsS3Key *string `json:"rootfsS3Key,omitempty"`
- WorkspaceS3Key *string `json:"workspaceS3Key,omitempty"`
- SandboxConfig json.RawMessage `json:"sandboxConfig"`
- Status string `json:"status"`
- SizeBytes int64 `json:"sizeBytes"`
- IsPublic bool `json:"isPublic"`
- CreatedAt time.Time `json:"createdAt"`
+ ID uuid.UUID `json:"id"`
+ SandboxID string `json:"sandboxId"`
+ OrgID uuid.UUID `json:"orgId"`
+ Name string `json:"name"`
+ RootfsS3Key *string `json:"rootfsS3Key,omitempty"`
+ WorkspaceS3Key *string `json:"workspaceS3Key,omitempty"`
+ SandboxConfig json.RawMessage `json:"sandboxConfig"`
+ Kind string `json:"kind"`
+ PromotionStatus *string `json:"promotionStatus,omitempty"`
+ PromotedCheckpointID *string `json:"promotedCheckpointId,omitempty"`
+ PromotedRootfsS3Key *string `json:"promotedRootfsS3Key,omitempty"`
+ PromotedWorkspaceS3Key *string `json:"promotedWorkspaceS3Key,omitempty"`
+ PromotedSizeBytes *int64 `json:"promotedSizeBytes,omitempty"`
+ PromotedAt *time.Time `json:"promotedAt,omitempty"`
+ PromotionError *string `json:"promotionError,omitempty"`
+ Status string `json:"status"`
+ SizeBytes int64 `json:"sizeBytes"`
+ IsPublic bool `json:"isPublic"`
+ CreatedAt time.Time `json:"createdAt"`
// ErrorMsg holds the failure reason when Status == "failed". Persisted by
// SetCheckpointFailed so customers/operators can see WHY a checkpoint
// failed (timeout, archive error, S3 upload error, etc.) instead of just
@@ -2019,11 +2028,14 @@ type Checkpoint struct {
// CreateCheckpoint inserts a new checkpoint record.
func (s *Store) CreateCheckpoint(ctx context.Context, cp *Checkpoint) error {
+ if cp.Kind == "" {
+ cp.Kind = "full"
+ }
return s.pool.QueryRow(ctx,
- `INSERT INTO sandbox_checkpoints (id, sandbox_id, org_id, name, sandbox_config)
- VALUES ($1, $2, $3, $4, $5)
+ `INSERT INTO sandbox_checkpoints (id, sandbox_id, org_id, name, sandbox_config, kind, promotion_status, promoted_checkpoint_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING created_at`,
- cp.ID, cp.SandboxID, cp.OrgID, cp.Name, cp.SandboxConfig,
+ cp.ID, cp.SandboxID, cp.OrgID, cp.Name, cp.SandboxConfig, cp.Kind, cp.PromotionStatus, cp.PromotedCheckpointID,
).Scan(&cp.CreatedAt)
}
@@ -2071,15 +2083,71 @@ func (s *Store) SetCheckpointFailed(ctx context.Context, checkpointID uuid.UUID,
return err
}
+// SetCheckpointPromotionProcessing marks the derived full-checkpoint promotion as running.
+func (s *Store) SetCheckpointPromotionProcessing(ctx context.Context, checkpointID uuid.UUID) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_checkpoints
+ SET promotion_status = 'processing',
+ promotion_error = NULL
+ WHERE id = $1`,
+ checkpointID)
+ return err
+}
+
+// SetCheckpointPromotionReady records the full-checkpoint artifact derived from a disk-only checkpoint.
+func (s *Store) SetCheckpointPromotionReady(ctx context.Context, checkpointID uuid.UUID, promotedID, rootfsKey, workspaceKey string, sizeBytes int64) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_checkpoints
+ SET promotion_status = 'ready',
+ promoted_checkpoint_id = $2,
+ promoted_rootfs_s3_key = $3,
+ promoted_workspace_s3_key = $4,
+ promoted_size_bytes = $5,
+ promoted_at = now(),
+ promotion_error = NULL
+ WHERE id = $1`,
+ checkpointID, promotedID, rootfsKey, workspaceKey, sizeBytes)
+ return err
+}
+
+// SetCheckpointPromotionFailed records that asynchronous full promotion failed.
+func (s *Store) SetCheckpointPromotionFailed(ctx context.Context, checkpointID uuid.UUID, reason string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_checkpoints
+ SET promotion_status = 'failed',
+ promotion_error = $2
+ WHERE id = $1`,
+ checkpointID, reason)
+ return err
+}
+
+const checkpointSelectColumns = `id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, kind,
+ promotion_status, promoted_checkpoint_id, promoted_rootfs_s3_key, promoted_workspace_s3_key,
+ promoted_size_bytes, promoted_at, promotion_error,
+ status, size_bytes, is_public, created_at, error_msg, failed_at`
+
+const checkpointSelectColumnsWithAlias = `c.id, c.sandbox_id, c.org_id, c.name, c.rootfs_s3_key, c.workspace_s3_key, c.sandbox_config, c.kind,
+ c.promotion_status, c.promoted_checkpoint_id, c.promoted_rootfs_s3_key, c.promoted_workspace_s3_key,
+ c.promoted_size_bytes, c.promoted_at, c.promotion_error,
+ c.status, c.size_bytes, c.is_public, c.created_at, c.error_msg, c.failed_at`
+
+func scanCheckpoint(scanner interface {
+ Scan(dest ...any) error
+}, cp *Checkpoint) error {
+ return scanner.Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,
+ &cp.SandboxConfig, &cp.Kind, &cp.PromotionStatus, &cp.PromotedCheckpointID, &cp.PromotedRootfsS3Key,
+ &cp.PromotedWorkspaceS3Key, &cp.PromotedSizeBytes, &cp.PromotedAt, &cp.PromotionError,
+ &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt,
+ &cp.ErrorMsg, &cp.FailedAt)
+}
+
// GetCheckpoint returns a checkpoint by ID.
func (s *Store) GetCheckpoint(ctx context.Context, checkpointID uuid.UUID) (*Checkpoint, error) {
cp := &Checkpoint{}
- err := s.pool.QueryRow(ctx,
- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at, error_msg, failed_at
+ err := scanCheckpoint(s.pool.QueryRow(ctx,
+ `SELECT `+checkpointSelectColumns+`
FROM sandbox_checkpoints WHERE id = $1`, checkpointID,
- ).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)
+ ), cp)
if err != nil {
return nil, fmt.Errorf("checkpoint not found: %w", err)
}
@@ -2089,7 +2157,7 @@ func (s *Store) GetCheckpoint(ctx context.Context, checkpointID uuid.UUID) (*Che
// ListCheckpoints returns all checkpoints for a sandbox, newest first.
func (s *Store) ListCheckpoints(ctx context.Context, sandboxID string) ([]Checkpoint, error) {
rows, err := s.pool.Query(ctx,
- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at, error_msg, failed_at
+ `SELECT `+checkpointSelectColumns+`
FROM sandbox_checkpoints WHERE sandbox_id = $1 ORDER BY created_at DESC`, sandboxID)
if err != nil {
return nil, err
@@ -2099,9 +2167,7 @@ func (s *Store) ListCheckpoints(ctx context.Context, sandboxID string) ([]Checkp
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 {
+ if err := scanCheckpoint(rows, &cp); err != nil {
return nil, err
}
checkpoints = append(checkpoints, cp)
@@ -2126,9 +2192,7 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,
}
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,
+ `SELECT `+checkpointSelectColumnsWithAlias+`,
(SELECT COUNT(*) FROM sandbox_sessions ss WHERE ss.based_on_checkpoint_id = c.id AND ss.status IN ('running', 'hibernated')) AS active_forks,
(SELECT COUNT(*) FROM sandbox_sessions ss WHERE ss.based_on_checkpoint_id = c.id) AS total_forks
FROM sandbox_checkpoints c WHERE c.org_id = $1
@@ -2142,9 +2206,10 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,
for rows.Next() {
var cf CheckpointWithForks
if err := rows.Scan(&cf.ID, &cf.SandboxID, &cf.OrgID, &cf.Name, &cf.RootfsS3Key, &cf.WorkspaceS3Key,
- &cf.SandboxConfig, &cf.Status, &cf.SizeBytes, &cf.IsPublic, &cf.CreatedAt,
- &cf.ErrorMsg, &cf.FailedAt,
- &cf.ActiveForks, &cf.TotalForks); err != nil {
+ &cf.SandboxConfig, &cf.Kind, &cf.PromotionStatus, &cf.PromotedCheckpointID, &cf.PromotedRootfsS3Key,
+ &cf.PromotedWorkspaceS3Key, &cf.PromotedSizeBytes, &cf.PromotedAt, &cf.PromotionError,
+ &cf.Status, &cf.SizeBytes, &cf.IsPublic, &cf.CreatedAt,
+ &cf.ErrorMsg, &cf.FailedAt, &cf.ActiveForks, &cf.TotalForks); err != nil {
return nil, 0, err
}
results = append(results, cf)
@@ -2155,12 +2220,10 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,
// GetCheckpointByName looks up a checkpoint by sandbox-scoped name.
func (s *Store) GetCheckpointByName(ctx context.Context, sandboxID, name string) (*Checkpoint, error) {
cp := &Checkpoint{}
- err := s.pool.QueryRow(ctx,
- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at, error_msg, failed_at
+ err := scanCheckpoint(s.pool.QueryRow(ctx,
+ `SELECT `+checkpointSelectColumns+`
FROM sandbox_checkpoints WHERE sandbox_id = $1 AND name = $2`, sandboxID, name,
- ).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)
+ ), cp)
if err != nil {
return nil, fmt.Errorf("checkpoint not found: %w", err)
}
@@ -2175,21 +2238,35 @@ func (s *Store) CountCheckpoints(ctx context.Context, sandboxID string) (int, er
return count, err
}
+// CountCheckpointsByKind returns the number of checkpoints of a specific kind for a sandbox.
+func (s *Store) CountCheckpointsByKind(ctx context.Context, sandboxID, kind string) (int, error) {
+ var count int
+ err := s.pool.QueryRow(ctx,
+ `SELECT COUNT(*) FROM sandbox_checkpoints WHERE sandbox_id = $1 AND kind = $2`, sandboxID, kind).Scan(&count)
+ 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) {
+ return s.ListCheckpointRetentionCandidatesByKind(ctx, sandboxID, orgID, "", limit)
+}
+
+// ListCheckpointRetentionCandidatesByKind returns the oldest checkpoints of a
+// specific kind that can be deleted by an automatic retention policy. When
+// kind is empty, all checkpoint kinds are eligible.
+func (s *Store) ListCheckpointRetentionCandidatesByKind(ctx context.Context, sandboxID string, orgID uuid.UUID, kind string, 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
+ `SELECT `+checkpointSelectColumnsWithAlias+`
FROM sandbox_checkpoints c
WHERE c.sandbox_id = $1
AND c.org_id = $2
+ AND ($3 = '' OR c.kind = $3)
AND c.is_public = false
AND NOT EXISTS (
SELECT 1 FROM checkpoint_patches p WHERE p.checkpoint_id = c.id
@@ -2198,7 +2275,7 @@ func (s *Store) ListCheckpointRetentionCandidates(ctx context.Context, sandboxID
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)
+ LIMIT $4`, sandboxID, orgID, kind, limit)
if err != nil {
return nil, err
}
@@ -2207,9 +2284,7 @@ func (s *Store) ListCheckpointRetentionCandidates(ctx context.Context, sandboxID
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 {
+ if err := scanCheckpoint(rows, &cp); err != nil {
return nil, err
}
checkpoints = append(checkpoints, cp)
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index d7193e23..a4844ffa 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -207,6 +207,30 @@ func quiesceAndCloseAgent(ctx context.Context, agent *AgentClient) error {
return nil
}
+func freezeGuestFilesystemsForDiskSnapshot(ctx context.Context, agent *AgentClient) error {
+ if agent == nil {
+ return fmt.Errorf("%w: missing agent", ErrAgentUnresponsive)
+ }
+ freezeCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
+ defer cancel()
+ _, err := agent.Exec(freezeCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", strings.Join([]string{
+ "set -eu",
+ "sync",
+ "blockdev --flushbufs /dev/vda 2>/dev/null || true",
+ "blockdev --flushbufs /dev/vdb 2>/dev/null || true",
+ `targets="$(for p in /home/sandbox /; do findmnt -n -T "$p" -o TARGET 2>/dev/null || echo "$p"; done | awk '!seen[$0]++')"`,
+ "for mp in $targets; do fsfreeze --freeze \"$mp\"; done",
+ }, "\n")},
+ RunAsRoot: true,
+ })
+ if err != nil {
+ return fmt.Errorf("%w: fsfreeze failed: %v", ErrAgentUnresponsive, err)
+ }
+ return nil
+}
+
// Compile-time check that Manager implements sandbox.Manager.
var _ sandbox.Manager = (*Manager)(nil)
@@ -3312,6 +3336,159 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
return rootfsKey, workspaceKey, sizeBytes, nil
}
+func (m *Manager) CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, sizeBytes int64, err error) {
+ tStart := time.Now()
+ failureReason := "other"
+ template := "unknown"
+ defer func() {
+ status := "success"
+ if err != nil {
+ status = "failure"
+ metrics.CheckpointFailuresTotal.WithLabelValues(m.cfg.Region, template, failureReason).Inc()
+ }
+ metrics.CheckpointDuration.WithLabelValues(m.cfg.Region, template, status).Observe(time.Since(tStart).Seconds())
+ }()
+
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ failureReason = "vm_not_found"
+ return "", "", 0, err
+ }
+ template = vm.Template
+ if err := m.checkRootfsPressure(ctx, vm); err != nil {
+ failureReason = "disk_pressure"
+ return "", "", 0, err
+ }
+ if !vm.opMu.TryLock() {
+ failureReason = "op_in_progress"
+ return "", "", 0, fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)
+ }
+ defer vm.opMu.Unlock()
+ if vm.qmp == nil {
+ failureReason = "qmp_unavailable"
+ return "", "", 0, fmt.Errorf("QMP connection not available for %s", sandboxID)
+ }
+ if vm.agent == nil {
+ failureReason = "agent_unresponsive"
+ return "", "", 0, fmt.Errorf("checkpoint %s: %w", sandboxID, ErrAgentUnresponsive)
+ }
+
+ t0 := time.Now()
+ cacheDir := m.checkpointCacheDir(checkpointID)
+ stagingDir := cacheDir + ".staging"
+ if mkErr := os.MkdirAll(filepath.Join(stagingDir, "snapshot"), 0755); mkErr != nil {
+ failureReason = "staging_setup"
+ return "", "", 0, fmt.Errorf("mkdir staging: %w", mkErr)
+ }
+ defer func() {
+ if err != nil {
+ os.RemoveAll(stagingDir)
+ }
+ }()
+
+ if qErr := freezeGuestFilesystemsForDiskSnapshot(ctx, vm.agent); qErr != nil {
+ failureReason = "agent_unresponsive"
+ return "", "", 0, fmt.Errorf("disk-only checkpoint %s: %w", sandboxID, qErr)
+ }
+ frozen := true
+ stopped := false
+ defer func() {
+ if stopped {
+ if contErr := vm.qmp.Cont(); contErr != nil {
+ log.Printf("qemu: DiskOnlyCheckpoint %s/%s: failed to resume VM: %v", sandboxID, checkpointID, contErr)
+ }
+ }
+ if frozen {
+ m.agentFsThawAfterWake(context.Background(), sandboxID, vm.agent)
+ }
+ }()
+
+ if stopErr := vm.qmp.Stop(); stopErr != nil {
+ failureReason = "qmp_stop"
+ return "", "", 0, fmt.Errorf("qmp stop before disk-only copy: %w", stopErr)
+ }
+ stopped = true
+
+ srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.qcow2")
+ srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")
+ if err := copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2")); err != nil {
+ failureReason = "qcow2_copy"
+ return "", "", 0, fmt.Errorf("copy rootfs: %w", err)
+ }
+ if err := copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2")); err != nil {
+ failureReason = "qcow2_copy"
+ return "", "", 0, fmt.Errorf("copy workspace: %w", err)
+ }
+ if contErr := vm.qmp.Cont(); contErr != nil {
+ log.Printf("qemu: DiskOnlyCheckpoint %s/%s: failed to resume VM after copy: %v", sandboxID, checkpointID, contErr)
+ } else {
+ stopped = false
+ }
+ m.agentFsThawAfterWake(context.Background(), sandboxID, vm.agent)
+ frozen = false
+
+ rootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)
+ workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)
+ meta := &SnapshotMeta{
+ SandboxID: vm.ID,
+ Network: vm.network,
+ GuestCID: vm.guestCID,
+ GuestMAC: vm.guestMAC,
+ BootArgs: vm.bootArgs,
+ CpuCount: vm.CpuCount,
+ MemoryMB: vm.MemoryMB,
+ BaseMemoryMB: vm.baseMemoryMB,
+ Template: vm.Template,
+ GuestPort: vm.GuestPort,
+ GoldenVersion: vm.goldenVersion,
+ SnapshotedAt: time.Now(),
+ }
+ if m.secretsProxy != nil && vm.network != nil {
+ meta.SealedTokens = m.secretsProxy.GetSessionTokens(vm.network.GuestIP)
+ meta.EgressAllowlist = m.secretsProxy.GetSessionAllowlist(vm.network.GuestIP)
+ meta.TokenHosts = m.secretsProxy.GetSessionTokenHosts(vm.network.GuestIP)
+ }
+ metaJSON, _ := json.Marshal(meta)
+ _ = os.WriteFile(filepath.Join(stagingDir, "snapshot", "snapshot-meta.json"), metaJSON, 0644)
+
+ m.checkpointCacheMu.Lock()
+ os.RemoveAll(cacheDir)
+ if renameErr := os.Rename(stagingDir, cacheDir); renameErr != nil {
+ m.checkpointCacheMu.Unlock()
+ failureReason = "staging_setup"
+ return "", "", 0, fmt.Errorf("rename staging to cache: %w", renameErr)
+ }
+ m.checkpointCacheMu.Unlock()
+ log.Printf("qemu: disk-only checkpoint %s: cache saved (%dms)", checkpointID, time.Since(t0).Milliseconds())
+
+ if checkpointStore != nil {
+ archiveFiles := []string{"rootfs.qcow2", "workspace.qcow2", filepath.Join("snapshot", "snapshot-meta.json")}
+ archivePath := filepath.Join(cacheDir, "checkpoint.tar.zst")
+ if archErr := createArchive(archivePath, cacheDir, archiveFiles); archErr != nil {
+ failureReason = "archive"
+ return rootfsKey, workspaceKey, 0, fmt.Errorf("create disk-only checkpoint archive: %w", archErr)
+ }
+ uploadCtx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
+ _, uerr := checkpointStore.Upload(uploadCtx, rootfsKey, archivePath)
+ cancel()
+ if info, statErr := os.Stat(archivePath); statErr == nil {
+ sizeBytes = info.Size()
+ }
+ os.Remove(archivePath)
+ if uerr != nil {
+ failureReason = "s3_upload"
+ return rootfsKey, workspaceKey, sizeBytes, fmt.Errorf("upload disk-only checkpoint to S3: %w", uerr)
+ }
+ log.Printf("qemu: disk-only checkpoint %s: S3 upload complete (%dms, %.1f MB)",
+ checkpointID, time.Since(t0).Milliseconds(), float64(sizeBytes)/(1024*1024))
+ }
+
+ if onReady != nil {
+ onReady()
+ }
+ return rootfsKey, workspaceKey, sizeBytes, nil
+}
+
// RestoreFromCheckpoint reverts a sandbox to a checkpoint by killing the current
// QEMU process and starting a fresh one from the checkpoint's cached qcow2 drives.
// In-place loadvm corrupts the qcow2 COW layer because blocks written after the
@@ -3391,8 +3568,11 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
incomingURI = fmt.Sprintf("exec:cat %s", memRaw)
}
+ snapshotNamePath := filepath.Join(cacheDir, "snapshot-name")
+ hasSnapshotName := fileExists(snapshotNamePath)
+ coldBoot := incomingURI == "" && !hasSnapshotName
snapshotName := "cp-" + checkpointID
- if data, err := os.ReadFile(filepath.Join(cacheDir, "snapshot-name")); err == nil {
+ if data, err := os.ReadFile(snapshotNamePath); err == nil {
snapshotName = strings.TrimSpace(string(data))
}
@@ -3465,6 +3645,9 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
}
// Remember what the user had so we can re-scale after restore
desiredMemMB := vm.MemoryMB
+ if coldBoot && desiredMemMB > bootMemMB {
+ bootMemMB = desiredMemMB
+ }
logFile, _ := os.Create(filepath.Join(sandboxDir, "qemu.log"))
args := m.buildQEMUArgs(bootCpus, bootMemMB, rootfsPath, workspacePath,
@@ -3473,7 +3656,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
if incomingURI != "" {
// Migration-based restore: QEMU loads state from the mem dump file.
args = append(args, "-incoming", incomingURI)
- } else {
+ } else if !coldBoot {
// Savevm-based fallback: start paused, then loadvm.
args = append(args, "-S")
}
@@ -3510,7 +3693,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
m.cleanupVM(netCfg, "")
return fmt.Errorf("migration load: %w", err)
}
- } else {
+ } else if !coldBoot {
// Savevm fallback: load the internal snapshot.
if err := qmpClient.LoadVM(snapshotName); err != nil {
qmpClient.Close()
@@ -3524,7 +3707,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
// Re-scale virtio-mem BEFORE cont — the VM is paused, so the kernel sees full
// memory immediately on resume. Without this, restored processes that were using
// >baseMemMB would OOM before the post-resume re-scale completes.
- if desiredMemMB > bootMemMB {
+ if !coldBoot && desiredMemMB > bootMemMB {
additionalMB := alignVirtioMemBlock(desiredMemMB - bootMemMB)
if err := qmpClient.SetVirtioMemSize(additionalMB); err != nil {
log.Printf("qemu: RestoreFromCheckpoint %s: pre-resume scale to %dMB failed: %v (continuing with base %dMB)",
@@ -3535,12 +3718,14 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
}
}
- if err := qmpClient.Cont(); err != nil {
- qmpClient.Close()
- cmd.Process.Kill()
- cmd.Wait()
- m.cleanupVM(netCfg, "")
- return fmt.Errorf("cont: %w", err)
+ if !coldBoot {
+ if err := qmpClient.Cont(); err != nil {
+ qmpClient.Close()
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ return fmt.Errorf("cont: %w", err)
+ }
}
// Step 7: Reconnect agent + patch network
@@ -3777,6 +3962,20 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
// Fall back to the old loadvm path.
incomingURI = ""
}
+ snapshotNamePath := filepath.Join(cacheDir, "snapshot-name")
+ hasSnapshotName := fileExists(snapshotNamePath)
+ coldBoot := incomingURI == "" && !hasSnapshotName
+ if coldBoot {
+ if cfg.CpuCount > 0 {
+ cpus = cfg.CpuCount
+ }
+ if cfg.MemoryMB > 0 {
+ memMB = cfg.MemoryMB
+ } else if meta.MemoryMB > 0 {
+ memMB = meta.MemoryMB
+ }
+ desiredMemMB = memMB
+ }
// Boot QEMU, load the checkpoint (migration or loadvm), and connect the
// agent inside. Post-loadvm virtio-serial occasionally comes up with the
@@ -3798,7 +3997,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)
if incomingURI != "" {
args = append(args, "-incoming", incomingURI)
- } else {
+ } else if !coldBoot {
args = append(args, "-S")
}
@@ -3833,9 +4032,9 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
cmd.Wait()
return nil, nil, nil, fmt.Errorf("migration load: %w", err)
}
- } else {
+ } else if !coldBoot {
snapshotName := "cp-" + checkpointID
- if data, readErr := os.ReadFile(filepath.Join(cacheDir, "snapshot-name")); readErr == nil {
+ if data, readErr := os.ReadFile(snapshotNamePath); readErr == nil {
snapshotName = strings.TrimSpace(string(data))
}
if err := qmpClient.LoadVM(snapshotName); err != nil {
@@ -3849,7 +4048,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
// Honor cfg.MemoryMB above the snapshot base via pre-Cont virtio-mem
// plug. VM is paused, so the kernel sees the full memory map on resume —
// same pattern as RestoreFromCheckpoint and wake-from-hibernate.
- if desiredMemMB > memMB {
+ if !coldBoot && desiredMemMB > memMB {
additionalMB := alignVirtioMemBlock(desiredMemMB - memMB)
if err := qmpClient.SetVirtioMemSize(additionalMB); err != nil {
log.Printf("qemu: ForkFromCheckpoint %s: pre-resume virtio-mem plug to +%dMB failed: %v (continuing at base %dMB)",
@@ -3860,11 +4059,13 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
}
}
- if err := qmpClient.Cont(); err != nil {
- qmpClient.Close()
- cmd.Process.Kill()
- cmd.Wait()
- return nil, nil, nil, fmt.Errorf("QMP cont: %w", err)
+ if !coldBoot {
+ if err := qmpClient.Cont(); err != nil {
+ qmpClient.Close()
+ cmd.Process.Kill()
+ cmd.Wait()
+ return nil, nil, nil, fmt.Errorf("QMP cont: %w", err)
+ }
}
log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms), connecting agent...",
checkpointID, id, time.Since(t0).Milliseconds())
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 40110034..adee2ff7 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -314,6 +314,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
return &pb.CreateSandboxResponse{
SandboxId: sb.ID,
Status: string(sb.Status),
+ MemoryMb: int32(sb.MemoryMB),
}, nil
}
@@ -903,6 +904,16 @@ func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpo
var rootfsKey, workspaceKey string
var sizeBytes int64
var err error
+ kind := req.Kind
+ if kind == "" {
+ kind = "full"
+ }
+ if kind != "full" && kind != "disk_only" {
+ return nil, fmt.Errorf("unsupported checkpoint kind %q", kind)
+ }
+ if kind == "disk_only" && req.FinalizeMemoryMb > 0 {
+ return nil, fmt.Errorf("disk-only checkpoints do not support finalize_memory_mb")
+ }
if req.FinalizeMemoryMb > 0 {
type finalizer interface {
CreateCheckpointFinalized(ctx context.Context, buildSandboxID, checkpointID string, store *storage.CheckpointStore, finalizeMemMB int, onReady func()) (string, string, int64, error)
@@ -912,6 +923,15 @@ func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpo
return nil, fmt.Errorf("manager does not support finalized checkpoints")
}
rootfsKey, workspaceKey, sizeBytes, err = fz.CreateCheckpointFinalized(ctx, req.SandboxId, checkpointID, s.checkpointStore, int(req.FinalizeMemoryMb), onReady)
+ } else if kind == "disk_only" {
+ type diskOnlyCheckpointer interface {
+ CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checkpointID string, store *storage.CheckpointStore, onReady func()) (string, string, int64, error)
+ }
+ diskMgr, ok := s.manager.(diskOnlyCheckpointer)
+ if !ok {
+ return nil, fmt.Errorf("manager does not support disk-only checkpoints")
+ }
+ rootfsKey, workspaceKey, sizeBytes, err = diskMgr.CreateDiskOnlyCheckpoint(ctx, req.SandboxId, checkpointID, s.checkpointStore, onReady)
} else {
rootfsKey, workspaceKey, sizeBytes, err = s.manager.CreateCheckpoint(ctx, req.SandboxId, checkpointID, s.checkpointStore, onReady)
}
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 1514e3a6..5e6a5bd4 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -2603,8 +2603,11 @@ type CreateCheckpointRequest struct {
// — so the image's memory floor is finalize_memory_mb, decoupled from the
// (larger) build-phase RAM. Used by the image builder. 0 = snapshot in place.
FinalizeMemoryMb int32 `protobuf:"varint,4,opt,name=finalize_memory_mb,json=finalizeMemoryMb,proto3" json:"finalize_memory_mb,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // full (default) captures disk + memory/device state. disk_only captures
+ // only root/workspace disks and restores with a cold boot.
+ Kind string `protobuf:"bytes,5,opt,name=kind,proto3" json:"kind,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *CreateCheckpointRequest) Reset() {
@@ -2665,6 +2668,13 @@ func (x *CreateCheckpointRequest) GetFinalizeMemoryMb() int32 {
return 0
}
+func (x *CreateCheckpointRequest) GetKind() string {
+ if x != nil {
+ return x.Kind
+ }
+ return ""
+}
+
type CreateCheckpointResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
RootfsS3Key string `protobuf:"bytes,1,opt,name=rootfs_s3_key,json=rootfsS3Key,proto3" json:"rootfs_s3_key,omitempty"`
@@ -3962,13 +3972,14 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\tnet_input\x18\x04 \x01(\x04R\bnetInput\x12\x1d\n" +
"\n" +
"net_output\x18\x05 \x01(\x04R\tnetOutput\x12\x12\n" +
- "\x04pids\x18\x06 \x01(\x05R\x04pids\"\xb2\x01\n" +
+ "\x04pids\x18\x06 \x01(\x05R\x04pids\"\xc6\x01\n" +
"\x17CreateCheckpointRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" +
"\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\x12%\n" +
"\x0eprepare_golden\x18\x03 \x01(\bR\rprepareGolden\x12,\n" +
- "\x12finalize_memory_mb\x18\x04 \x01(\x05R\x10finalizeMemoryMb\"\x87\x01\n" +
+ "\x12finalize_memory_mb\x18\x04 \x01(\x05R\x10finalizeMemoryMb\x12\x12\n" +
+ "\x04kind\x18\x05 \x01(\tR\x04kind\"\x87\x01\n" +
"\x18CreateCheckpointResponse\x12\"\n" +
"\rrootfs_s3_key\x18\x01 \x01(\tR\vrootfsS3Key\x12(\n" +
"\x10workspace_s3_key\x18\x02 \x01(\tR\x0eworkspaceS3Key\x12\x1d\n" +
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 18bc58b3..4dd403de 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -343,6 +343,9 @@ message CreateCheckpointRequest {
// — so the image's memory floor is finalize_memory_mb, decoupled from the
// (larger) build-phase RAM. Used by the image builder. 0 = snapshot in place.
int32 finalize_memory_mb = 4;
+ // full (default) captures disk + memory/device state. disk_only captures
+ // only root/workspace disks and restores with a cold boot.
+ string kind = 5;
}
message CreateCheckpointResponse {
diff --git a/proto/worker/worker_kind_test.go b/proto/worker/worker_kind_test.go
new file mode 100644
index 00000000..c5bad87e
--- /dev/null
+++ b/proto/worker/worker_kind_test.go
@@ -0,0 +1,26 @@
+package worker
+
+import (
+ "testing"
+
+ "google.golang.org/protobuf/proto"
+)
+
+func TestCreateCheckpointRequestKindRoundTrip(t *testing.T) {
+ msg := &CreateCheckpointRequest{
+ SandboxId: "sb-test",
+ CheckpointId: "cp-test",
+ Kind: "disk_only",
+ }
+ data, err := proto.Marshal(msg)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var out CreateCheckpointRequest
+ if err := proto.Unmarshal(data, &out); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if out.Kind != "disk_only" {
+ t.Fatalf("kind did not round trip: got %q", out.Kind)
+ }
+}
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 1f385229..915c22e1 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -605,12 +605,19 @@ class Sandbox:
async def create_checkpoint(
self,
name: str,
+ kind: str | None = None,
+ promote_to_full: bool = False,
retention_policy: dict | None = None,
) -> dict:
"""Create a named checkpoint of the running sandbox.
Args:
name: A unique name for this checkpoint.
+ kind: Optional checkpoint kind. Use "full" for disk, memory, and
+ device state, or "disk_only" for a disk-only checkpoint that
+ restores with a cold boot.
+ promote_to_full: For disk-only checkpoints, asynchronously create
+ a derived full checkpoint so future forks can use warm restore.
retention_policy: Optional policy such as
{"mode": "delete_oldest", "maxCount": 10}. When set, the
server may delete older eligible checkpoints before creating
@@ -620,6 +627,10 @@ class Sandbox:
Checkpoint info dict with id, sandboxId, name, status, etc.
"""
body = {"name": name}
+ if kind is not None:
+ body["kind"] = kind
+ if promote_to_full:
+ body["promoteToFull"] = True
if retention_policy is not None:
body["retentionPolicy"] = retention_policy
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 08f20edd..daebc144 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -106,6 +106,8 @@ export type CheckpointRetentionPolicy =
| { mode: "delete_oldest"; maxCount?: number };
export interface CreateCheckpointOptions {
+ kind?: "full" | "disk_only";
+ promoteToFull?: boolean;
retentionPolicy?: CheckpointRetentionPolicy;
}
@@ -703,6 +705,12 @@ export class Sandbox {
async createCheckpoint(name: string, opts: CreateCheckpointOptions = {}): Promise<CheckpointInfo> {
const body: Record<string, unknown> = { name };
+ if (opts.kind) {
+ body.kind = opts.kind;
+ }
+ if (opts.promoteToFull) {
+ body.promoteToFull = true;
+ }
if (opts.retentionPolicy) {
body.retentionPolicy = opts.retentionPolicy;
}
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index cda4a0a6..5e39be6b 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -219,6 +219,9 @@ export interface CheckpointItem {
orgId: string
name: string
status: string
+ kind?: 'full' | 'disk_only'
+ promotionStatus?: 'pending' | 'processing' | 'ready' | 'failed'
+ promotedCheckpointId?: string
sizeBytes: number
activeForks: number
totalForks: number
diff --git a/web/src/pages/Checkpoints.tsx b/web/src/pages/Checkpoints.tsx
index f2992a34..2c48f2df 100644
--- a/web/src/pages/Checkpoints.tsx
+++ b/web/src/pages/Checkpoints.tsx
@@ -2,6 +2,26 @@ import { Fragment, useMemo, useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getCheckpoints, deleteCheckpointDashboard, type CheckpointItem } from '../api/client'
+function checkpointTypeLabel(cp: CheckpointItem) {
+ return cp.kind === 'disk_only' ? 'Disk-only' : 'Full'
+}
+
+function checkpointTypeDetail(cp: CheckpointItem) {
+ if (cp.kind !== 'disk_only') {
+ return 'Disk, memory, CPU'
+ }
+ if (cp.promotionStatus === 'ready') {
+ return 'Promoted for fast fork'
+ }
+ if (cp.promotionStatus === 'processing' || cp.promotionStatus === 'pending') {
+ return 'Promoting'
+ }
+ if (cp.promotionStatus === 'failed') {
+ return 'Promotion failed'
+ }
+ return 'Disk only'
+}
+
export default function Checkpoints() {
const queryClient = useQueryClient()
const [page, setPage] = useState(1)
@@ -78,6 +98,7 @@ export default function Checkpoints() {
<tr>
<th>Name</th>
<th>Sandbox</th>
+ <th>Type</th>
<th>Status</th>
<th style={{ textAlign: 'right' }}>Active Forks</th>
<th style={{ textAlign: 'right' }}>Total Forks</th>
@@ -93,6 +114,35 @@ export default function Checkpoints() {
<td>
<code style={{ fontSize: 12 }}>{cp.sandboxId}</code>
</td>
+ <td>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
+ <span
+ style={{
+ fontSize: 11,
+ fontWeight: 600,
+ padding: '2px 8px',
+ borderRadius: 10,
+ width: 'fit-content',
+ background: cp.kind === 'disk_only'
+ ? 'rgba(59, 130, 246, 0.08)'
+ : 'rgba(148, 163, 184, 0.08)',
+ color: cp.kind === 'disk_only'
+ ? '#60a5fa'
+ : 'var(--text-secondary)',
+ border: `1px solid ${
+ cp.kind === 'disk_only'
+ ? 'rgba(59, 130, 246, 0.18)'
+ : 'rgba(148, 163, 184, 0.16)'
+ }`,
+ }}
+ >
+ {checkpointTypeLabel(cp)}
+ </span>
+ <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
+ {checkpointTypeDetail(cp)}
+ </span>
+ </div>
+ </td>
<td>
<span
style={{
@@ -150,7 +200,7 @@ export default function Checkpoints() {
</tr>
{cp.status === 'failed' && cp.errorMsg && (
<tr key={`${cp.id}-error`}>
- <td colSpan={7} style={{ paddingTop: 0 }}>
+ <td colSpan={8} style={{ paddingTop: 0 }}>
<div
style={{
border: '1px solid rgba(251, 113, 133, 0.16)',
@@ -177,7 +227,7 @@ export default function Checkpoints() {
))}
{visibleCheckpoints.length === 0 && (
<tr>
- <td colSpan={7} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>
+ <td colSpan={8} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>
{checkpoints.length === 0 ? 'No checkpoints yet' : 'No checkpoints to show'}
</td>
</tr>