The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(checkpoints): add full checkpoint kind and metadata API (#3051)
lfld287ffd598b75b9d
diff --git a/apps/api/README.md b/apps/api/README.mdindex 3436130b2..301ae0190 100644--- a/apps/api/README.md+++ b/apps/api/README.md@@ -268,18 +268,25 @@ Coverage runs bypass the cache.## Checkpoint capture-`POST /api/v1/checkpoints` accepts `source_box_id` and an optional `name`.+`POST /api/v1/checkpoints` accepts `source_box_id`, an optional `name` and an optional+`kind` of `disk` or `full`. Omission selects `disk`. Explicit `null` returns HTTP 400.+`full` returns HTTP 400 with `code: "unsupported"`.+`GET /api/v1/checkpoints` and `GET /api/v1/checkpoints/{id-or-name}` read the-organization's records. The routes also accept the existing organization path-prefix. Capture requires Box write permission; reads require organization-membership, following the existing Box read policy. List/detail responses omit stored environment values and-internal object locations.+organization's records. Create, list and detail responses include `kind: "disk"`.+List and detail responses omit stored environment values and internal object locations.++The routes also accept the organization path prefix. Capture requires Box write+permission, and reads require organization membership under the Box read policy.+`GET /v1/config` (hosted at `/api/v1/config`) reports+`capabilities.memory_checkpoints_enabled: false`.Checkpoint operations stay outside the MCP OAuth allowlist, like export/import.The `checkpoints` collection name is reserved and cannot be claimed as an application subdomain.A source must be stopped and idle on a ready v2 runner, without volumes or secrets.-Stop the Box and wait for `stopped` before capture; other states return `409`.+Stop the Box and wait for `stopped` before capture. A source state mismatch+returns HTTP 409 with `code: "invalid_state"`.Checkpoint capture never stops the source automatically or uses hot export.Creating a checkpoint takes the source's `BOX` job slotuntil native export completes. The completion transaction clears its checkpointdiff --git a/apps/api/src/box/services/checkpoint.integration.spec.ts b/apps/api/src/box/services/checkpoint.integration.spec.tsindex 958546ea8..33c00f53c 100644--- a/apps/api/src/box/services/checkpoint.integration.spec.ts+++ b/apps/api/src/box/services/checkpoint.integration.spec.ts@@ -426,7 +426,10 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>it('requires a stopped source before accepting checkpoint capture', async () => {const box = await source()await boxes.update(box.id, { state: BoxState.STARTED, desiredState: BoxDesiredState.STARTED })- await expect(service.create(organizationId, box.id, 'running-source')).rejects.toMatchObject({ status: 409 })+ await expect(service.create(organizationId, box.id, 'running-source')).rejects.toMatchObject({+ status: 409,+ response: expect.objectContaining({ code: 'invalid_state' }),+ })expect(await checkpoints.count()).toBe(0)expect(await jobs.count()).toBe(0)expect(await states.count()).toBe(0)@@ -1298,7 +1301,10 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>await dataSource.getRepository(BoxMigration).insert({ boxId: box.id, state: BoxMigrationState.PENDING_EXPORT, arcPath: '', updatedAt: box.updatedAt })- await expect(service.create(organizationId, box.id)).rejects.toMatchObject({ status: 409 })+ await expect(service.create(organizationId, box.id)).rejects.toMatchObject({+ status: 409,+ response: expect.objectContaining({ code: 'invalid_state' }),+ })expect(await jobs.count()).toBe(0)expect(await checkpoints.count()).toBe(0)expect(await boxes.findOneByOrFail({ id: box.id }).then(withCheckpointState)).toMatchObject({@@ -1315,7 +1321,10 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>await jobs.insert(new Job({ type: JobType.START_BOX, runnerId: runner.id, resourceType: ResourceType.BOX, resourceId: box.id }),)- await expect(service.create(organizationId, box.id)).rejects.toMatchObject({ status: 409 })+ await expect(service.create(organizationId, box.id)).rejects.toMatchObject({+ status: 409,+ response: expect.objectContaining({ code: 'invalid_state' }),+ })expect(await checkpoints.count()).toBe(0)expect(await jobs.count()).toBe(1)})diff --git a/apps/api/src/box/services/checkpoint.service.ts b/apps/api/src/box/services/checkpoint.service.tsindex 8a6f12aab..bb2d0b41b 100644--- a/apps/api/src/box/services/checkpoint.service.ts+++ b/apps/api/src/box/services/checkpoint.service.ts@@ -82,14 +82,18 @@ export class CheckpointService {String(box.state) !== String(box.desiredState) ||box.state !== BoxState.STOPPED) {- throw new ConflictException(- 'Checkpoint source must be idle and stopped; stop the Box before creating a checkpoint',- )+ throw new ConflictException({+ message: 'Checkpoint source must be idle and stopped; stop the Box before creating a checkpoint',+ code: 'invalid_state',+ })}if (box.volumes?.length || box.secrets?.length)throw new BadRequestException('Checkpoints with volumes or secrets are not supported')if (await manager.exists(BoxMigration, { where: { boxId: box.id, state: Not(BoxMigrationState.COMPLETED) } })) {- throw new ConflictException('Checkpoint source is migrating')+ throw new ConflictException({+ message: 'Checkpoint source is migrating',+ code: 'invalid_state',+ })}const runner = box.runnerId? await manager.findOneBy(Runner, {@@ -110,7 +114,10 @@ export class CheckpointService {},})) {- throw new ConflictException('Source box already has an unfinished job')+ throw new ConflictException({+ message: 'Source box already has an unfinished job',+ code: 'invalid_state',+ })}if ((await manager.countBy(Checkpoint, { organizationId })) >= settings.maxPerOrganization)throw new ConflictException('Checkpoint limit reached')diff --git a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.tsindex ed0ae47ee..9bbb14565 100644--- a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts@@ -3,6 +3,7 @@import {BadRequestException,+ ConflictException,RequestTimeoutException,ServiceUnavailableException,UnauthorizedException,@@ -187,6 +188,7 @@ describe('Checkpoint REST authentication and request admission', () => {name: 'base',source_box_id: 'source-id',state: 'creating',+ kind: 'disk',created_at: record.createdAt.toISOString(),size_bytes: 0,})@@ -196,6 +198,57 @@ describe('Checkpoint REST authentication and request admission', () => {)})+ it('admits explicit disk capture', async () => {+ const result = await request('/v1/checkpoints', 'checkpoint-write-key', {+ source_box_id: 'source-id',+ kind: 'disk',+ })+ expect(result.status).toBe(201)+ expect(await result.json()).toMatchObject({ id: record.id, kind: 'disk' })+ expect(checkpoints.create).toHaveBeenCalledWith(organizationId, 'source-id', undefined)+ })++ it('preserves the invalid_state code from a checkpoint source state conflict', async () => {+ const message = 'Checkpoint source must be idle and stopped; stop the Box before creating a checkpoint'+ checkpoints.create.mockRejectedValueOnce(new ConflictException({ message, code: 'invalid_state' }))+ const result = await request('/v1/checkpoints', 'checkpoint-write-key', {+ source_box_id: 'source-id',+ kind: 'disk',+ })+ expect(result.status).toBe(409)+ expect(await result.json()).toMatchObject({ code: 'invalid_state', message })+ })++ it('preserves a duplicate checkpoint name conflict without adding a code', async () => {+ const message = 'Checkpoint name already exists'+ checkpoints.create.mockRejectedValueOnce(new ConflictException(message))+ const result = await request('/v1/checkpoints', 'checkpoint-write-key', {+ source_box_id: 'source-id',+ name: 'base',+ })+ expect(result.status).toBe(409)+ const body = await result.json()+ expect(body).toMatchObject({ message })+ expect(body).not.toHaveProperty('code')+ })++ it('rejects full capture before calling the service', async () => {+ const result = await request('/v1/checkpoints', 'checkpoint-write-key', {+ source_box_id: 'source-id',+ kind: 'full',+ })+ expect(result.status).toBe(400)+ expect(await result.json()).toMatchObject({ code: 'unsupported' })+ expect(checkpoints.create).not.toHaveBeenCalled()+ })++ it.each([null, 'bogus', 123])('rejects invalid checkpoint kind %j before calling the service', async (kind) => {+ const result = await request('/v1/checkpoints', 'checkpoint-write-key', { source_box_id: 'source-id', kind })+ expect(result.status).toBe(400)+ expect(await result.json()).not.toHaveProperty('code', 'unsupported')+ expect(checkpoints.create).not.toHaveBeenCalled()+ })+it('allows reads without exposing the stored environment or object URI', async () => {const list = await request('/v1/checkpoints', 'checkpoint-read-key')expect(list.status).toBe(200)diff --git a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.tsindex 0b34fe38d..5f2910f40 100644--- a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts@@ -2,6 +2,7 @@// SPDX-License-Identifier: AGPL-3.0import {+ BadRequestException,Body,Controller,Delete,@@ -17,7 +18,7 @@ import {ValidationPipe,} from '@nestjs/common'import { ApiExcludeController } from '@nestjs/swagger'-import { IsOptional, IsString, Matches, MaxLength, MinLength } from 'class-validator'+import { IsIn, IsOptional, IsString, Matches, MaxLength, MinLength, ValidateIf } from 'class-validator'import { CombinedAuthGuard } from '../auth/combined-auth.guard'import { OrganizationResourceActionGuard } from '../organization/guards/organization-resource-action.guard'import { RequiredOrganizationResourcePermissions } from '../organization/decorators/required-organization-resource-permissions.decorator'@@ -30,6 +31,9 @@ import { CheckpointService } from '../box/services/checkpoint.service'class CreateCheckpointRequest {@IsString() @MinLength(1) @MaxLength(128) source_box_id: string@IsOptional() @IsString() @Matches(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/) name?: string+ @ValidateIf((_obj, value) => value !== undefined)+ @IsIn(['disk', 'full'])+ kind?: 'disk' | 'full'}@Controller(['v1/checkpoints', 'v1/:prefix/checkpoints'])@@ -43,6 +47,9 @@ export class BoxliteCheckpointController {@HttpCode(201)@RequiredOrganizationResourcePermissions([OrganizationResourcePermission.WRITE_BOXES])async create(@AuthContext() auth: OrganizationAuthContext, @Body() request: CreateCheckpointRequest) {+ if (request.kind === 'full') {+ throw new BadRequestException({ message: 'Full checkpoints are not supported', code: 'unsupported' })+ }return response(await this.checkpoints.create(auth.organizationId, request.source_box_id, request.name ?? undefined),)@@ -83,6 +90,7 @@ function response(checkpoint: Checkpoint) {name: checkpoint.name,source_box_id: checkpoint.sourceBoxId,state: checkpoint.state,+ kind: 'disk',created_at: checkpoint.createdAt.toISOString(),size_bytes: checkpoint.archive?.sizeBytes ?? 0,...(checkpoint.errorReason ? { error_reason: checkpoint.errorReason } : {}),diff --git a/apps/api/src/boxlite-rest/boxlite-config.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-config.controller.spec.tsindex 1a7b6acfc..d7d56284c 100644--- a/apps/api/src/boxlite-rest/boxlite-config.controller.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-config.controller.spec.ts@@ -10,6 +10,7 @@ describe('checkpoint capability discovery', () => {])('advertises checkpoint admission only after rollout: %j', ({ archivePrefix, enabled, expected }) => {const controller = new BoxliteConfigController(new ConfigService({ checkpoint: { archivePrefix, enabled } }))expect(controller.getConfig().capabilities.checkpoints_enabled).toBe(expected)+ expect(controller.getConfig().capabilities.memory_checkpoints_enabled).toBe(false)expect(controller.getConfig().capabilities.import_enabled).toBe(false)})})diff --git a/apps/api/src/boxlite-rest/boxlite-config.controller.ts b/apps/api/src/boxlite-rest/boxlite-config.controller.tsindex f2a32d509..e63963ee0 100644--- a/apps/api/src/boxlite-rest/boxlite-config.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-config.controller.ts@@ -21,6 +21,7 @@ export class BoxliteConfigController {capabilities: {checkpoints_enabled:this.config?.get('checkpoint.enabled') === true && !!this.config?.get('checkpoint.archivePrefix'),+ memory_checkpoints_enabled: false,privileged_enabled: true,snapshots_enabled: false,clone_enabled: false,diff --git a/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts b/apps/api/src/boxlite-rest/boxlite-openapi.spec.tsindex ca9bb968d..1cc816fac 100644--- a/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts@@ -10,6 +10,8 @@ import { resolve } from 'node:path'import { parse } from 'yaml'import { ImageCatalogService } from '../image/services/image-catalog.service'import { RegistriesService } from '../registry/services/registries.service'+import { BoxliteCheckpointController } from './boxlite-checkpoint.controller'+import { BoxliteConfigController } from './boxlite-config.controller'import { BoxliteDomainController } from './boxlite-domain.controller'import { BoxliteImageController } from './boxlite-image.controller'import { BoxliteRegistryController } from './boxlite-registry.controller'@@ -27,6 +29,56 @@ function validator(name: string) {return validate}+describe('Box API checkpoint schemas', () => {+ it('accepts omission or known kinds in a closed capture request', () => {+ const validate = validator('CreateCheckpointRequest')+ const request = { source_box_id: 'source' }+ expect(validate(request)).toBe(true)+ for (const kind of ['disk', 'full']) expect(validate({ ...request, kind })).toBe(true)+ for (const kind of [null, 'bogus', 123]) expect(validate({ ...request, kind })).toBe(false)+ expect(validate({ ...request, kind: 'full', extra: true })).toBe(false)+ })++ it('accepts omitted metadata and a known zero memory size, and rejects nulls and negative sizes', () => {+ const validate = validator('Checkpoint')+ const checkpoint = {+ id: 'checkpoint',+ name: 'backup',+ source_box_id: 'source',+ created_at: '2026-10-01T00:00:00Z',+ size_bytes: 512,+ state: 'ready',+ }+ expect(validate(checkpoint)).toBe(true)+ expect(validate({ ...checkpoint, kind: 'full', memory_size_bytes: 0 })).toBe(true)+ expect(validate({ ...checkpoint, kind: null })).toBe(false)+ expect(validate({ ...checkpoint, kind: 'full', memory_size_bytes: null })).toBe(false)+ expect(validate({ ...checkpoint, kind: 'full', memory_size_bytes: -1 })).toBe(false)+ })++ it('validates actual checkpoint and config controller responses', async () => {+ const record = {+ id: 'checkpoint',+ name: 'backup',+ sourceBoxId: 'source',+ createdAt: new Date('2026-10-01T00:00:00Z'),+ state: 'creating',+ }+ const service = {+ create: jest.fn().mockResolvedValue(record),+ get: jest.fn().mockResolvedValue(record),+ list: jest.fn().mockResolvedValue({ checkpoints: [record] }),+ }+ const controller = new BoxliteCheckpointController(service as never)+ const auth = { organizationId: 'org-1' } as never+ expect(validator('Checkpoint')(await controller.create(auth, { source_box_id: 'source' }))).toBe(true)+ expect(validator('Checkpoint')(await controller.get(auth, 'checkpoint'))).toBe(true)+ const page = JSON.parse(JSON.stringify(await controller.list(auth)))+ expect(validator('CheckpointList')(page)).toBe(true)+ expect(validator('ServerConfig')(new BoxliteConfigController().getConfig())).toBe(true)+ })+})+describe('Box API JSON Schema nullability', () => {const nullableFields = {Principal: ['path_prefix', 'expires_at'],diff --git a/docs/contributing/README.md b/docs/contributing/README.mdindex 62505f12c..e3810602e 100644--- a/docs/contributing/README.md+++ b/docs/contributing/README.md@@ -36,6 +36,7 @@ How to build, test, and change the code.Dated root-cause analyses and design studies, newest first.+- 2026-11-23 · [Memory and VMState checkpoint API](investigations/2026-11-23-checkpoint-memory-vmstate-api.md): Defines full checkpoint options, capability checks, and the implementation order across the runtime, REST API, CLI, and SDKs.- 2026-11-23 · [Create Box subscription value](investigations/2026-11-23-create-box-subscription-value.md): catalog-derived subscription savings beside the PAYG estimate, billing-state rules, and draft-preserving plan access.- 2026-11-19 · [Trial discovery in Welcome](investigations/2026-11-19-trial-discovery-preview.md): frontend onboarding study, mock boundaries, direct completion and full walkthrough screenshots.diff --git a/docs/contributing/architecture/platform/api.md b/docs/contributing/architecture/platform/api.mdindex 7d9fa11ab..d6fc57cbe 100644--- a/docs/contributing/architecture/platform/api.md+++ b/docs/contributing/architecture/platform/api.md@@ -86,8 +86,15 @@ service does not currently register, including clone, binary archive import/expoand runtime-wide metrics. `GET /v1/config` reports those archive capabilities asdisabled. Checkpoint capture and box creation from a checkpoint are a separate capability:`checkpoints_enabled` requires both `CHECKPOINTS_ENABLED=true` and a configured-checkpoint archive prefix. Private tunnels are enabled; clients check that-capability before every private prepare.+checkpoint archive prefix.++Hosted `GET /v1/config` reports `memory_checkpoints_enabled: false`. Hosted+`POST /v1/checkpoints` recognizes `kind: "disk"` and `kind: "full"`. Disk+responses include `kind: "disk"`. A full request returns HTTP 400 with code+`unsupported` before checkpoint admission.++Private tunnels are enabled. Clients check that capability before every private+prepare.## Services at a glance@@ -731,7 +738,7 @@ organization membership.| Method | Path | What it does || ------ | ---- | ------------ |-| `POST` | `/v1[/{prefix}]/checkpoints` | Captures an independent disk archive from `source_box_id`, with an optional `name`; returns `201`. |+| `POST` | `/v1[/{prefix}]/checkpoints` | Takes `source_box_id`, optional `name`, and optional `kind` (defaults to `disk`). Returns `201` for accepted disk capture, `409` with `code: "invalid_state"` for a source state mismatch, or `400` with `code: "unsupported"` for `full`. || `GET` | `/v1[/{prefix}]/checkpoints` | Lists organization checkpoints; accepts `pageToken` or `page_token`, and returns `next_page_token`. || `GET` | `/v1[/{prefix}]/checkpoints/{key}` | Gets checkpoint metadata by ID or name, including state and optional `error_reason`. || `DELETE` | `/v1[/{prefix}]/checkpoints/{key}` | Deletes an unused checkpoint; `force=true` tolerates an already absent checkpoint, but active capture/use returns `409`; returns `204`. |@@ -743,9 +750,11 @@ creates a Box that inherits the saved settings. `checkpoint_id` excludes `image``/boxes/import` route on the hosted service and no way to replace an existing Boxfrom a checkpoint.-Capture requires a stopped, idle source; callers stop the Box and wait for-`stopped` first. Other states return `409`; capture never automatically stops a Box.-The runner checks again under its source-operation lock before native export.+Disk capture requires a stopped, idle source. Callers stop the Box and wait for+`stopped` before requesting capture. A source state mismatch returns HTTP 409+with `code: "invalid_state"`. The runner checks again under its source-operation+lock before native export. A `kind: "full"` request returns HTTP 400 with+`code: "unsupported"` before admission.Capture, creation from a checkpoint, and deletion require `write:boxes`; reads requireorganization membership. Turning off checkpoint admission leaves reads, deletion, anddiff --git a/docs/contributing/investigations/2026-11-23-checkpoint-memory-vmstate-api.md b/docs/contributing/investigations/2026-11-23-checkpoint-memory-vmstate-api.mdnew file mode 100644index 000000000..af47f9861--- /dev/null+++ b/docs/contributing/investigations/2026-11-23-checkpoint-memory-vmstate-api.md@@ -0,0 +1,194 @@+# Memory and VMState checkpoint API++**Status:** Implemented++## Summary++The BoxLite API exposes a `full` checkpoint option for disk, guest memory and VMState. Disk+requests retain their existing behavior, and servers without full capture support reject `full`.++## Scope and non-goals++This phase defines the API contract and passes it through from Rust Runtime Core to the REST+client, OpenAPI, the hosted API (`apps/api`), `boxlite serve` capability discovery, the CLI, and+the C, Go, Python and Node SDKs. The hosted API recognizes full capture requests and rejects+them before admission.++Local VMM, KVM, device and memory capture and restore are outside this phase. `FIFREEZE`,+`with_quiesce_async`, the SQLite schema and `boxlite-vmm` are outside its scope.++## Wire and API contract++### Capture request and source state++SDK entry points expose `CheckpointOptions` with an optional `kind`. The wire schema uses the+`CheckpointKind` values `disk` and `full`, requires `source_box_id` and rejects extra properties.+Default calls, empty options and explicit `disk` all use the legacy body+`{"source_box_id":"...","name":"..."}` with an optional `name`. `RestRuntime` omits `kind` for+both `None` and `Some(CheckpointKind::Disk)` and emits `"kind":"full"` only for+`Some(CheckpointKind::Full)`. This preserves compatibility with older servers that reject+unknown request fields. [CreateCheckpointRequest](../../../openapi/box.openapi.yaml#L3266-L3281),+[CheckpointKind schema](../../../openapi/box.openapi.yaml#L3212-L3217)++The `createCheckpoint` operation requires a stopped and idle source Box for `disk` and a+running source Box for `full`. A state mismatch returns HTTP 409 with `code: "invalid_state"`+on a backend that supports the requested kind. Capture leaves lifecycle transitions to the caller.+[Create checkpoint operation](../../../openapi/box.openapi.yaml#L1921-L1934)++### Capability preflight and response verification++`ServerConfig.capabilities` defines optional booleans for `checkpoints_enabled` and+`memory_checkpoints_enabled`. The Rust `ServerCapabilities` represents both as `Option<bool>`.+[OpenAPI capabilities](../../../openapi/box.openapi.yaml#L2846-L2853),+[REST capability types](../../../src/boxlite/src/rest/types.rs#L90-L104)++Only `Some(CheckpointKind::Full)` calls `require_memory_checkpoints_enabled()` before+`POST /checkpoints`. The helper fetches `GET /v1/config` without caching, using the existing+live capability checks. A missing capability object, missing field or `Some(false)` returns+`BoxliteError::Unsupported` with zero POSTs. `Some(true)` permits the POST. Default and+explicit disk requests incur zero extra round trips.+[Config fetch](../../../src/boxlite/src/rest/client.rs#L605-L607),+[Full capture preflight](../../../src/boxlite/src/rest/client.rs#L677-L685),+[Capability validation](../../../src/boxlite/src/rest/client.rs#L818-L830)++The HTTP 201 response to an accepted full request must immediately echo `kind: "full"`, even+while `state` is `creating`. `memory_size_bytes` may be absent at that point. If the decoded+kind differs from `Full`, including an omitted kind or an unknown value, the client returns+`BoxliteError::Unsupported` with the returned checkpoint's `id` in the error message. The client+leaves that checkpoint available for inspection and issues no automatic delete or retry.+[REST response check](../../../src/boxlite/src/rest/runtime.rs#L71-L89)++### Checkpoint metadata and restore++The `Checkpoint` response schema defines two optional properties outside the nullable field+allowlist. The schema accepts omission and rejects explicit `null` for both properties.+[Checkpoint schema](../../../openapi/box.openapi.yaml#L3219-L3249),+[Schema nullability tests](../../../apps/api/src/boxlite-rest/boxlite-openapi.spec.ts#L42-L57)++| Field | Wire schema | Meaning |+|---|---|---|+| `kind` | `type: string`, `enum: [disk, full]` | Omission defaults to `disk`. Rust response decoding uses `#[serde(other)]` to map future strings to `Unknown` so `list()` and `get()` keep working. Creation request validation rejects `Unknown` in both the [Rust handle](../../../src/boxlite/src/runtime/checkpoints.rs#L149-L154) and the [REST backend](../../../src/boxlite/src/rest/runtime.rs#L50-L61). |+| `memory_size_bytes` | `type: integer`, `format: int64`, `minimum: 0` | Archived memory payload size in bytes. Omit it for disk checkpoints, during `creating`, or when unavailable. Preserve a known `0`. |++`target_arch` and `format_version` depend on a stable VMM format and are outside this contract.++The `createBox` contract uses `checkpoint_id` and the checkpoint's `kind` to select disk+restore or disk, memory and VMState restore on a server that supports the kind. A ready+checkpoint supplies the saved execution settings, and only `name` may accompany+`checkpoint_id`. Local `RuntimeImpl` returns `BoxliteError::Unsupported` for checkpoint-based+creation. The local checkpoint handle uses the same error for checkpoint management.+[Create Box operation](../../../openapi/box.openapi.yaml#L313-L319),+[Local restore guard](../../../src/boxlite/src/runtime/rt_impl.rs#L482-L489),+[Local checkpoint handle](../../../src/boxlite/src/runtime/checkpoints.rs#L172-L179)++## Layer-by-layer implementation++### Rust Runtime Core and REST client++- Rust re-exports `CheckpointKind` and `CheckpointOptions`, which has+ `kind: Option<CheckpointKind>`. `CheckpointInfo` has `kind: CheckpointKind` and+ `memory_size_bytes: Option<u64>`. A missing kind defaults to `Disk`. Serializing Core metadata+ omits `Disk` and absent memory size, preserving the legacy JSON shape for direct consumers.+ [Checkpoint types](../../../src/boxlite/src/runtime/checkpoints.rs),+ [Runtime exports](../../../src/boxlite/src/runtime/mod.rs),+ [Crate exports](../../../src/boxlite/src/lib.rs)+- `CheckpointBackend::create` takes `options: CheckpointOptions`.+ `CheckpointHandle::create(source, name)` delegates to+ `create_with_options(source, name, options)` with default options. The handle validates+ `source`, `name` and `kind` before looking up the backend.+ [Checkpoint backend and handle](../../../src/boxlite/src/runtime/checkpoints.rs)+- The REST backend sends the legacy body for disk. For full capture, it checks the live+ capability, sends `kind: "full"` and verifies that the creation response confirms `full`.+ [REST runtime boundary](../../../src/boxlite/src/rest/runtime.rs)++### OpenAPI and servers++- The hosted `CreateCheckpointRequest` DTO pairs `@ValidateIf((_obj, value) => value !== undefined)`+ with `@IsIn(['disk', 'full'])`. It accepts omission and rejects explicit `null` and other invalid+ values with HTTP 400. [Hosted request DTO](../../../apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts#L31-L37)+- The hosted controller rejects a valid `full` request before `CheckpointService.create` with+ HTTP 400. The flat JSON body includes `statusCode`, `error`, `message` and `code: "unsupported"`.+ A disk source state mismatch returns HTTP 409 with `code: "invalid_state"`.+ [Hosted capture handler](../../../apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts#L46-L56),+ [Hosted error body](../../../apps/api/src/filters/all-exceptions.filter.ts#L124-L133),+ [Source state guard](../../../apps/api/src/box/services/checkpoint.service.ts#L79-L89)+- Hosted checkpoint responses include `kind: "disk"`. Hosted `GET /v1/config` advertises+ `capabilities.memory_checkpoints_enabled: false`.+ [Hosted response mapping](../../../apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts#L87-L98),+ [Hosted config controller](../../../apps/api/src/boxlite-rest/boxlite-config.controller.ts#L18-L24)+- `boxlite serve` advertises `memory_checkpoints_enabled: false` in `GET /v1/config`.+ [Serve capability types](../../../src/cli/src/commands/serve/types.rs),+ [Serve config handler](../../../src/cli/src/commands/serve/handlers/config.rs)++### CLI and SDKs++| Layer | Entry points and result metadata |+|---|---|+| CLI | `checkpoint create --kind <disk\|full>` passes the selection through `CheckpointOptions`. Both `list` and `get` show `KIND` in tables. JSON and YAML include `kind`, including `disk`, and include `memory_size_bytes` when present. [Checkpoint commands](../../../src/cli/src/commands/checkpoint.rs) |+| C | `boxlite_checkpoint_create` selects disk. `boxlite_checkpoint_create_with_options` accepts an optional `const char *kind`, which it copies and validates synchronously before `submit()`. `CCheckpointInfo` ends with `uint64_t memory_size_bytes`, `int has_memory_size_bytes` and `char *kind`. [C bindings](../../../sdks/c/src/checkpoints.rs), [C header](../../../sdks/c/include/boxlite.h) |+| Go | `Create(ctx, source, name)` selects disk. `CreateWithOptions(ctx, source, name, opts)` accepts `CheckpointOptions`. Go rejects embedded NULs and invalid kinds before crossing cgo. `CheckpointInfo.Kind` is a `CheckpointKind` and `MemorySizeBytes` is a `*uint64`. Both are copied before freeing the C metadata. [Go API](../../../sdks/go/checkpoints.go) |+| Python | `CheckpointOptions(kind=None)` is exported by the extension and package. The async and sync handles accept `create(source, name=None, options=None)`. Invalid `kind` raises `InvalidArgumentError`. Results expose `kind` and optional `memory_size_bytes`. [Python bindings](../../../sdks/python/src/checkpoints.rs), [Extension registration](../../../sdks/python/src/lib.rs), [Package exports](../../../sdks/python/boxlite/__init__.py), [Sync checkpoint handle](../../../sdks/python/boxlite/sync_api/_checkpoints.py) |+| Node | `create(source, name?, options?)` accepts `CheckpointOptions { kind?: "disk" \| "full" \| null }`. Omission or `null` selects disk. The native boundary parses `Option<String>` with `TryFrom` and uses the `invalid argument:` prefix consumed by `errorCode()`. `CheckpointInfo` exposes `kind` and `memorySizeBytes?: number`. [Node bindings](../../../sdks/node/src/checkpoints.rs), [Native contracts](../../../sdks/node/lib/native-contracts.ts#L175-L197), [Public exports](../../../sdks/node/lib/index.ts) |++## Design rationale and alternatives considered++- Declaring `kind` in the hosted DTO allows valid values through `forbidNonWhitelisted`.+ HTTP 400 with `code: "unsupported"` follows the shared `BoxliteError::Unsupported` convention+ and preserves the error class in the REST client.+ [Shared HTTP error mapping](../../../src/shared/src/errors.rs#L166-L175),+ [REST error decoding](../../../src/boxlite/src/rest/error.rs#L73-L82)+- Fresh capability discovery limits stale positives after a rollback or replica change.+ `Option<bool>` preserves the distinction between an older server with no field and a server+ that explicitly reports false. Both fail before POST, avoiding misleading invalid-argument+ responses and orphan `creating` records behind permissive proxies. A successful preflight+ cannot guarantee that the same backend handles the POST. The 201 kind check detects a silent+ downgrade and preserves the returned ID for reconciliation.+- Sending `kind: "disk"` would fail against legacy closed request schemas. Omitting it makes+ the explicit disk choice equivalent to the existing default at the wire boundary.+- Omission keeps the response additive and fits the OpenAPI nullable allowlist. It also+ distinguishes an unavailable memory size from an archived payload with a known size of zero.+ The CLI needs one selector for the same mode. Two mutually exclusive flags add a conflict+ rule without expressing an additional mode.++## Original inside-out pull request roadmap++All layers were delivered together on this branch. The original roadmap grouped the work by+dependency and estimated source lines for each proposed pull request.++| Proposed pull request | Original dependencies and estimated code lines | Documentation |+|---|---|---|+| PR-1 · Runtime Core | First, ~100–140 LOC for the Rust types and `CheckpointHandle` contract. | [Rust reference](../../reference/rust/README.md) |+| PR-2 · REST, OpenAPI and servers | After PR-1 and the planned compatibility review, ~150–200 LOC for the wire contract, `apps/api` and `boxlite serve`. | [Platform API](../architecture/platform/api.md) |+| PR-3 · CLI | After PR-2, ~80–120 LOC. | [CLI reference](../../../src/cli/README.md) |+| PR-4 · C and Go SDKs | After PR-2, ~190–280 LOC. Go depends on the C FFI and `boxlite.h`. | [C reference](../../reference/c/README.md), [Go SDK](../../../sdks/go/README.md) |+| PR-5 · Python and Node SDKs | After PR-2, ~170–230 LOC combined for two independent SDKs. | [Python reference](../../reference/python/README.md), [Node reference](../../reference/nodejs/README.md) |++The Rust handle is the foundation for the wire contract. The CLI and SDKs use that contract,+and Go consumes the C FFI header. The API changes require no shared mutable runtime state,+lock changes or database schema changes.++## Verification and test matrix++| Layer | Commands | Required coverage |+|---|---|---|+| OpenAPI and hosted API | `make test:unit:openapi`, `make test:apps:api` | Validate legacy and explicit-kind requests, response omission, zero and schema bounds. At the hosted HTTP boundary, verify default and disk reach `CheckpointService.create` and return `kind: 'disk'` on success. Preserve HTTP 409 `invalid_state` for a disk source in the wrong state. Full returns 400 `unsupported` with zero service calls, invalid input returns 400 invalid argument, and discovery advertises false. [Hosted HTTP tests](../../../apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts) |+| Rust Core and REST client | `make test:unit:core` | Verify validation before backend lookup, local `Unsupported`, prior disk payloads with and without `name`, and response defaults. Assert exact requests and order on loopback, including zero config GETs for disk, zero POSTs for absent and false capabilities, a fresh GET per full request, accepted 201 `full` during `creating`, and mismatched kind errors carrying the ID without follow-up requests. Verify unknown kinds through `list()` and `get()`, reject `Unknown` on creation before transport, and preserve the existing `POST /boxes` body. Keep REST loopback tests in [rest/runtime.rs](../../../src/boxlite/src/rest/runtime.rs). The `RUST_UNIT_REST_ARGS` pass uses the `rest::` filter and silently skips them under [runtime/checkpoints/tests.rs](../../../src/boxlite/src/runtime/checkpoints/tests.rs). |+| CLI | `make coverage:cli` | Test the selected create flag, legacy disk payload, table `KIND`, JSON metadata including a known zero, and the local serve config value. [CLI checkpoint tests](../../../src/cli/tests/checkpoint.rs) |+| C and Go | `make dev:c`, `make test:unit:ffi`, `make test:unit:go` | Verify FFI validation before submission, callback and list ownership, absent size versus zero, and Go input guards and option forwarding. `make coverage:go:checkpoint` covers the local archive only. `make test:unit:go` exercises the REST boundary. [Go REST boundary tests](../../../sdks/go/checkpoints_test.go) |+| Python | `make dev:python && make test:unit:python` | Build the native `.so` so checkpoint tests run. Cover async and `SyncCheckpointHandle.create(..., options=...)`, invalid input as `InvalidArgumentError`, and optional size conversion. [Python checkpoint tests](../../../sdks/python/tests/test_checkpoint_handle.py) |+| Node | `make dev:node`, `make test:unit:node`, `make test:integration:node FILTER='^checkpoint '` | Put native conversion and error tests in a `#[cfg(test)]` module in [Node checkpoints.rs](../../../sdks/node/src/checkpoints.rs). Exercise the native REST boundary and public JS metadata in [checkpoints.integration.test.ts](../../../sdks/node/tests/checkpoints.integration.test.ts). Prefix new test names in that file with `checkpoint ` so the targeted integration run selects them. `make test:unit:node` excludes `*.integration.test.ts`. |+| Lint | `make lint` | Run for each implementation pull request. |++## Decisions++1. **C ABI.** The pre-1.0 API appends fields to `CCheckpointInfo` and uses that struct for+ callbacks and list entries. The larger element stride requires precompiled list consumers+ to rebuild against the current header.+2. **Node `memorySizeBytes`.** The public type is `number`, matching `sizeBytes` and supporting+ `JSON.stringify`. The maximum safe integer is `2^53 - 1` bytes, just under 8 PiB.+3. **Go signature.** `Create` keeps its signature and delegates to `CreateWithOptions`. Existing+ direct calls, interfaces and method values retain their types.+4. **CLI flag.** `--kind <disk|full>` matches the wire and SDK terminology.+5. **OpenAPI compatibility.** The branch includes the additive schema changes in the REST+ implementation commit (`56d64028c`). The contract preserves required fields, the disk+ default and the existing disk request body.diff --git a/docs/reference/c/README.md b/docs/reference/c/README.mdindex 9d37145e2..eaca236c6 100644--- a/docs/reference/c/README.md+++ b/docs/reference/c/README.md@@ -41,6 +41,7 @@ The SDK provides two API styles:- [Native API](#native-api)- [Runtime Management](#runtime-management)- [Box Management](#box-management)+ - [Managed checkpoints](#managed-checkpoints)- [Network Tunnels](#network-tunnels)- [Command Execution](#command-execution)- [Discovery & Introspection](#discovery--introspection)@@ -697,6 +698,39 @@ Safe to call with NULL. Use when you need to release a box handle without freein---+### Managed checkpoints++```c+enum BoxliteErrorCode boxlite_checkpoint_create_with_options(+ CBoxliteRuntime *runtime, const char *source, const char *name,+ const char *kind, CCheckpointInfoCb cb, void *user_data,+ CBoxliteError *out_error);+```++Pass a box ID or name as `source` and use `NULL` to let the server choose a+checkpoint name. `boxlite_checkpoint_create` captures a disk checkpoint from a+stopped box. The options entry point does the same with a `NULL` or `"disk"`+kind. Pass `"full"` to capture disk, guest memory, and VM state from a running+box. Full capture requires+`capabilities.memory_checkpoints_enabled: true` from `GET /v1/config`. If the+server omits or disables the capability, the callback receives `Unsupported`+and the SDK skips the capture request. Disk capture skips the preflight.++The function copies its string inputs before returning. An unrecognized kind+or invalid UTF-8 in `kind` returns `InvalidArgument` synchronously, populating+`out_error` if supplied. Callbacks run through `boxlite_runtime_drain` for+accepted requests.++`CCheckpointInfo.kind` contains `"disk"`, `"full"`, or `"unknown"`.+`memory_size_bytes` is the archived guest memory size. The representation+uses `has_memory_size_bytes == 1` for a reported size, including zero, and+`has_memory_size_bytes == 0` with a zero value when absent.+Release standalone metadata, including its strings, with+`boxlite_free_checkpoint_info`. List entries belong to their enclosing list,+which callers release with `boxlite_free_checkpoint_list`. Compile consumers+against the header that matches the library because indexing+`CCheckpointList.items` uses `sizeof(CCheckpointInfo)`.+### Network tunnelsCreation takes a complete system `sockaddr_storage` and a `BoxliteTunnelOptions`diff --git a/docs/reference/nodejs/README.md b/docs/reference/nodejs/README.mdindex 475c99046..f1acf8c55 100644--- a/docs/reference/nodejs/README.md+++ b/docs/reference/nodejs/README.md@@ -58,6 +58,7 @@ new JsBoxlite(options: JsOptions)| `close()` | `() => void` | Close runtime (no-op) || `images` | getter `=> ImageHandle` | The images this runtime can boot from; see [`ImageHandle`](#imagehandle) || `registries` | getter `=> RegistryHandle` | The server's registry logins; throws `unsupported` on a local runtime. See [`RegistryHandle`](#registryhandle) |+| `checkpoints` | getter `=> CheckpointHandle` | Managed checkpoint archives. See [`CheckpointHandle`](#checkpointhandle) |#### Example@@ -82,6 +83,27 @@ boxes.forEach(info => console.log(`${info.id}: ${info.state.status}`));---+### `CheckpointHandle`++Use `runtime.checkpoints` to manage REST checkpoint archives. Operations on an+embedded runtime reject with `unsupported`.++| Method | Signature | Description |+|--------|-----------|-------------|+| `create` | `(source: string, name?: string \| null, options?: CheckpointOptions \| null) => Promise<CheckpointInfo>` | Capture a box by ID or name |+| `list` | `() => Promise<CheckpointInfo[]>` | List checkpoints |+| `get` | `(key: string) => Promise<CheckpointInfo>` | Get a checkpoint by ID or name |+| `remove` | `(key: string, force?: boolean \| null) => Promise<void>` | Remove a checkpoint. With `force: true`, absence is treated as success. |++`CheckpointOptions.kind` accepts `"disk"`, `"full"`, or `null`. Disk capture is+the default. Full capture includes guest memory and VM state and requires the+server to advertise `memory_checkpoints_enabled`.++`CheckpointInfo` includes `id`, `name`, `sourceBoxId`, `createdAt`, `sizeBytes`,+`state`, and optional `errorReason`. Its `kind` is a `CheckpointKind` (`"disk"`,+`"full"`, or `"unknown"` for an unrecognized server value). `memorySizeBytes?: number`+reports the archived guest memory size when available, including zero.+### `ImageHandle`The images a runtime can boot from: the local cache on an embedded runtime,diff --git a/docs/reference/python/README.md b/docs/reference/python/README.mdindex a95d6ba1b..5730bbdb9 100644--- a/docs/reference/python/README.md+++ b/docs/reference/python/README.md@@ -48,6 +48,7 @@ from boxlite import Boxlite, Options, BoxOptions, ImageRegistry| `metrics()` | `async () -> RuntimeMetrics` | Get runtime-wide metrics || `images` | property `-> ImageHandle` | The images this runtime can boot from; see [`boxlite.ImageHandle`](#boxliteimagehandle) || `registries` | property `-> RegistryHandle` | The server's registry logins; raises `UnsupportedError` on a local runtime. See [`boxlite.RegistryHandle`](#boxliteregistryhandle) |+| `checkpoints` | property `-> CheckpointHandle` | Manage checkpoint archives on a REST runtime |#### Example@@ -77,6 +78,22 @@ for info in await runtime.list_info():print(f"{info.id}: {info.state.status}")```+### `boxlite.CheckpointHandle`++`Boxlite.checkpoints` provides async `create(source, name=None, options=None)`,+`list()`, `get(key)`, and `remove(key, force=False)`. `SyncBoxlite.checkpoints`+returns a `boxlite.SyncCheckpointHandle` with the same methods and arguments.+Checkpoint operations on local runtimes raise `UnsupportedError`.++`boxlite.CheckpointOptions(kind=None)` defaults to `"disk"` for a stopped box.+Use `CheckpointOptions(kind="full")` to capture disk, guest memory, and VM state+from a running box. Full capture requires server support. Invalid kinds raise+`InvalidArgumentError`.++`create` and `get` return a `boxlite.CheckpointInfo`. `list` returns a list of them.+`kind` is `"disk"`, `"full"`, or `"unknown"` for unrecognized server values.+`memory_size_bytes` is the archived guest memory size in bytes, or `None` if absent.+### `boxlite.ImageHandle`The images a runtime can boot from: the local cache on an embedded runtime,diff --git a/docs/reference/rust/README.md b/docs/reference/rust/README.mdindex 80c419d24..bf2797c9f 100644--- a/docs/reference/rust/README.md+++ b/docs/reference/rust/README.md@@ -17,6 +17,10 @@ The Rust SDK is the core implementation of BoxLite. It provides async-first APIs- [BoxliteRuntime](#boxliteruntime)- [ImageHandle](#imagehandle)- [RegistryHandle](#registryhandle)+ - [CheckpointHandle](#checkpointhandle)+ - [CheckpointOptions](#checkpointoptions)+ - [CheckpointKind](#checkpointkind)+ - [CheckpointInfo](#checkpointinfo)- [BoxliteOptions](#boxliteoptions)- [Box Handle](#box-handle)- [LiteBox](#litebox)@@ -103,6 +107,7 @@ let runtime = BoxliteRuntime::default_runtime();| `metrics` | `async fn metrics(&self) -> RuntimeMetrics` | Get runtime-wide metrics || `remove` | `async fn remove(&self, id_or_name: &str, force: bool) -> BoxliteResult<()>` | Remove box completely || `images` | `fn images(&self) -> BoxliteResult<ImageHandle>` | The images this runtime can boot from; never fails |+| `checkpoints` | `fn checkpoints(&self) -> CheckpointHandle` | Get the handle for managed checkpoints |Local `remove()` returns `InvalidState` while a disk operation is busy or the disklock file is missing. Retry busy removal after the operation finishes. For a@@ -221,6 +226,62 @@ for login in registries.list().await? {registries.remove(&login.id).await?;```+### CheckpointHandle++Use `runtime.checkpoints()` to manage checkpoint archives. On a local runtime,+operations with valid arguments return `Unsupported`. A REST runtime sends the+same capture request for default and explicit `Disk` options. `Disk` requires a+stopped source box. `Full` requires a running source box and checks+`memory_checkpoints_enabled` with a live `GET /v1/config` before each+`POST /checkpoints`. If the capability is missing or disabled, the client returns+`Unsupported` before the POST. The client verifies that the HTTP 201 response+echoes `kind: "full"`, even while the checkpoint is creating. If the response+does not confirm full capture, `Unsupported` includes the returned checkpoint ID.++| Method | Signature | Description |+|--------|-----------|-------------|+| `create` | `async fn create(&self, source: &str, name: Option<String>) -> BoxliteResult<CheckpointInfo>` | Create a disk checkpoint from a stopped box by ID or name |+| `create_with_options` | `async fn create_with_options(&self, source: &str, name: Option<String>, options: CheckpointOptions) -> BoxliteResult<CheckpointInfo>` | Create a checkpoint with the requested kind |+| `list` | `async fn list(&self) -> BoxliteResult<Vec<CheckpointInfo>>` | List managed checkpoints across all pages |+| `get` | `async fn get(&self, key: &str) -> BoxliteResult<CheckpointInfo>` | Get checkpoint metadata by ID or name |+| `remove` | `async fn remove(&self, key: &str, force: bool) -> BoxliteResult<()>` | Remove a checkpoint by ID or name. `force` suppresses `NotFound` only |++```rust+use boxlite::{CheckpointKind, CheckpointOptions};++let checkpoints = runtime.checkpoints();+let checkpoint = checkpoints+ .create_with_options(+ "source-box",+ Some("backup".into()),+ CheckpointOptions { kind: Some(CheckpointKind::Disk) },+ )+ .await?;+```++### CheckpointOptions++The `kind: Option<CheckpointKind>` field defaults to `None`, which selects disk+capture. REST sends the same request for `None` and `Some(CheckpointKind::Disk)`.++### CheckpointKind++| Variant | Meaning |+|---------|---------|+| `Disk` | Disk data only. The default kind |+| `Full` | Disk data, guest memory, and VM state |+| `Unknown` | An unrecognized kind reported by a server. Creation returns `InvalidArgument` for this variant |++### CheckpointInfo++Checkpoint metadata includes the ID, name, source box ID, creation time, archive+size, state, and optional error reason. In JSON, an omitted `kind` decodes to+`Disk`.++`memory_size_bytes: Option<u64>` reports the archived guest memory size when+available. An omitted size decodes to `None` and a reported zero to `Some(0)`.+Serialization omits `kind` for `Disk` and `memory_size_bytes` for `None`.+### BoxliteOptionsRuntime configuration options.diff --git a/openapi/box.openapi.yaml b/openapi/box.openapi.yamlindex bd61419d8..7244c1862 100644--- a/openapi/box.openapi.yaml+++ b/openapi/box.openapi.yaml@@ -156,7 +156,7 @@ tags:- name: Imagesdescription: Container image management- name: Checkpoints- description: Independent managed disk archives+ description: Independent managed checkpoint archives- name: Volumesdescription: Managed persistent volumes- name: Registries@@ -311,8 +311,10 @@ paths:initialize the VM, or it will start lazily on first `exec`.`checkpoint_id` creates the box from a ready managed checkpoint- instead of an image. The box inherits every saved execution setting,- so only `name` may accompany it; any other field is refused with 400.+ instead of an image. The server uses the checkpoint's `kind` to select+ disk-only restore or full restore of disk, guest memory, and VM state.+ The box inherits every saved execution setting. Only `name` may+ accompany `checkpoint_id`; any other field is refused with 400.It requires `checkpoints_enabled` and a REST service: local SDKoperations return Unsupported. A cloud wait failure after admission,including 408, carries `boxId` in the error body; query that box@@ -1917,14 +1919,19 @@ paths:- $ref: "#/components/parameters/prefix"post:operationId: createCheckpoint- summary: Capture an independent disk checkpoint+ summary: Capture a disk or full checkpointdescription: |- Export the source box directly, without a snapshot or temporary clone.- The source must be stopped and idle; other states return 409.- Stop the box and wait for stopped before capture; capture never stops it automatically.+ `disk` capture requires a stopped and idle source box and exports it+ directly. `full` capture requires a running source box. On a backend+ that supports the requested kind, a source state mismatch returns 409+ with code `invalid_state`. If `full` is unsupported, the server returns+ 400 with code `unsupported`. Capture leaves the source lifecycle state+ to the caller.+Requires Box write permission. Sources with volumes or secrets are- refused. A local capture returns ready after export; cloud capture- returns creating and becomes ready only after upload succeeds.+ refused. A local capture returns ready after export. A cloud capture+ returns creating and becomes ready after upload succeeds. A 201+ response accepting `full` includes `kind: "full"` even while creating.tags: [Checkpoints]requestBody:required: true@@ -2840,6 +2847,10 @@ components:type: booleandescription: Whether managed checkpoint capture, use and deletion are supportedexample: true+ memory_checkpoints_enabled:+ type: boolean+ description: Whether full checkpoint capture and restore support disk, guest memory, and VM state+ example: falseimport_enabled:type: booleandescription: Whether ordinary archive import is supported@@ -3206,6 +3217,13 @@ components:- failed- unknown+ CheckpointKind:+ type: string+ enum: [disk, full]+ description: |+ `disk` includes disk data only. `full` includes disk data, guest memory,+ and VM state. Omission defaults to `disk`.+Checkpoint:type: objectrequired: [id, name, source_box_id, created_at, size_bytes, state]@@ -3227,6 +3245,16 @@ components:state:type: stringenum: [creating, ready, failed, deleting]+ kind:+ $ref: "#/components/schemas/CheckpointKind"+ memory_size_bytes:+ type: integer+ format: int64+ minimum: 0+ description: |+ Archived guest memory payload size in bytes. Omitted for disk+ checkpoints, during `creating`, or when unavailable. A known size+ of zero is reported as `0`.error_reason:type: stringdescription: Optional failure description without environment values or object locations@@ -3257,6 +3285,8 @@ components:minLength: 1maxLength: 128pattern: "^[A-Za-z0-9][A-Za-z0-9._-]*$"+ kind:+ $ref: "#/components/schemas/CheckpointKind"CreateBoxRequest:type: object@@ -3298,7 +3328,9 @@ components:description: |ID or name of a ready managed checkpoint to create the box from(alternative to `image`). Mutually exclusive with `image` and- `rootfs_path`. Only `name` may accompany it.+ `rootfs_path`. The checkpoint's `kind` selects disk-only+ restore or full restore of disk, guest memory, and VM state.+ Only `name` may accompany `checkpoint_id`.cpus:type: numberminimum: 0.125diff --git a/sdks/c/README.md b/sdks/c/README.mdindex 1e438ad63..53b80353e 100644--- a/sdks/c/README.md+++ b/sdks/c/README.md@@ -27,11 +27,15 @@ create call. The checkpoint handle only manages checkpoints. Archive import is aseparate operation for local `.boxlite` files and is unchanged. The CLI form is`boxlite create --checkpoint ID [--name NAME]`.-The source must be stopped before checkpoint creation; stop it and wait for `stopped` first.-Checkpoint creation rejects other states and never stops the source automatically.--`boxlite_checkpoint_create`, `list`, `get` and `remove` require a-REST runtime and use its existing post-and-drain event queue. Local runtimes+`boxlite_checkpoint_create` captures a disk checkpoint from a stopped box.+`boxlite_checkpoint_create_with_options` accepts `NULL` or `"disk"` for the same+capture. Pass `"full"` to capture disk, guest memory, and VM state from a running+box. Full capture checks that the REST server advertises+`capabilities.memory_checkpoints_enabled` through `GET /v1/config` before+submitting the capture. Disk capture skips that request.++Checkpoint creation, listing, lookup, and removal require a REST runtime and+use its post-and-drain event queue. Local runtimesdeliver an unsupported-operation error through the same callback queue.To create a Box from a checkpoint, call `boxlite_options_set_checkpoint` on theoptions and pass them to `boxlite_create_box`. Only the name may accompany it.@@ -40,6 +44,11 @@ or `CCheckpointList`; release them with `boxlite_free_checkpoint_info` or`boxlite_free_checkpoint_list`. List entries belong to the list. Errorpointers are borrowed during callback dispatch.+`CCheckpointInfo.kind` is `"disk"`, `"full"`, or `"unknown"` for an+unrecognized server kind. Read `memory_size_bytes` when+`has_memory_size_bytes` is 1, including when the reported size is zero.+When the flag is 0, the size is absent and the numeric field is zero.+Cloud capture may initially report `creating`; wait for `ready` before use.A Box created from a checkpoint inherits all saved execution settings; any otheroption fails the create with an invalid-argument error.diff --git a/sdks/c/include/boxlite.h b/sdks/c/include/boxlite.hindex b00c1aa77..2a77b0ecd 100644--- a/sdks/c/include/boxlite.h+++ b/sdks/c/include/boxlite.h@@ -295,6 +295,12 @@ typedef struct CCheckpointInfo {char *state;// Null unless the server reports a failure reason.char *error_reason;+ // Archived guest memory size, or zero when absent.+ uint64_t memory_size_bytes;+ // One when memory_size_bytes is present, including a reported zero.+ int has_memory_size_bytes;+ // Lowercase disk, full, or unknown.+ char *kind;} CCheckpointInfo;// Entries belong to this list; release once with boxlite_free_checkpoint_list.@@ -1179,6 +1185,17 @@ enum BoxliteErrorCode boxlite_checkpoint_create(CBoxliteRuntime *runtime,void *user_data,CBoxliteError *out_error);+// Queue capture with an optional kind. Null or "disk" selects a disk checkpoint.+// "full" includes guest memory and VM state.+// Invalid kinds return InvalidArgument synchronously without invoking the callback.+enum BoxliteErrorCode boxlite_checkpoint_create_with_options(CBoxliteRuntime *runtime,+ const char *source,+ const char *name,+ const char *kind,+ CCheckpointInfoCb cb,+ void *user_data,+ CBoxliteError *out_error);+// Queue metadata lookup by ID or name. All inputs except out_error are required.enum BoxliteErrorCode boxlite_checkpoint_get(CBoxliteRuntime *runtime,const char *key,diff --git a/sdks/c/src/checkpoints.rs b/sdks/c/src/checkpoints.rsindex beed1aa63..deade9cbd 100644--- a/sdks/c/src/checkpoints.rs+++ b/sdks/c/src/checkpoints.rs@@ -7,7 +7,9 @@ use std::future::Future;use std::os::raw::{c_char, c_int, c_void};use std::sync::Arc;-use boxlite::{BoxliteError, BoxliteResult, BoxliteRuntime, CheckpointInfo};+use boxlite::{+ BoxliteError, BoxliteResult, BoxliteRuntime, CheckpointInfo, CheckpointKind, CheckpointOptions,+};use tokio::runtime::Runtime as TokioRuntime;use crate::archive::TokioRuntimeDropGuard;@@ -31,6 +33,12 @@ pub struct CCheckpointInfo {pub state: *mut c_char,/// Null unless the server reports a failure reason.pub error_reason: *mut c_char,+ /// Archived guest memory size, or zero when absent.+ pub memory_size_bytes: u64,+ /// One when memory_size_bytes is present, including a reported zero.+ pub has_memory_size_bytes: c_int,+ /// Lowercase disk, full, or unknown.+ pub kind: *mut c_char,}impl CCheckpointInfo {@@ -48,6 +56,7 @@ impl CCheckpointInfo {info.source_box_id,info.created_at.to_rfc3339(),format!("{:?}", info.state).to_lowercase(),+ info.kind.as_str().to_owned(),];// Validate every string before transferring any allocation to raw C ownership.let mut strings = values@@ -67,6 +76,9 @@ impl CCheckpointInfo {size_bytes: info.size_bytes,state: strings.next().unwrap().into_raw(),error_reason: reason.map_or(std::ptr::null_mut(), CString::into_raw),+ memory_size_bytes: info.memory_size_bytes.unwrap_or_default(),+ has_memory_size_bytes: c_int::from(info.memory_size_bytes.is_some()),+ kind: strings.next().unwrap().into_raw(),})}}@@ -80,6 +92,7 @@ impl Drop for CCheckpointInfo {self.created_at,self.state,self.error_reason,+ self.kind,] {if !value.is_null() {unsafe {@@ -163,16 +176,53 @@ pub unsafe extern "C" fn boxlite_checkpoint_create(cb: CCheckpointInfoCb,user_data: *mut c_void,out_error: *mut CBoxliteError,+) -> BoxliteErrorCode {+ unsafe {+ boxlite_checkpoint_create_with_options(+ runtime,+ source,+ name,+ std::ptr::null(),+ cb,+ user_data,+ out_error,+ )+ }+}++/// Queue capture with an optional kind. Null or "disk" selects a disk checkpoint.+/// "full" includes guest memory and VM state.+/// Invalid kinds return InvalidArgument synchronously without invoking the callback.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn boxlite_checkpoint_create_with_options(+ runtime: *mut CBoxliteRuntime,+ source: *const c_char,+ name: *const c_char,+ kind: *const c_char,+ cb: CCheckpointInfoCb,+ user_data: *mut c_void,+ out_error: *mut CBoxliteError,) -> BoxliteErrorCode {let cb = crate::unwrap_cb_or_return!(cb, out_error);let source = input_or_return!(unsafe { required(source) }, out_error);let name = input_or_return!(unsafe { optional(name) }, out_error);+ let kind = input_or_return!(+ unsafe { optional(kind) }.and_then(|kind| match kind.as_deref() {+ None => Ok(None),+ Some("disk") => Ok(Some(CheckpointKind::Disk)),+ Some("full") => Ok(Some(CheckpointKind::Full)),+ Some(_) => Err(BoxliteError::InvalidArgument(+ "checkpoint kind must be disk or full".into(),+ )),+ }),+ out_error+ );let user_data = user_data as usize;unsafe {submit(runtime, out_error, move |runtime, _, _| async move {let result = runtime.checkpoints()- .create(&source, name)+ .create_with_options(&source, name, CheckpointOptions { kind }).await.and_then(CCheckpointInfo::new).map(|info| OwnedFfiPtr::new(Box::new(info)));@@ -309,6 +359,35 @@ mod tests {use std::sync::mpsc;use std::time::{Duration, SystemTime, UNIX_EPOCH};+ #[test]+ fn checkpoint_c_metadata_preserves_kind_and_optional_memory_size() {+ for (kind, memory, expected_kind, expected_flag) in [+ (CheckpointKind::Disk, None, c"disk", 0),+ (CheckpointKind::Full, Some(0), c"full", 1),+ (CheckpointKind::Full, Some(4096), c"full", 1),+ (CheckpointKind::Unknown, None, c"unknown", 0),+ ] {+ let info = CCheckpointInfo::new(CheckpointInfo {+ id: "checkpoint-1".into(),+ name: "backup".into(),+ source_box_id: "source-1".into(),+ created_at: "2026-11-06T00:00:00Z".parse().unwrap(),+ size_bytes: 8192,+ state: Default::default(),+ error_reason: None,+ kind,+ memory_size_bytes: memory,+ })+ .unwrap();+ assert_eq!(info.memory_size_bytes, memory.unwrap_or_default());+ assert_eq!(info.has_memory_size_bytes, expected_flag);+ unsafe {+ assert_eq!(std::ffi::CStr::from_ptr(info.kind), expected_kind);+ boxlite_free_checkpoint_info(Box::into_raw(Box::new(info)));+ }+ }+ }+extern "C" fn list_received(list: *mut CCheckpointList,error: *mut CBoxliteError,@@ -457,6 +536,29 @@ mod tests {crate::boxlite_error_free(&mut error);}}+ for kind in [+ c"".as_ptr(),+ c"unknown".as_ptr(),+ c"bogus".as_ptr(),+ invalid.as_ptr().cast(),+ ] {+ unsafe {+ assert_eq!(+ boxlite_checkpoint_create_with_options(+ &mut runtime,+ c"source-1".as_ptr(),+ ptr::null(),+ kind,+ Some(metadata_received),+ data,+ &mut error,+ ),+ BoxliteErrorCode::InvalidArgument+ );+ assert_eq!(error.code, BoxliteErrorCode::InvalidArgument);+ crate::boxlite_error_free(&mut error);+ }+ }unsafe {assert_eq!(crate::boxlite_runtime_drain(&mut runtime, 0, &mut error), 0);}@@ -500,9 +602,12 @@ mod tests {.into_owned()};format!(- "{}:{}:{reason}",+ "{}:{}:{reason}:{}:{}:{}",std::ffi::CStr::from_ptr((*info).id).to_string_lossy(),std::ffi::CStr::from_ptr((*info).state).to_string_lossy(),+ std::ffi::CStr::from_ptr((*info).kind).to_string_lossy(),+ (*info).has_memory_size_bytes,+ (*info).memory_size_bytes,)}};@@ -564,7 +669,8 @@ mod tests {std::thread::scope(|scope| {let server = scope.spawn(move || {let mut requests = Vec::new();- while requests.len() < 7 {+ let mut memory_checkpoints_enabled = false;+ while requests.len() < 12 {let deadline = Instant::now() + Duration::from_secs(5);let (mut stream, _) = loop {match listener.accept() {@@ -599,11 +705,19 @@ mod tests {let method = request.next().unwrap().to_owned();let path = request.next().unwrap().to_owned();let body = if body.is_empty() { serde_json::Value::Null } else { serde_json::from_slice(&body).unwrap() };- let info = serde_json::json!({"id":"checkpoint-1","name":"base","source_box_id":"source-1","created_at":"2026-11-06T00:00:00Z","size_bytes":4096,"state":"ready"});+ let mut info = serde_json::json!({"id":"checkpoint-1","name":"base","source_box_id":"source-1","created_at":"2026-11-06T00:00:00Z","size_bytes":4096,"state":"ready"});+ if body["kind"] == "full" {+ info["kind"] = "full".into();+ info["memory_size_bytes"] = 0.into();+ }let (status, response) = if path.ends_with("/missing") {(404, serde_json::json!({"message":"Checkpoint not found"}))} else if path == "/v1/boxes" {(200, serde_json::json!({"box_id":"target-1","name":"worker","status":"stopped","created_at":"2026-11-06T00:00:00Z","updated_at":"2026-11-06T00:00:00Z","image":"alpine:latest","cpus":2,"memory_mib":512}))+ } else if path == "/v1/config" {+ let response = serde_json::json!({"capabilities":{"memory_checkpoints_enabled":memory_checkpoints_enabled}});+ memory_checkpoints_enabled = true;+ (200, response)} else if method == "GET" && path == "/v1/checkpoints" {(200, serde_json::json!({"checkpoints":[info]}))} else if method == "GET" {@@ -661,7 +775,7 @@ mod tests {);assert_eq!(drain(&mut runtime),- (BoxliteErrorCode::Ok, "checkpoint-1:ready:".into())+ (BoxliteErrorCode::Ok, "checkpoint-1:ready::disk:0:0".into()));}assert_eq!(@@ -678,7 +792,7 @@ mod tests {drain(&mut runtime),(BoxliteErrorCode::Ok,- "checkpoint-1:failed:upload failed".into()+ "checkpoint-1:failed:upload failed:disk:0:0".into()));assert_eq!(@@ -740,6 +854,38 @@ mod tests {drain(&mut runtime),(BoxliteErrorCode::NotFound, String::new()));+ for (kind, code, metadata) in [+ (+ ptr::null(),+ BoxliteErrorCode::Ok,+ "checkpoint-1:ready::disk:0:0",+ ),+ (+ c"disk".as_ptr(),+ BoxliteErrorCode::Ok,+ "checkpoint-1:ready::disk:0:0",+ ),+ (c"full".as_ptr(), BoxliteErrorCode::Unsupported, ""),+ (+ c"full".as_ptr(),+ BoxliteErrorCode::Ok,+ "checkpoint-1:ready::full:1:0",+ ),+ ] {+ assert_eq!(+ boxlite_checkpoint_create_with_options(+ &mut runtime,+ source.as_ptr(),+ ptr::null(),+ kind,+ Some(checkpoint_metadata_reply),+ data,+ ptr::null_mut(),+ ),+ BoxliteErrorCode::Ok+ );+ assert_eq!(drain(&mut runtime), (code, metadata.into()));+ }}let requests = server.join().unwrap();assert_eq!(@@ -756,6 +902,21 @@ mod tests {serde_json::json!({"checkpoint_id":"checkpoint-1","name":"worker"}));assert_eq!(requests[5].1, "/v1/checkpoints/checkpoint-1?force=true");+ for request in &requests[7..9] {+ assert_eq!(request.0, "POST");+ assert_eq!(request.1, "/v1/checkpoints");+ assert_eq!(request.2, requests[1].2);+ }+ for request in &requests[9..11] {+ assert_eq!(request.0, "GET");+ assert_eq!(request.1, "/v1/config");+ }+ assert_eq!(requests[11].0, "POST");+ assert_eq!(requests[11].1, "/v1/checkpoints");+ assert_eq!(+ requests[11].2,+ serde_json::json!({"source_box_id":"source-1","kind":"full"})+ );});}}diff --git a/sdks/go/README.md b/sdks/go/README.mdindex 27299ef17..7c3a6265d 100644--- a/sdks/go/README.md+++ b/sdks/go/README.md@@ -31,21 +31,33 @@ create call. The checkpoint handle only manages checkpoints. Archive import is aseparate operation for local `.boxlite` files and is unchanged. The CLI form is`boxlite create --checkpoint ID [--name NAME]`.-The source must be stopped before `Create`; stop it and wait for `stopped` first.-Checkpoint creation rejects other states and never stops the source automatically.--On REST runtimes, `runtime.Checkpoints()` exposes `Create`, `List`, `Get` and-`Remove`, each taking a context. The handle follows its runtime's+`Create` captures a disk checkpoint from a stopped box. With+`CreateWithOptions(ctx, source, name, opts)`, set `opts.Kind` to a+`CheckpointKind`: leave it empty or use `CheckpointKindDisk` for disk capture.+Use `CheckpointKindFull` to capture disk, guest memory, and VM state from a+running box. Full capture checks `capabilities.memory_checkpoints_enabled`+through `GET /v1/config` before submitting the capture. If the server omits or+disables the capability, the call returns `ErrUnsupported`. Disk capture skips+the preflight.++On REST runtimes, `runtime.Checkpoints()` exposes `Create`, `CreateWithOptions`,+`List`, `Get`, and `Remove`, each taking a context. The handle follows its runtime'slifetime and needs no separate close. Captured archives survive source deletion.```go-checkpoint, err := runtime.Checkpoints().Create(ctx, "source", "dev-base")+checkpoint, err := runtime.Checkpoints().CreateWithOptions(ctx, "source", "dev-base",+ boxlite.CheckpointOptions{Kind: boxlite.CheckpointKindFull})if err != nil { return err }worker, err := runtime.Create(ctx, "", boxlite.WithCheckpoint(checkpoint.ID), boxlite.WithName("worker"))if err != nil { return err }defer worker.Close()```+`CheckpointInfo.Kind` reports the archive kind, including `"unknown"` for an+unrecognized server kind. `CheckpointInfo.MemorySizeBytes` is a pointer to the+archived guest memory size and is `nil` when the server omits it. A reported+zero comes back as a pointer to zero.+Pass an empty image with `WithCheckpoint`; combining it with an image or`WithRootfsPath` returns an error.diff --git a/sdks/go/checkpoints.go b/sdks/go/checkpoints.goindex ac29f7582..8bdb80f09 100644--- a/sdks/go/checkpoints.go+++ b/sdks/go/checkpoints.go@@ -12,7 +12,20 @@ import ("unsafe")-// CheckpointInfo describes an independent managed disk archive.+// CheckpointKind specifies the contents of a managed checkpoint.+type CheckpointKind string++const (+ CheckpointKindDisk CheckpointKind = "disk"+ CheckpointKindFull CheckpointKind = "full"+ // CheckpointKindUnknown represents a server-reported kind the SDK does not recognize.+ CheckpointKindUnknown CheckpointKind = "unknown"+)++// CheckpointOptions selects the archive kind. An empty Kind selects disk.+type CheckpointOptions struct{ Kind CheckpointKind }++// CheckpointInfo describes an independent managed checkpoint archive.type CheckpointInfo struct {ID stringName string@@ -21,6 +34,9 @@ type CheckpointInfo struct {SizeBytes uint64State stringErrorReason string+ Kind CheckpointKind+ // MemorySizeBytes is nil when the server does not report a memory size.+ MemorySizeBytes *uint64}// Checkpoints manages organization-scoped checkpoints through REST. Its lifetime@@ -45,15 +61,27 @@ func (c *Checkpoints) ready(ctx context.Context) (*Runtime, error) {return c.runtime, nil}-// Create captures source directly. Empty name lets the backend choose a name.+// Create captures a disk checkpoint of a stopped box. An empty name lets the backend choose a name.// Cloud capture can initially report creating; query until ready before use.func (c *Checkpoints) Create(ctx context.Context, source, name string) (*CheckpointInfo, error) {+ return c.CreateWithOptions(ctx, source, name, CheckpointOptions{})+}++// CreateWithOptions captures a disk checkpoint of a stopped box or a full+// checkpoint of a running box on a REST server that supports full capture.+// An empty name lets the backend choose a name.+func (c *Checkpoints) CreateWithOptions(ctx context.Context, source, name string, opts CheckpointOptions) (*CheckpointInfo, error) {if err := validateArchiveArgument(source, "checkpoint source", false); err != nil {return nil, err}if err := validateArchiveArgument(name, "checkpoint name", true); err != nil {return nil, err}+ switch opts.Kind {+ case "", CheckpointKindDisk, CheckpointKindFull:+ default:+ return nil, &Error{Code: ErrInvalidArgument, Message: "checkpoint kind must be disk or full"}+ }runtime, err := c.ready(ctx)if err != nil {return nil, err@@ -62,10 +90,15 @@ func (c *Checkpoints) Create(ctx context.Context, source, name string) (*Checkpodefer C.free(unsafe.Pointer(cSource))cName, freeName := archiveNameCString(name)defer freeName()+ var cKind *C.char+ if opts.Kind != "" {+ cKind = toCString(string(opts.Kind))+ defer C.free(unsafe.Pointer(cKind))+ }result := make(chan handleResult[*C.CCheckpointInfo], 1)handle := registerHandleForDispatch(cgo.NewHandle(result))var nativeError C.CBoxliteError- code := C.boxlite_checkpoint_create(runtime.handle, cSource, cName, C.cbCheckpointInfo(), handleToPtr(handle), &nativeError)+ code := C.boxlite_checkpoint_create_with_options(runtime.handle, cSource, cName, cKind, C.cbCheckpointInfo(), handleToPtr(handle), &nativeError)if code != C.Ok {deleteHandleForDispatch(handle)return nil, freeError(&nativeError)@@ -159,7 +192,21 @@ func (c *Checkpoints) Remove(ctx context.Context, key string, force bool) error}func checkpointInfoFromC(info *C.CCheckpointInfo) CheckpointInfo {- return CheckpointInfo{ID: cString(info.id), Name: cString(info.name), SourceBoxID: cString(info.source_box_id), CreatedAt: cString(info.created_at), SizeBytes: uint64(info.size_bytes), State: cString(info.state), ErrorReason: cString(info.error_reason)}+ checkpoint := CheckpointInfo{+ ID: cString(info.id),+ Name: cString(info.name),+ SourceBoxID: cString(info.source_box_id),+ CreatedAt: cString(info.created_at),+ SizeBytes: uint64(info.size_bytes),+ State: cString(info.state),+ ErrorReason: cString(info.error_reason),+ Kind: CheckpointKind(cString(info.kind)),+ }+ if info.has_memory_size_bytes != 0 {+ size := uint64(info.memory_size_bytes)+ checkpoint.MemorySizeBytes = &size+ }+ return checkpoint}func checkpointInfoResult(ctx context.Context, runtime *Runtime, result <-chan handleResult[*C.CCheckpointInfo], handle cgo.Handle) (*CheckpointInfo, error) {diff --git a/sdks/go/checkpoints_test.go b/sdks/go/checkpoints_test.goindex 62b7c5c52..08ef00be6 100644--- a/sdks/go/checkpoints_test.go+++ b/sdks/go/checkpoints_test.go@@ -4,6 +4,7 @@ import ("context""encoding/json""errors"+ "maps""net/http""net/http/httptest""reflect"@@ -21,6 +22,10 @@ func TestCheckpointManagementNativeRestBoundary(t *testing.T) {var mu sync.Mutexvar requests []requestinfo := map[string]any{"id": "checkpoint-1", "name": "base", "source_box_id": "source-1", "created_at": "2026-11-06T00:00:00Z", "size_bytes": 4096, "state": "ready"}+ full := maps.Clone(info)+ full["id"], full["kind"], full["memory_size_bytes"] = "checkpoint-2", "full", 0+ future := maps.Clone(info)+ future["id"], future["kind"], future["memory_size_bytes"] = "checkpoint-3", "future", 4096box := map[string]any{"box_id": "target-1", "name": "worker", "status": "stopped", "image": "alpine:latest", "cpus": 2, "memory_mib": 512, "created_at": info["created_at"], "updated_at": info["created_at"]}server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {var body map[string]any@@ -41,7 +46,7 @@ func TestCheckpointManagementNativeRestBoundary(t *testing.T) {if strings.HasPrefix(r.URL.Path, "/v1/boxes") {response = box} else if r.Method == http.MethodGet && r.URL.Path == "/v1/checkpoints" {- response = map[string]any{"checkpoints": []any{info}}+ response = map[string]any{"checkpoints": []any{info, full, future}}}if r.Method == http.MethodGet && r.URL.Path == "/v1/checkpoints/checkpoint-1" {failed := make(map[string]any, len(info)+1)@@ -70,10 +75,22 @@ func TestCheckpointManagementNativeRestBoundary(t *testing.T) {if captured.ID != "checkpoint-1" || captured.State != "ready" || captured.SizeBytes != 4096 {t.Fatalf("metadata: %+v", captured)}+ if captured.Kind != CheckpointKindDisk || captured.MemorySizeBytes != nil {+ t.Fatalf("disk metadata: %+v", captured)+ }list, err := checkpoints.List(ctx)- if err != nil || len(list) != 1 || list[0].SourceBoxID != "source-1" {+ if err != nil || len(list) != 3 {t.Fatalf("list: %+v %v", list, err)}+ if disk := list[0]; disk.ID != "checkpoint-1" || disk.SourceBoxID != "source-1" || disk.Kind != CheckpointKindDisk || disk.MemorySizeBytes != nil {+ t.Fatalf("disk list metadata: %+v", disk)+ }+ if full := list[1]; full.ID != "checkpoint-2" || full.Kind != CheckpointKindFull || full.MemorySizeBytes == nil || *full.MemorySizeBytes != 0 {+ t.Fatalf("full list metadata: %+v", full)+ }+ if future := list[2]; future.ID != "checkpoint-3" || future.Kind != CheckpointKindUnknown || future.MemorySizeBytes == nil || *future.MemorySizeBytes != 4096 {+ t.Fatalf("unknown list metadata: %+v", future)+ }detail, err := checkpoints.Get(ctx, "checkpoint-1")if err != nil || detail.ID != captured.ID || detail.State != "failed" || detail.ErrorReason != "archive upload failed" {t.Fatalf("get: %+v %v", detail, err)@@ -127,9 +144,79 @@ func TestCheckpointManagementNativeRestBoundary(t *testing.T) {}}+func TestCheckpointCreateWithOptions(t *testing.T) {+ zero, used := uint64(0), uint64(4096)+ post, config := "POST /v1/checkpoints", "GET /v1/config"+ for _, tc := range []struct {+ name string+ kind CheckpointKind+ enabled bool+ response string+ wantKind CheckpointKind+ wantMemory *uint64+ wantCalls []string+ }{+ {"default", "", false, "", CheckpointKindDisk, nil, []string{post}},+ {"disk", CheckpointKindDisk, false, "", CheckpointKindDisk, nil, []string{post}},+ {"full zero", CheckpointKindFull, true, `,"kind":"full","memory_size_bytes":0`, CheckpointKindFull, &zero, []string{config, post}},+ {"full nonzero", CheckpointKindFull, true, `,"kind":"full","memory_size_bytes":4096`, CheckpointKindFull, &used, []string{config, post}},+ {"full disabled", CheckpointKindFull, false, "", "", nil, []string{config}},+ {"unknown response", "", false, `,"kind":"future"`, CheckpointKindUnknown, nil, []string{post}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ var mu sync.Mutex+ var calls []string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ calls = append(calls, r.Method+" "+r.URL.RequestURI())+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == "/v1/config" {+ _ = json.NewEncoder(w).Encode(map[string]any{"capabilities": map[string]bool{"memory_checkpoints_enabled": tc.enabled}})+ return+ }+ want := map[string]any{"source_box_id": "source-1", "name": "base"}+ if tc.kind == CheckpointKindFull {+ want["kind"] = "full"+ }+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil || !reflect.DeepEqual(body, want) {+ t.Errorf("request body = %v, want %v (decode error: %v)", body, want, err)+ }+ _, _ = w.Write([]byte(`{"id":"cp-1","name":"base","source_box_id":"source-1","created_at":"2026-11-06T00:00:00Z","size_bytes":8192` + tc.response + "}"))+ }))+ defer server.Close()+ runtime, err := NewRest(BoxliteRestOptions{URL: server.URL})+ if err != nil {+ t.Fatal(err)+ }+ defer runtime.Close()+ info, err := runtime.Checkpoints().CreateWithOptions(context.Background(), "source-1", "base", CheckpointOptions{Kind: tc.kind})+ if tc.kind == CheckpointKindFull && !tc.enabled {+ requireErrorCode(t, err, ErrUnsupported, "full checkpoint")+ } else if err != nil || info == nil || info.Kind != tc.wantKind || !reflect.DeepEqual(info.MemorySizeBytes, tc.wantMemory) {+ t.Fatalf("metadata = %+v, error = %v, want kind %q and memory %v", info, err, tc.wantKind, tc.wantMemory)+ }+ mu.Lock()+ defer mu.Unlock()+ if !reflect.DeepEqual(calls, tc.wantCalls) {+ t.Fatalf("requests = %v, want %v", calls, tc.wantCalls)+ }+ })+ }+}+func TestCheckpointManagementRejectsInvalidInputsAndClosedRuntime(t *testing.T) {ctx := context.Background()checkpoints := (&Runtime{}).Checkpoints()+ for _, kind := range []CheckpointKind{"bogus", CheckpointKindUnknown, "full\x00"} {+ if _, err := checkpoints.CreateWithOptions(ctx, "source-1", "base", CheckpointOptions{Kind: kind}); !IsInvalidArgument(err) {+ t.Fatalf("create with kind %q: %v", kind, err)+ }+ }+ if _, err := checkpoints.CreateWithOptions(ctx, "source-1", "bad\x00name", CheckpointOptions{Kind: CheckpointKindFull}); !IsInvalidArgument(err) {+ t.Fatalf("create with invalid name: %v", err)+ }for _, key := range []string{"", "bad\x00suffix"} {if _, err := checkpoints.Get(ctx, key); !IsInvalidArgument(err) {t.Fatalf("get %q: %v", key, err)diff --git a/sdks/node/README.md b/sdks/node/README.mdindex 7783060ef..ff9eeb332 100644--- a/sdks/node/README.md+++ b/sdks/node/README.md@@ -20,16 +20,21 @@ and call `events.return()` to close it.## Managed checkpoints-A checkpoint is a source for a new box, like an image: pass it to the ordinary-create call. The checkpoint handle only manages checkpoints. Archive import is a-separate operation for local `.boxlite` files and is unchanged. The CLI form is+Pass a checkpoint to the ordinary create call to use it as the source for a new+box. The checkpoint handle manages checkpoint archives. Archive import loads+local `.boxlite` files. The CLI form for creating a box from a checkpoint is`boxlite create --checkpoint ID [--name NAME]`.-The source must be stopped before `create`; stop it and wait for `stopped` first.-Checkpoint creation rejects other states and never stops the source automatically.+In `CheckpointOptions`, `kind: "disk"` captures a stopped, idle source and is+the default. `kind: "full"` captures disk and memory from a running source.+Before requesting full capture, the SDK checks that the REST server advertises+`memory_checkpoints_enabled`.-The REST runtime's `checkpoints` handle exposes `create`, `list`,-`get` and `remove` as promises. Checkpoints survive their source box.+The REST runtime's `checkpoints` handle exposes `create(source, name?, options?)`,+`list()`, `get(key)`, and `remove(key, force?)` as promises. Checkpoints survive+source deletion. `CheckpointInfo.kind` is `"disk"`, `"full"`, or `"unknown"` for+an unrecognized server kind. `CheckpointInfo.memorySizeBytes` is absent when+omitted by the server and preserves a reported zero.```typescriptconst checkpoint = await runtime.checkpoints.create("source", "dev-base");diff --git a/sdks/node/lib/index.ts b/sdks/node/lib/index.tsindex 0ab1d89cc..6adb298ef 100644--- a/sdks/node/lib/index.ts+++ b/sdks/node/lib/index.ts@@ -33,6 +33,8 @@ import type {export type {CheckpointHandle,CheckpointInfo,+ CheckpointKind,+ CheckpointOptions,Domain,DomainHandle,DomainList,diff --git a/sdks/node/lib/native-contracts.ts b/sdks/node/lib/native-contracts.tsindex 4e5827636..eaa1ca3ba 100644--- a/sdks/node/lib/native-contracts.ts+++ b/sdks/node/lib/native-contracts.ts@@ -170,19 +170,31 @@ export interface VolumeHandle {remove(id: string, force?: boolean | null): Promise<void>;}-/** Independent managed disk archive, local or organization scoped. */+export type CheckpointKind = "disk" | "full" | "unknown";++export interface CheckpointOptions {+ kind?: "disk" | "full" | null;+}++/** Metadata for a managed checkpoint archive. */export interface CheckpointInfo {id: string;name: string;sourceBoxId: string;createdAt: string;sizeBytes: number;+ kind: CheckpointKind;+ memorySizeBytes?: number;state: "creating" | "ready" | "failed" | "deleting";errorReason?: string;}export interface CheckpointHandle {- create(source: string, name?: string | null): Promise<CheckpointInfo>;+ create(+ source: string,+ name?: string | null,+ options?: CheckpointOptions | null,+ ): Promise<CheckpointInfo>;list(): Promise<CheckpointInfo[]>;get(key: string): Promise<CheckpointInfo>;remove(key: string, force?: boolean | null): Promise<void>;diff --git a/sdks/node/src/checkpoints.rs b/sdks/node/src/checkpoints.rsindex 967883d60..4703e8d68 100644--- a/sdks/node/src/checkpoints.rs+++ b/sdks/node/src/checkpoints.rs@@ -1,13 +1,57 @@-//! REST-managed disk checkpoints; local runtimes return Unsupported.+//! REST-managed checkpoints. Local runtimes return Unsupported.use std::sync::Arc;-use boxlite::{CheckpointHandle, CheckpointInfo};+use boxlite::{BoxliteError, CheckpointHandle, CheckpointInfo, CheckpointKind, CheckpointOptions};use napi::bindgen_prelude::*;use napi_derive::napi;use crate::util::map_err;+#[napi(object, object_from_js = false)]+#[derive(Debug)]+pub struct JsCheckpointOptions {+ #[napi(ts_type = "\"disk\" | \"full\" | null")]+ pub kind: Option<String>,+}++impl ValidateNapiValue for JsCheckpointOptions {}++impl FromNapiValue for JsCheckpointOptions {+ unsafe fn from_napi_value(env: sys::napi_env, value: sys::napi_value) -> Result<Self> {+ // SAFETY: napi provides an environment and value from the same JS call.+ let value = unsafe { Unknown::from_napi_value(env, value)? };+ if value.get_type()? != ValueType::Object || value.is_array()? {+ return Err(map_err(BoxliteError::InvalidArgument(+ "checkpoint options must be an object".into(),+ )));+ }+ // SAFETY: the value has been checked to be an object.+ let object: Object = unsafe { value.cast()? };+ // Read through Option so both an omitted property and null select the default.+ let kind = object.get::<Option<String>>("kind")?.flatten();+ Ok(Self { kind })+ }+}++impl TryFrom<JsCheckpointOptions> for CheckpointOptions {+ type Error = BoxliteError;++ fn try_from(options: JsCheckpointOptions) -> std::result::Result<Self, Self::Error> {+ let kind = match options.kind.as_deref() {+ None => None,+ Some("disk") => Some(CheckpointKind::Disk),+ Some("full") => Some(CheckpointKind::Full),+ Some(other) => {+ return Err(BoxliteError::InvalidArgument(format!(+ "checkpoint kind must be disk or full, got {other:?}"+ )));+ }+ };+ Ok(Self { kind })+ }+}+#[napi(object)]pub struct JsCheckpointInfo {pub id: String,@@ -18,6 +62,9 @@ pub struct JsCheckpointInfo {pub created_at: String,#[napi(js_name = "sizeBytes")]pub size_bytes: i64,+ pub kind: String,+ #[napi(js_name = "memorySizeBytes")]+ pub memory_size_bytes: Option<i64>,pub state: String,#[napi(js_name = "errorReason")]pub error_reason: Option<String>,@@ -31,6 +78,10 @@ impl From<CheckpointInfo> for JsCheckpointInfo {source_box_id: info.source_box_id,created_at: info.created_at.to_rfc3339(),size_bytes: i64::try_from(info.size_bytes).unwrap_or(i64::MAX),+ kind: info.kind.as_str().to_string(),+ memory_size_bytes: info+ .memory_size_bytes+ .map(|n| i64::try_from(n).unwrap_or(i64::MAX)),state: format!("{:?}", info.state).to_lowercase(),error_reason: info.error_reason,}@@ -45,10 +96,20 @@ pub struct JsCheckpointHandle {#[napi]impl JsCheckpointHandle {#[napi]- pub async fn create(&self, source: String, name: Option<String>) -> Result<JsCheckpointInfo> {+ pub async fn create(+ &self,+ source: String,+ name: Option<String>,+ options: Option<JsCheckpointOptions>,+ ) -> Result<JsCheckpointInfo> {+ let parsed = options+ .map(CheckpointOptions::try_from)+ .transpose()+ .map_err(map_err)?+ .unwrap_or_default();Ok(self.handle- .create(&source, name)+ .create_with_options(&source, name, parsed).await.map_err(map_err)?.into())@@ -80,3 +141,54 @@ impl JsCheckpointHandle {.map_err(map_err)}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_checkpoint_options() {+ for (kind, expected) in [+ (None, None),+ (Some("disk"), Some(CheckpointKind::Disk)),+ (Some("full"), Some(CheckpointKind::Full)),+ ] {+ let options = JsCheckpointOptions {+ kind: kind.map(str::to_owned),+ };+ assert_eq!(CheckpointOptions::try_from(options).unwrap().kind, expected);+ }+ for kind in ["", "unknown", "bogus"] {+ let error = CheckpointOptions::try_from(JsCheckpointOptions {+ kind: Some(kind.into()),+ })+ .unwrap_err();+ assert!(matches!(error, BoxliteError::InvalidArgument(_)));+ assert!(map_err(error).reason.starts_with("invalid argument: "));+ }+ }++ #[test]+ fn converts_checkpoint_metadata() {+ for (kind, memory_size_bytes, expected_kind, expected_size) in [+ (CheckpointKind::Disk, None, "disk", None),+ (CheckpointKind::Full, Some(0), "full", Some(0)),+ (CheckpointKind::Full, Some(4096), "full", Some(4096)),+ (CheckpointKind::Unknown, None, "unknown", None),+ ] {+ let info = JsCheckpointInfo::from(CheckpointInfo {+ id: "checkpoint-1".into(),+ name: "backup".into(),+ source_box_id: "source-1".into(),+ created_at: Default::default(),+ size_bytes: 4096,+ state: Default::default(),+ error_reason: None,+ kind,+ memory_size_bytes,+ });+ assert_eq!(info.kind, expected_kind);+ assert_eq!(info.memory_size_bytes, expected_size);+ }+ }+}diff --git a/sdks/node/src/lib.rs b/sdks/node/src/lib.rsindex 0affd010f..2d51653d7 100644--- a/sdks/node/src/lib.rs+++ b/sdks/node/src/lib.rs@@ -29,7 +29,7 @@ mod volumes;// Re-export all public typespub use advanced_options::{JsAdvancedBoxOptions, JsContainerCapabilities, JsSecurityOptions};pub use box_handle::JsBox;-pub use checkpoints::{JsCheckpointHandle, JsCheckpointInfo};+pub use checkpoints::{JsCheckpointHandle, JsCheckpointInfo, JsCheckpointOptions};pub use copy::JsCopyOptions;pub use domains::{JsDomain, JsDomainHandle, JsDomainList, JsDomainTarget};pub use exec::{diff --git a/sdks/node/tests/checkpoints.integration.test.ts b/sdks/node/tests/checkpoints.integration.test.tsindex 9c849a2a4..ca8333888 100644--- a/sdks/node/tests/checkpoints.integration.test.ts+++ b/sdks/node/tests/checkpoints.integration.test.ts@@ -1,7 +1,7 @@import { createServer } from "node:http";import type { AddressInfo } from "node:net";import { expect, test } from "vitest";-import { BoxliteRestOptions, JsBoxlite } from "../lib/index.js";+import { BoxliteRestOptions, errorCode, JsBoxlite } from "../lib/index.js";test("checkpoint native methods reject an unwrapped receiver", async () => {const runtime = JsBoxlite.rest(@@ -16,6 +16,7 @@ test("checkpoint native methods reject an unwrapped receiver", async () => {test("checkpoint native REST calls preserve configuration inheritance and result identity", async () => {const requests: Array<{ method?: string; path?: string; body?: unknown }> =[];+ let memoryCheckpointsEnabled = true;const checkpoint = {id: "checkpoint-1",name: "base",@@ -28,16 +29,39 @@ test("checkpoint native REST calls preserve configuration inheritance and resultconst chunks: Buffer[] = [];for await (const chunk of request) chunks.push(Buffer.from(chunk));const bytes = Buffer.concat(chunks).toString();+ const capture = bytes+ ? (JSON.parse(bytes) as { kind?: string; name?: string })+ : undefined;requests.push({method: request.method,path: request.url,- body: bytes ? JSON.parse(bytes) : undefined,+ body: capture,});response.setHeader("Content-Type", "application/json");if (request.method === "DELETE") {response.writeHead(204).end();return;}+ if (request.url === "/v1/config") {+ response.end(+ JSON.stringify({+ capabilities: {+ memory_checkpoints_enabled: memoryCheckpointsEnabled,+ },+ }),+ );+ return;+ }+ if (request.method === "POST" && capture?.kind === "full") {+ response.end(+ JSON.stringify({+ ...checkpoint,+ kind: "full",+ memory_size_bytes: capture.name === "full-zero" ? 0 : undefined,+ }),+ );+ return;+ }const body = request.url?.startsWith("/v1/boxes")? {box_id: "target-1",@@ -50,7 +74,7 @@ test("checkpoint native REST calls preserve configuration inheritance and resultupdated_at: checkpoint.created_at,}: request.method === "GET" && request.url === "/v1/checkpoints"- ? { checkpoints: [checkpoint] }+ ? { checkpoints: [{ ...checkpoint, kind: "future" }] }: checkpoint;response.end(JSON.stringify(@@ -58,6 +82,7 @@ test("checkpoint native REST calls preserve configuration inheritance and resultrequest.url === "/v1/checkpoints/checkpoint-1"? {...checkpoint,+ kind: "future",state: "failed",error_reason: "archive upload failed",}@@ -69,16 +94,35 @@ test("checkpoint native REST calls preserve configuration inheritance and resulttry {const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;const runtime = JsBoxlite.rest(new BoxliteRestOptions({ url }));+ for (const options of ["full", [], 123]) {+ await expect(async () =>+ runtime.checkpoints.create("source-1", null, options as never),+ ).rejects.toSatisfy(+ (err: unknown) => errorCode(err) === "invalid_argument",+ );+ }+ expect(requests).toEqual([]);+ await expect(async () =>+ runtime.checkpoints.create("source-1", null, { kind: "bogus" as never }),+ ).rejects.toSatisfy(+ (err: unknown) => errorCode(err) === "invalid_argument",+ );+ expect(requests).toEqual([]);const captured = await runtime.checkpoints.create("source-1", "base");expect(captured).toMatchObject({id: "checkpoint-1",sourceBoxId: "source-1",sizeBytes: 4096,+ kind: "disk",state: "ready",});- expect((await runtime.checkpoints.list())[0].id).toBe("checkpoint-1");+ expect((await runtime.checkpoints.list())[0]).toMatchObject({+ id: "checkpoint-1",+ kind: "unknown",+ });expect(await runtime.checkpoints.get("checkpoint-1")).toMatchObject({name: "base",+ kind: "unknown",state: "failed",errorReason: "archive upload failed",});@@ -91,7 +135,15 @@ test("checkpoint native REST calls preserve configuration inheritance and resultawait runtime.checkpoints.remove("checkpoint-1", true);await runtime.checkpoints.remove("checkpoint-1");await runtime.checkpoints.remove("checkpoint-1", false);- await runtime.checkpoints.create("source-1");+ for (const options of [+ undefined,+ null,+ {},+ { kind: null },+ { kind: "disk" },+ ] as const) {+ await runtime.checkpoints.create("source-1", undefined, options);+ }await runtime.create({ checkpoint: "checkpoint-1" });for (const overridden of [{ checkpoint: "checkpoint-1", cpus: 2 },@@ -128,17 +180,47 @@ test("checkpoint native REST calls preserve configuration inheritance and resultpath: "/v1/checkpoints/checkpoint-1",body: undefined,},- {+ ...Array.from({ length: 5 }, () => ({method: "POST",path: "/v1/checkpoints",body: { source_box_id: "source-1" },- },+ })),{method: "POST",path: "/v1/boxes",body: { checkpoint_id: "checkpoint-1" },},]);++ requests.length = 0;+ for (const [name, memorySizeBytes] of [+ ["full-zero", 0],+ ["full-pending", undefined],+ ] as const) {+ const info = await runtime.checkpoints.create("source-1", name, {+ kind: "full",+ });+ expect(info.kind).toBe("full");+ expect(info.memorySizeBytes).toBe(memorySizeBytes);+ }+ expect(requests).toEqual(+ ["full-zero", "full-pending"].flatMap((name) => [+ { method: "GET", path: "/v1/config", body: undefined },+ {+ method: "POST",+ path: "/v1/checkpoints",+ body: { source_box_id: "source-1", name, kind: "full" },+ },+ ]),+ );+ requests.length = 0;+ memoryCheckpointsEnabled = false;+ await expect(+ runtime.checkpoints.create("source-1", null, { kind: "full" }),+ ).rejects.toSatisfy((err: unknown) => errorCode(err) === "unsupported");+ expect(requests).toEqual([+ { method: "GET", path: "/v1/config", body: undefined },+ ]);} finally {server.closeAllConnections();await new Promise<void>((resolve, reject) =>diff --git a/sdks/python/README.md b/sdks/python/README.mdindex 6594e0a11..c282f819f 100644--- a/sdks/python/README.md+++ b/sdks/python/README.md@@ -14,23 +14,30 @@ when finished; cancellation of a read preserves its pending event for the next r## Managed checkpoints-Checkpoint settings must be omitted, including explicit defaults such as-`detach=False`, `tty=False`, or `advanced=AdvancedBoxOptions(privileged=False)`.+When creating a box from a checkpoint, omit execution settings, including+explicit defaults such as `detach=False`, `tty=False`, or+`advanced=AdvancedBoxOptions(privileged=False)`.Explicit empty `env`, `volumes`, `ports`, or `secrets` lists also reject.Omitted collection arguments default to `None` and normalize to empty lists;ordinary image creation continues accepting empty lists.-A checkpoint is a source for a new box, like an image: pass it to the ordinary-create call. The checkpoint handle only manages checkpoints. Archive import is a-separate operation for local `.boxlite` files and is unchanged. The CLI form is+Pass a checkpoint to the ordinary create call to use it as the source for a new+box. The checkpoint handle manages checkpoint archives. Archive import loads+local `.boxlite` files. The CLI form for creating a box from a checkpoint is`boxlite create --checkpoint ID [--name NAME]`.-The source must be stopped before `create`; stop it and wait for `stopped` first.-Checkpoint creation rejects other states and never stops the source automatically.--On REST runtimes, `runtime.checkpoints` exposes async `create(source, name=None)`, `list()`,-`get(key)` and `remove(key, force=False)`. `SyncBoxlite.checkpoints` exposes the same-operations synchronously. These independent archives survive source deletion.+`CheckpointOptions(kind="disk")` captures a stopped, idle source and is the+default. `CheckpointOptions(kind="full")` captures disk and memory from a+running source. Before requesting full capture, the SDK checks that the REST+server advertises `memory_checkpoints_enabled`.++On REST runtimes, `runtime.checkpoints` exposes async+`create(source, name=None, options=None)`, `list()`, `get(key)`, and+`remove(key, force=False)`. `SyncBoxlite.checkpoints` exposes the same operations+synchronously. Checkpoints survive source deletion. `CheckpointInfo.kind` is+`"disk"`, `"full"`, or `"unknown"` for an unrecognized server kind.+`CheckpointInfo.memory_size_bytes` is `None` when omitted by the server and+preserves a reported zero.```pythoncheckpoint = await runtime.checkpoints.create("source", "dev-base")diff --git a/sdks/python/boxlite/__init__.py b/sdks/python/boxlite/__init__.pyindex 05d68c374..f8f820f40 100644--- a/sdks/python/boxlite/__init__.py+++ b/sdks/python/boxlite/__init__.py@@ -21,6 +21,7 @@ try:BoxStateInfo,CheckpointHandle,CheckpointInfo,+ CheckpointOptions,CloneOptions,ContainerCapabilities,CopyOptions,@@ -87,6 +88,7 @@ try:"Boxlite","CheckpointHandle","CheckpointInfo",+ "CheckpointOptions","NetworkSpec","OutboundNetworkSpec","InboundNetworkSpec",diff --git a/sdks/python/boxlite/sync_api/_checkpoints.py b/sdks/python/boxlite/sync_api/_checkpoints.pyindex c559c0b33..df572e910 100644--- a/sdks/python/boxlite/sync_api/_checkpoints.py+++ b/sdks/python/boxlite/sync_api/_checkpoints.py@@ -3,7 +3,7 @@from typing import TYPE_CHECKINGif TYPE_CHECKING:- from ..boxlite import CheckpointHandle, CheckpointInfo+ from ..boxlite import CheckpointHandle, CheckpointInfo, CheckpointOptionsfrom ._boxlite import SyncBoxlite@@ -15,8 +15,13 @@ class SyncCheckpointHandle:self._handle = handleself._bridge = SyncBase(handle, runtime.loop, runtime.dispatcher_fiber)- def create(self, source: str, name: str | None = None) -> "CheckpointInfo":- return self._bridge._sync(self._handle.create(source, name))+ def create(+ self,+ source: str,+ name: str | None = None,+ options: "CheckpointOptions | None" = None,+ ) -> "CheckpointInfo":+ return self._bridge._sync(self._handle.create(source, name, options))def list(self) -> list["CheckpointInfo"]:return self._bridge._sync(self._handle.list())diff --git a/sdks/python/src/checkpoints.rs b/sdks/python/src/checkpoints.rsindex 6aa014516..e8daa5440 100644--- a/sdks/python/src/checkpoints.rs+++ b/sdks/python/src/checkpoints.rs@@ -2,11 +2,53 @@use std::sync::Arc;-use boxlite::{CheckpointHandle, CheckpointInfo};+use boxlite::{+ BoxliteError, BoxliteResult, CheckpointHandle, CheckpointInfo, CheckpointKind,+ CheckpointOptions,+};use pyo3::prelude::*;use crate::util::map_err;+#[pyclass(name = "CheckpointOptions", from_py_object)]+#[derive(Clone, Default)]+pub(crate) struct PyCheckpointOptions {+ #[pyo3(get, set)]+ pub(crate) kind: Option<String>,+}++#[pymethods]+impl PyCheckpointOptions {+ #[new]+ #[pyo3(signature = (kind=None))]+ fn new(kind: Option<String>) -> Self {+ Self { kind }+ }++ fn __repr__(&self) -> String {+ match &self.kind {+ Some(kind) => format!("CheckpointOptions(kind={kind:?})"),+ None => "CheckpointOptions(kind=None)".into(),+ }+ }+}++fn parse_checkpoint_options(+ options: Option<PyCheckpointOptions>,+) -> BoxliteResult<CheckpointOptions> {+ let kind = match options.and_then(|options| options.kind).as_deref() {+ None => None,+ Some("disk") => Some(CheckpointKind::Disk),+ Some("full") => Some(CheckpointKind::Full),+ Some(kind) => {+ return Err(BoxliteError::InvalidArgument(format!(+ "checkpoint kind must be 'disk' or 'full', got {kind:?}"+ )));+ }+ };+ Ok(CheckpointOptions { kind })+}+#[pyclass(name = "CheckpointInfo")]#[derive(Clone)]pub(crate) struct PyCheckpointInfo {@@ -24,6 +66,10 @@ pub(crate) struct PyCheckpointInfo {state: String,#[pyo3(get)]error_reason: Option<String>,+ #[pyo3(get)]+ kind: String,+ #[pyo3(get)]+ memory_size_bytes: Option<u64>,}impl From<CheckpointInfo> for PyCheckpointInfo {@@ -36,6 +82,8 @@ impl From<CheckpointInfo> for PyCheckpointInfo {size_bytes: info.size_bytes,state: format!("{:?}", info.state).to_lowercase(),error_reason: info.error_reason,+ kind: info.kind.as_str().to_string(),+ memory_size_bytes: info.memory_size_bytes,}}}@@ -47,18 +95,23 @@ pub(crate) struct PyCheckpointHandle {#[pymethods]impl PyCheckpointHandle {- /// Capture a box directly into an independent managed disk archive.- #[pyo3(signature = (source, name=None))]+ /// Capture a box into an independent managed checkpoint.+ #[pyo3(signature = (source, name=None, options=None))]fn create<'py>(&self,py: Python<'py>,source: String,name: Option<String>,+ options: Option<PyCheckpointOptions>,) -> PyResult<Bound<'py, PyAny>> {+ let options = parse_checkpoint_options(options).map_err(map_err)?;let handle = Arc::clone(&self.handle);pyo3_async_runtimes::tokio::future_into_py(py, async move {Ok(PyCheckpointInfo::from(- handle.create(&source, name).await.map_err(map_err)?,+ handle+ .create_with_options(&source, name, options)+ .await+ .map_err(map_err)?,))})}@@ -99,3 +152,35 @@ impl PyCheckpointHandle {})}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn checkpoint_options_parse_kinds() {+ let parse = |kind: &str| {+ parse_checkpoint_options(Some(PyCheckpointOptions::new(Some(kind.into()))))+ };+ assert_eq!(parse_checkpoint_options(None).unwrap().kind, None);+ assert_eq!(parse("disk").unwrap().kind, Some(CheckpointKind::Disk));+ assert_eq!(parse("full").unwrap().kind, Some(CheckpointKind::Full));+ assert!(matches!(+ parse("unknown"),+ Err(BoxliteError::InvalidArgument(_))+ ));+ }++ #[test]+ fn checkpoint_info_preserves_kind_and_memory_size() {+ let info = serde_json::from_value::<CheckpointInfo>(serde_json::json!({+ "id": "archive", "name": "base", "source_box_id": "source",+ "created_at": "2026-11-06T00:00:00Z", "size_bytes": 4096,+ "kind": "full", "memory_size_bytes": 0+ }))+ .unwrap();+ let info = PyCheckpointInfo::from(info);+ assert_eq!(info.kind, "full");+ assert_eq!(info.memory_size_bytes, Some(0));+ }+}diff --git a/sdks/python/src/lib.rs b/sdks/python/src/lib.rsindex 2a1cdcbee..127dff5e0 100644--- a/sdks/python/src/lib.rs+++ b/sdks/python/src/lib.rs@@ -84,6 +84,7 @@ fn boxlite_python(m: &Bound<'_, PyModule>) -> PyResult<()> {m.add_class::<PyVolumeInfo>()?;m.add_class::<crate::checkpoints::PyCheckpointHandle>()?;m.add_class::<crate::checkpoints::PyCheckpointInfo>()?;+ m.add_class::<crate::checkpoints::PyCheckpointOptions>()?;m.add_class::<PyRegistryHandle>()?;m.add_class::<PyRegistryCredential>()?;m.add_class::<PyBoxInfo>()?;diff --git a/sdks/python/tests/test_checkpoint_handle.py b/sdks/python/tests/test_checkpoint_handle.pyindex 74c5ed7bf..3fc339153 100644--- a/sdks/python/tests/test_checkpoint_handle.py+++ b/sdks/python/tests/test_checkpoint_handle.py@@ -1,5 +1,6 @@"""Exercise checkpoint serialization and result ownership through native REST."""+import asyncioimport importlib.utilimport jsonimport threading@@ -78,7 +79,12 @@ async def test_checkpoint_rejects_mutated_empty_collections(checkpoint_server, f@pytest.fixture-def checkpoint_server():+def checkpoint_settings():+ return {"enabled": True, "memory": {}}+++def checkpoint_server(checkpoint_settings):requests = []class Handler(BaseHTTPRequestHandler):@@ -91,13 +97,22 @@ def checkpoint_server():self.end_headers()returnpayload = INFO- if self.path == "/v1/checkpoints" and self.command == "GET":- payload = {"checkpoints": [INFO]}+ if self.path == "/v1/config":+ payload = {+ "capabilities": {+ "memory_checkpoints_enabled": checkpoint_settings["enabled"]+ }+ }+ elif self.path == "/v1/checkpoints" and self.command == "GET":+ payload = {"checkpoints": [{**INFO, "kind": "future"}]}+ elif self.path == "/v1/checkpoints" and (body or {}).get("kind") == "full":+ payload = {**INFO, "kind": "full", **checkpoint_settings["memory"]}elif self.path.startswith("/v1/boxes"):payload = BOXif self.command == "GET" and self.path == "/v1/checkpoints/checkpoint-1":payload = {**INFO,+ "kind": "future","state": "failed","error_reason": "archive upload failed",}@@ -134,8 +149,10 @@ async def test_checkpoint_native_rest_management_and_box_creation(checkpoint_ser4096,"ready",)- assert (await checkpoints.list())[0].source_box_id == "source-1"+ listed = (await checkpoints.list())[0]+ assert (listed.source_box_id, listed.kind) == ("source-1", "unknown")detail = await checkpoints.get("checkpoint-1")+ assert detail.kind == "unknown"assert (detail.id, detail.state, detail.error_reason) == ("checkpoint-1","failed",@@ -185,3 +202,60 @@ def test_checkpoint_sync_bridge_returns_managed_box_handles(checkpoint_server):assert isinstance(target, boxlite.SyncBox)assert target.id == "target-1"assert requests[1][2] == {"checkpoint_id": "checkpoint-1", "name": "worker"}++[email protected]("sync", [False, True], ids=["async", "sync"])+ "kwargs, enabled, memory, error",+ [+ (None, False, None, None),+ ({}, False, None, None),+ ({"kind": "disk"}, False, None, None),+ ({"kind": "full"}, True, None, None),+ ({"kind": "full"}, True, 0, None),+ ({"kind": "full"}, True, 8192, None),+ ({"kind": "full"}, False, None, "UnsupportedError"),+ ({"kind": "bogus"}, True, None, "InvalidArgumentError"),+ ({"kind": ""}, True, None, "InvalidArgumentError"),+ ],+)+def test_checkpoint_create_options(+ checkpoint_server, checkpoint_settings, sync, kwargs, enabled, memory, error+):+ url, requests = checkpoint_server+ checkpoint_settings["enabled"] = enabled+ if memory is not None:+ checkpoint_settings["memory"]["memory_size_bytes"] = memory+ rest = boxlite.BoxliteRestOptions(url=url)+ options = None if kwargs is None else boxlite.CheckpointOptions(**kwargs)+ full = (kwargs or {}).get("kind") == "full"+ name = "base" if memory == 0 else None++ async def capture_async():+ return await boxlite.Boxlite.rest(rest).checkpoints.create(+ "source-1", name, options=options+ )++ def capture():+ if sync:+ with boxlite.SyncBoxlite.rest(rest) as runtime:+ return runtime.checkpoints.create("source-1", name, options=options)+ return asyncio.run(capture_async())++ expected = [("GET", "/v1/config", None)] if full else []+ if error:+ with pytest.raises(getattr(boxlite, error)):+ capture()+ else:+ info = capture()+ assert (info.kind, info.memory_size_bytes) == (+ "full" if full else "disk",+ memory,+ )+ body = {"source_box_id": "source-1"}+ if full:+ body["kind"] = "full"+ if name is not None:+ body["name"] = name+ expected.append(("POST", "/v1/checkpoints", body))+ assert requests == expecteddiff --git a/src/boxlite/src/lib.rs b/src/boxlite/src/lib.rsindex e69989c13..6871287e4 100644--- a/src/boxlite/src/lib.rs+++ b/src/boxlite/src/lib.rs@@ -44,8 +44,9 @@ pub use litebox::{};pub use portal::GuestSession;pub use runtime::{- AuthHandle, BoxliteRuntime, CheckpointHandle, CheckpointInfo, CheckpointState, Domain,- DomainHandle, DomainList, DomainTarget, ImageHandle, Principal,+ AuthHandle, BoxliteRuntime, CheckpointHandle, CheckpointInfo, CheckpointKind,+ CheckpointOptions, CheckpointState, Domain, DomainHandle, DomainList, DomainTarget,+ ImageHandle, Principal,};pub use boxlite_shared::BoxByteStream;diff --git a/src/boxlite/src/rest/client.rs b/src/boxlite/src/rest/client.rsindex ea67b389e..fa00e85fb 100644--- a/src/boxlite/src/rest/client.rs+++ b/src/boxlite/src/rest/client.rs@@ -836,6 +836,16 @@ impl ApiClient {)}+ pub async fn require_memory_checkpoints_enabled(&self) -> BoxliteResult<()> {+ let config = self.fetch_config().await?;+ ensure_capability(+ "full checkpoint",+ config+ .capabilities+ .and_then(|caps| caps.memory_checkpoints_enabled),+ )+ }+pub async fn require_clone_enabled(&self) -> BoxliteResult<()> {let config = self.get_config().await?;let capabilities = config.capabilities.ok_or_else(|| {diff --git a/src/boxlite/src/rest/runtime.rs b/src/boxlite/src/rest/runtime.rsindex 5968ba2fa..878e3d709 100644--- a/src/boxlite/src/rest/runtime.rs+++ b/src/boxlite/src/rest/runtime.rs@@ -8,7 +8,7 @@ use crate::metrics::RuntimeMetrics;use crate::runtime::advanced_options::SecurityOptions;use crate::runtime::backend::RuntimeBackend;use crate::runtime::options::{BoxArchive, BoxOptions};-use crate::{BoxInfo, LiteBox};+use crate::{BoxInfo, CheckpointKind, CheckpointOptions, LiteBox};use super::client::ApiClient;use super::litebox::RestBox;@@ -45,22 +45,47 @@ impl crate::runtime::checkpoints::CheckpointBackend for RestRuntime {&self,source: &str,name: Option<String>,+ options: CheckpointOptions,) -> BoxliteResult<crate::CheckpointInfo> {+ let kind = match options.kind {+ None | Some(CheckpointKind::Disk) => None,+ Some(CheckpointKind::Full) => {+ self.client.require_memory_checkpoints_enabled().await?;+ Some(CheckpointKind::Full)+ }+ Some(CheckpointKind::Unknown) => {+ return Err(BoxliteError::InvalidArgument(+ "unknown checkpoint kind".into(),+ ));+ }+ };+#[derive(serde::Serialize)]struct Capture<'a> {source_box_id: &'a str,#[serde(skip_serializing_if = "Option::is_none")]name: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ kind: Option<CheckpointKind>,}- self.client+ let info: crate::CheckpointInfo = self+ .client.post("/checkpoints",&Capture {source_box_id: source,name,+ kind,},)- .await+ .await?;+ if kind == Some(CheckpointKind::Full) && info.kind != CheckpointKind::Full {+ return Err(BoxliteError::Unsupported(format!(+ "Remote server returned checkpoint {} without confirming full capture",+ info.id+ )));+ }+ Ok(info)}async fn list(&self) -> BoxliteResult<Vec<crate::CheckpointInfo>> {@@ -1035,6 +1060,280 @@ mod tests {serde_json::from_str(body).unwrap()}+ const CHECKPOINT_RESPONSE: &str = r#"{"id":"disk","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512}"#;+ const FULL_CHECKPOINT_CREATING: &str = r#"{"id":"full","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":0,"state":"creating","kind":"full"}"#;+ const MEMORY_CHECKPOINTS_ENABLED: &str =+ r#"{"capabilities":{"memory_checkpoints_enabled":true}}"#;+ const MEMORY_CHECKPOINTS_DISABLED: &str =+ r#"{"capabilities":{"checkpoints_enabled":true,"memory_checkpoints_enabled":false}}"#;+ const FULL_CHECKPOINT_OPTIONS: CheckpointOptions = CheckpointOptions {+ kind: Some(CheckpointKind::Full),+ };++ #[tokio::test]+ async fn checkpoint_disk_create_uses_legacy_json() {+ use crate::BoxliteRuntime;++ for (name, expected) in [+ (None, serde_json::json!({"source_box_id": "source"})),+ (+ Some("backup".to_owned()),+ serde_json::json!({"source_box_id": "source", "name": "backup"}),+ ),+ ] {+ let (port, server) = exchange_server(vec![(201, CHECKPOINT_RESPONSE); 3]).await;+ let runtime =+ BoxliteRuntime::rest(BoxliteRestOptions::new(format!("http://127.0.0.1:{port}")))+ .unwrap();+ let checkpoints = runtime.checkpoints();+ let default = checkpoints.create("source", name.clone()).await.unwrap();+ let empty_options = checkpoints+ .create_with_options("source", name.clone(), CheckpointOptions::default())+ .await+ .unwrap();+ let explicit_disk = checkpoints+ .create_with_options(+ "source",+ name,+ CheckpointOptions {+ kind: Some(CheckpointKind::Disk),+ },+ )+ .await+ .unwrap();++ for info in [default, empty_options, explicit_disk] {+ assert_eq!(info.kind, CheckpointKind::Disk);+ assert_eq!(info.memory_size_bytes, None);+ }+ let requests = server.await.unwrap();+ assert_eq!(requests.len(), 3);+ for (line, body) in requests {+ assert_eq!(line, "POST /v1/checkpoints HTTP/1.1");+ assert_eq!(json_body(&body), expected);+ }+ }+ }++ #[tokio::test]+ async fn checkpoint_unknown_create_fails_before_transport() {+ use crate::runtime::checkpoints::CheckpointBackend;++ let options = BoxliteRestOptions::new("http://127.0.0.1:1");+ let backend = RestRuntime::new(&options).unwrap();+ let unknown = CheckpointBackend::create(+ &backend,+ "source",+ None,+ CheckpointOptions {+ kind: Some(CheckpointKind::Unknown),+ },+ )+ .await;+ assert!(+ matches!(unknown, Err(BoxliteError::InvalidArgument(_))),+ "{unknown:?}"+ );+ }++ #[tokio::test]+ async fn checkpoint_full_requires_advertised_capability() {+ for config in [+ "{}",+ r#"{"capabilities":{"checkpoints_enabled":true}}"#,+ MEMORY_CHECKPOINTS_DISABLED,+ ] {+ let (port, server) = json_server(vec![config, CHECKPOINT_RESPONSE]).await;+ let runtime = crate::BoxliteRuntime::rest(BoxliteRestOptions::new(format!(+ "http://127.0.0.1:{port}"+ )))+ .unwrap();+ let checkpoints = runtime.checkpoints();+ let result = checkpoints+ .create_with_options("source", None, FULL_CHECKPOINT_OPTIONS)+ .await;+ assert!(+ matches!(result, Err(BoxliteError::Unsupported(_))),+ "{result:?}"+ );++ // A final read keeps the listener open to detect any unexpected request.+ checkpoints.get("disk").await.unwrap();+ assert_eq!(+ server.await.unwrap(),+ [+ "GET /v1/config HTTP/1.1",+ "GET /v1/checkpoints/disk HTTP/1.1"+ ]+ );+ }+ }++ #[tokio::test]+ async fn checkpoint_full_sends_kind_and_accepts_creating_response() {+ for (name, expected_body) in [+ (+ None,+ serde_json::json!({"source_box_id": "source", "kind": "full"}),+ ),+ (+ Some("backup".to_owned()),+ serde_json::json!({"source_box_id": "source", "name": "backup", "kind": "full"}),+ ),+ ] {+ let (port, server) = exchange_server(vec![+ (200, MEMORY_CHECKPOINTS_ENABLED),+ (201, FULL_CHECKPOINT_CREATING),+ ])+ .await;+ let runtime = crate::BoxliteRuntime::rest(BoxliteRestOptions::new(format!(+ "http://127.0.0.1:{port}"+ )))+ .unwrap();+ let info = runtime+ .checkpoints()+ .create_with_options("source", name, FULL_CHECKPOINT_OPTIONS)+ .await+ .unwrap();+ assert_eq!(info.kind, CheckpointKind::Full);+ assert_eq!(info.state, crate::CheckpointState::Creating);+ assert_eq!(info.memory_size_bytes, None);++ let requests = server.await.unwrap();+ assert_eq!(+ requests[0],+ ("GET /v1/config HTTP/1.1".into(), String::new())+ );+ assert_eq!(requests[1].0, "POST /v1/checkpoints HTTP/1.1");+ assert_eq!(json_body(&requests[1].1), expected_body);+ }+ }++ #[tokio::test]+ async fn checkpoint_full_rechecks_capability_for_each_create() {+ let (port, server) = http_server(vec![+ (200, MEMORY_CHECKPOINTS_ENABLED),+ (201, FULL_CHECKPOINT_CREATING),+ (200, MEMORY_CHECKPOINTS_DISABLED),+ (200, CHECKPOINT_RESPONSE),+ ])+ .await;+ let runtime = crate::BoxliteRuntime::rest(BoxliteRestOptions::new(format!(+ "http://127.0.0.1:{port}"+ )))+ .unwrap();+ let checkpoints = runtime.checkpoints();+ checkpoints+ .create_with_options("source", None, FULL_CHECKPOINT_OPTIONS)+ .await+ .unwrap();+ let result = checkpoints+ .create_with_options("source", None, FULL_CHECKPOINT_OPTIONS)+ .await;+ assert!(+ matches!(result, Err(BoxliteError::Unsupported(_))),+ "{result:?}"+ );+ checkpoints.get("disk").await.unwrap();+ assert_eq!(+ server.await.unwrap(),+ [+ "GET /v1/config HTTP/1.1",+ "POST /v1/checkpoints HTTP/1.1",+ "GET /v1/config HTTP/1.1",+ "GET /v1/checkpoints/disk HTTP/1.1",+ ]+ );+ }++ #[tokio::test]+ async fn checkpoint_full_rejects_unconfirmed_kind_without_cleanup_or_retry() {+ const LEGACY: &str = r#"{"id":"legacy-id","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512}"#;+ const DISK: &str = r#"{"id":"disk-id","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"kind":"disk"}"#;+ const FUTURE: &str = r#"{"id":"future-id","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"kind":"future"}"#;+ for (body, id) in [+ (LEGACY, "legacy-id"),+ (DISK, "disk-id"),+ (FUTURE, "future-id"),+ ] {+ let (port, server) = http_server(vec![+ (200, MEMORY_CHECKPOINTS_ENABLED),+ (201, body),+ (200, body),+ ])+ .await;+ let runtime = crate::BoxliteRuntime::rest(BoxliteRestOptions::new(format!(+ "http://127.0.0.1:{port}"+ )))+ .unwrap();+ let checkpoints = runtime.checkpoints();+ let error = checkpoints+ .create_with_options("source", None, FULL_CHECKPOINT_OPTIONS)+ .await+ .unwrap_err();+ assert!(+ matches!(&error, BoxliteError::Unsupported(message) if message.contains(id)),+ "{error:?}"+ );++ assert_eq!(checkpoints.get(id).await.unwrap().id, id);+ assert_eq!(+ server.await.unwrap(),+ [+ "GET /v1/config HTTP/1.1".to_string(),+ "POST /v1/checkpoints HTTP/1.1".to_string(),+ format!("GET /v1/checkpoints/{id} HTTP/1.1"),+ ]+ );+ }+ }++ #[tokio::test]+ async fn checkpoint_get_and_list_decode_archive_metadata() {+ use crate::BoxliteRuntime;++ const FULL: &str = r#"{"id":"full","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"kind":"full","memory_size_bytes":256}"#;+ const DISK: &str = r#"{"id":"disk","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"kind":"disk"}"#;+ const FUTURE: &str = r#"{"id":"future","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"kind":"future_mode"}"#;+ let (port, server) = json_server(vec![FULL, DISK, FUTURE]).await;+ let runtime =+ BoxliteRuntime::rest(BoxliteRestOptions::new(format!("http://127.0.0.1:{port}")))+ .unwrap();+ let checkpoints = runtime.checkpoints();+ let mut expected = Vec::new();+ for (id, kind, size) in [+ ("full", CheckpointKind::Full, Some(256)),+ ("disk", CheckpointKind::Disk, None),+ ("future", CheckpointKind::Unknown, None),+ ] {+ let info = checkpoints.get(id).await.unwrap();+ assert_eq!(info.id, id);+ assert_eq!(info.kind, kind);+ assert_eq!(info.memory_size_bytes, size);+ expected.push(info);+ }+ assert_eq!(+ server.await.unwrap(),+ [+ "GET /v1/checkpoints/full HTTP/1.1",+ "GET /v1/checkpoints/disk HTTP/1.1",+ "GET /v1/checkpoints/future HTTP/1.1",+ ]+ );++ const LIST: &str = r#"{"checkpoints":[+ {"id":"full","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"kind":"full","memory_size_bytes":256},+ {"id":"disk","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"kind":"disk"},+ {"id":"future","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"kind":"future_mode"}+ ]}"#;+ let (port, server) = json_server(vec![LIST]).await;+ let runtime =+ BoxliteRuntime::rest(BoxliteRestOptions::new(format!("http://127.0.0.1:{port}")))+ .unwrap();+ assert_eq!(runtime.checkpoints().list().await.unwrap(), expected);+ assert_eq!(server.await.unwrap(), ["GET /v1/checkpoints HTTP/1.1"]);+ }+#[tokio::test]async fn create_from_a_checkpoint_sends_only_the_checkpoint_and_name() {let (port, server) = exchange_server(vec![(201, BOX_RESPONSE)]).await;diff --git a/src/boxlite/src/rest/types.rs b/src/boxlite/src/rest/types.rsindex e6d4f2eae..ace17ee1d 100644--- a/src/boxlite/src/rest/types.rs+++ b/src/boxlite/src/rest/types.rs@@ -100,6 +100,8 @@ pub(crate) struct ServerCapabilities {pub privileged_enabled: Option<bool>,pub linux_capabilities_enabled: Option<bool>,pub snapshots_enabled: Option<bool>,+ pub checkpoints_enabled: Option<bool>,+ pub memory_checkpoints_enabled: Option<bool>,pub clone_enabled: Option<bool>,pub export_enabled: Option<bool>,pub import_enabled: Option<bool>,diff --git a/src/boxlite/src/runtime/checkpoints.rs b/src/boxlite/src/runtime/checkpoints.rsindex 3217c4002..c100f0efb 100644--- a/src/boxlite/src/runtime/checkpoints.rs+++ b/src/boxlite/src/runtime/checkpoints.rs@@ -1,13 +1,56 @@-//! Managed disk archives, independent of the source box and its snapshots.+//! Managed checkpoint archives, independent of the source box and its snapshots.use async_trait::async_trait;use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};+use std::fmt;use std::sync::Arc;use crate::{BoxliteError, BoxliteResult};-/// Metadata for a checkpoint whose complete archive has been published.+/// Contents of a checkpoint archive.+#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum CheckpointKind {+ /// Disk data only.+ #[default]+ Disk,+ /// Disk data, guest memory, and VM state.+ Full,+ /// An unrecognized kind reported by the server.+ #[serde(other)]+ Unknown,+}++impl CheckpointKind {+ pub fn is_disk(&self) -> bool {+ *self == Self::Disk+ }++ pub fn as_str(&self) -> &'static str {+ match self {+ Self::Disk => "disk",+ Self::Full => "full",+ Self::Unknown => "unknown",+ }+ }+}++impl fmt::Display for CheckpointKind {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.write_str(self.as_str())+ }+}++/// Options for checkpoint creation.+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]+pub struct CheckpointOptions {+ /// Requested archive kind. `None` selects a disk checkpoint.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub kind: Option<CheckpointKind>,+}++/// Metadata for a managed checkpoint and its archive state.#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]pub struct CheckpointInfo {pub id: String,@@ -19,6 +62,11 @@ pub struct CheckpointInfo {pub state: CheckpointState,#[serde(default, skip_serializing_if = "Option::is_none")]pub error_reason: Option<String>,+ #[serde(default, skip_serializing_if = "CheckpointKind::is_disk")]+ pub kind: CheckpointKind,+ /// Archived guest memory size in bytes, when available.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub memory_size_bytes: Option<u64>,}/// Ready means the entire archive is available, including upload on REST.@@ -38,13 +86,18 @@ pub enum CheckpointState {)]#[async_trait]pub(crate) trait CheckpointBackend: Send + Sync {- async fn create(&self, source: &str, name: Option<String>) -> BoxliteResult<CheckpointInfo>;+ async fn create(+ &self,+ source: &str,+ name: Option<String>,+ options: CheckpointOptions,+ ) -> BoxliteResult<CheckpointInfo>;async fn list(&self) -> BoxliteResult<Vec<CheckpointInfo>>;async fn get(&self, key: &str) -> BoxliteResult<CheckpointInfo>;async fn remove(&self, key: &str, force: bool) -> BoxliteResult<()>;}-/// Checkpoint management through a REST server; local runtimes return Unsupported.+/// Checkpoint management through a REST server. Local runtimes return `Unsupported`.////// Using a checkpoint is a box operation: create a box from one with/// `RootfsSpec::Checkpoint`.@@ -53,8 +106,8 @@ pub struct CheckpointHandle {backend: Option<Arc<dyn CheckpointBackend>>,}-impl std::fmt::Debug for CheckpointHandle {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+impl fmt::Debug for CheckpointHandle {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {f.debug_struct("CheckpointHandle").finish_non_exhaustive()}}@@ -64,11 +117,26 @@ impl CheckpointHandle {Self { backend }}- /// Ask the REST server to capture a stopped source box.+ /// Create a disk checkpoint of a stopped source box.pub async fn create(&self,source: &str,name: Option<String>,+ ) -> BoxliteResult<CheckpointInfo> {+ self.create_with_options(source, name, CheckpointOptions::default())+ .await+ }++ /// Create a checkpoint with the requested options.+ ///+ /// REST sends the legacy request without `kind` for disk capture. For full+ /// capture, it checks the server's live capability before posting and+ /// requires the response to confirm `kind: full`.+ pub async fn create_with_options(+ &self,+ source: &str,+ name: Option<String>,+ options: CheckpointOptions,) -> BoxliteResult<CheckpointInfo> {if source.is_empty() || source.contains('\0') {return Err(BoxliteError::InvalidArgument(@@ -78,7 +146,12 @@ impl CheckpointHandle {if let Some(name) = &name {checked_name(name)?;}- self.backend()?.create(source, name).await+ if options.kind == Some(CheckpointKind::Unknown) {+ return Err(BoxliteError::InvalidArgument(+ "unknown checkpoint kind".into(),+ ));+ }+ self.backend()?.create(source, name, options).await}pub async fn list(&self) -> BoxliteResult<Vec<CheckpointInfo>> {diff --git a/src/boxlite/src/runtime/checkpoints/tests.rs b/src/boxlite/src/runtime/checkpoints/tests.rsindex 4489757dc..fd3aec7f9 100644--- a/src/boxlite/src/runtime/checkpoints/tests.rs+++ b/src/boxlite/src/runtime/checkpoints/tests.rs@@ -1,5 +1,7 @@use super::*;+const LEGACY_CHECKPOINT: &str = r#"{"id":"checkpoint","name":"backup","source_box_id":"source","created_at":"2026-01-01T00:00:00Z","size_bytes":512,"state":"ready"}"#;+#[tokio::test]async fn invalid_checkpoint_arguments_are_rejected_before_backend_dispatch() {// A valid request would reach this absent backend and return Unsupported.@@ -33,3 +35,72 @@ async fn invalid_checkpoint_arguments_are_rejected_before_backend_dispatch() {));}}++#[tokio::test]+async fn create_with_options_validates_arguments_before_backend_dispatch() {+ let checkpoints = CheckpointHandle::new(None);+ for (source, name, kind) in [+ ("", None, None),+ ("source\0suffix", None, Some(CheckpointKind::Disk)),+ ("source", Some("bad/name"), Some(CheckpointKind::Full)),+ ("source", None, Some(CheckpointKind::Unknown)),+ ] {+ assert!(matches!(+ checkpoints+ .create_with_options(source, name.map(str::to_owned), CheckpointOptions { kind })+ .await,+ Err(BoxliteError::InvalidArgument(_))+ ));+ }+}++#[tokio::test]+async fn create_with_options_reports_unsupported_on_local_runtime() {+ let home = tempfile::tempdir_in("/tmp").unwrap();+ let runtime = crate::BoxliteRuntime::new_for_test(crate::BoxliteOptions {+ home_dir: home.path().to_path_buf(),+ image_registries: vec![],+ ..Default::default()+ })+ .unwrap();+ let checkpoints = runtime.checkpoints();+ for kind in [None, Some(CheckpointKind::Disk), Some(CheckpointKind::Full)] {+ let error = checkpoints+ .create_with_options("source", Some("backup".into()), CheckpointOptions { kind })+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ BoxliteError::Unsupported(message) if message == UNSUPPORTED_ON_LOCAL+ ));+ }+}++#[test]+fn checkpoint_info_preserves_legacy_json_shape() {+ let legacy = serde_json::from_str::<serde_json::Value>(LEGACY_CHECKPOINT).unwrap();+ let info: CheckpointInfo = serde_json::from_str(LEGACY_CHECKPOINT).unwrap();+ assert_eq!(info.kind, CheckpointKind::Disk);+ assert_eq!(info.memory_size_bytes, None);+ assert_eq!(serde_json::to_value(&info).unwrap(), legacy);+}++#[test]+fn checkpoint_info_round_trips_full_kind_and_zero_memory_size() {+ let mut full: serde_json::Value = serde_json::from_str(LEGACY_CHECKPOINT).unwrap();+ full["kind"] = serde_json::json!("full");+ full["memory_size_bytes"] = serde_json::json!(0);+ let info: CheckpointInfo = serde_json::from_value(full.clone()).unwrap();+ assert_eq!(info.kind, CheckpointKind::Full);+ assert_eq!(info.memory_size_bytes, Some(0));+ assert_eq!(serde_json::to_value(&info).unwrap(), full);+}++#[test]+fn checkpoint_info_accepts_future_kinds() {+ let mut future: serde_json::Value = serde_json::from_str(LEGACY_CHECKPOINT).unwrap();+ future["kind"] = serde_json::json!("future_mode");+ let info: CheckpointInfo = serde_json::from_value(future).unwrap();+ assert_eq!(info.kind, CheckpointKind::Unknown);+ assert_eq!(info.memory_size_bytes, None);+}diff --git a/src/boxlite/src/runtime/mod.rs b/src/boxlite/src/runtime/mod.rsindex 981ea3830..db7543246 100644--- a/src/boxlite/src/runtime/mod.rs+++ b/src/boxlite/src/runtime/mod.rs@@ -22,7 +22,9 @@ mod import;pub(crate) mod rt_impl;pub use auth::{AuthHandle, Principal};-pub use checkpoints::{CheckpointHandle, CheckpointInfo, CheckpointState};+pub use checkpoints::{+ CheckpointHandle, CheckpointInfo, CheckpointKind, CheckpointOptions, CheckpointState,+};pub use core::BoxliteRuntime;pub use domains::{Domain, DomainHandle, DomainList, DomainTarget};pub use images::ImageHandle;diff --git a/src/cli/README.md b/src/cli/README.mdindex 60bee42c9..7b741bf83 100644--- a/src/cli/README.md+++ b/src/cli/README.md@@ -165,9 +165,13 @@ Explicit defaults such as `--auto-delete 0` and `--network enabled` also reject;global connection options remain available.Checkpoints are managed by the selected REST server. Local runtimes return-an unsupported-operation error. Each checkpoint captures a stopped box's disk-and execution configuration, survives source deletion, and can create multiple-boxes. It does not capture memory or running processes.+an unsupported-operation error. Checkpoints capture disk and execution+configuration, survive source deletion, and can create multiple boxes.++`checkpoint create --kind <disk|full>` selects the capture type. `disk` is the+default and requires a stopped, idle box. `full` also captures guest memory and+VM state and requires a running box. Before requesting a full capture, the CLI+checks that `GET /v1/config` reports `memory_checkpoints_enabled: true`.```bash# Use a REST context, or pass --url with the selected server.@@ -193,9 +197,9 @@ replace an existing box from a checkpoint; remove the box and create a new one.Storage and capture coordination belong to the server.The SDK's `CheckpointHandle` only validates inputs and sends REST requests.-The separate `import ARCHIVE` command keeps the native archive workflow unchanged.-Local `serve` reports `checkpoints_enabled: false` and exposes no checkpoint-management routes. Existing binary archive export/import remains available.+Local `serve` reports `checkpoints_enabled: false` and+`memory_checkpoints_enabled: false` and exposes no checkpoint management routes.+Use `import ARCHIVE` to import a binary archive.The cloud runner verifies the downloaded artifact SHA before ordinary nativeimport, which owns archive validation; this creates no localcheckpoint catalog or recovery records.diff --git a/src/cli/src/cli.rs b/src/cli/src/cli.rsindex e5b10b663..4d6c6f92b 100644--- a/src/cli/src/cli.rs+++ b/src/cli/src/cli.rs@@ -782,7 +782,7 @@ pub enum Commands {Signal(crate::commands::signal::SignalArgs),/// Create a new boxCreate(crate::commands::create::CreateArgs),- /// Manage disk checkpoints on the selected REST server.+ /// Manage checkpoints on the selected REST server.Checkpoint(crate::commands::checkpoint::CheckpointArgs),/// Import a .boxlite archive into a new box.Import(crate::commands::import::ImportArgs),diff --git a/src/cli/src/commands/checkpoint.rs b/src/cli/src/commands/checkpoint.rsindex 52b679b47..2fb0dea92 100644--- a/src/cli/src/commands/checkpoint.rs+++ b/src/cli/src/commands/checkpoint.rs@@ -3,7 +3,7 @@use std::io::Write;use anyhow::{Result, bail};-use boxlite::{BoxliteRuntime, CheckpointInfo};+use boxlite::{BoxliteRuntime, CheckpointInfo, CheckpointKind, CheckpointOptions, CheckpointState};use clap::{Args, Subcommand};use tabled::Tabled;@@ -18,7 +18,7 @@ pub struct CheckpointArgs {#[derive(Subcommand, Debug)]pub enum CheckpointCommand {- /// Capture a box's disk and execution configuration.+ /// Capture a box's disk (or disk and memory) and execution configuration.Create(CaptureArgs),/// List checkpoints independently of source boxes.#[command(visible_alias = "ls")]@@ -31,11 +31,28 @@ pub enum CheckpointCommand {Delete(DeleteArgs),}+#[derive(Clone, Copy, Debug, clap::ValueEnum)]+pub enum CheckpointKindArg {+ Disk,+ Full,+}++impl From<CheckpointKindArg> for CheckpointKind {+ fn from(kind: CheckpointKindArg) -> Self {+ match kind {+ CheckpointKindArg::Disk => Self::Disk,+ CheckpointKindArg::Full => Self::Full,+ }+ }+}+#[derive(Args, Debug)]pub struct CaptureArgs {pub source: String,#[arg(long)]pub name: Option<String>,+ #[arg(long, value_enum)]+ pub kind: Option<CheckpointKindArg>,}#[derive(Args, Debug)]@@ -76,7 +93,12 @@ pub async fn execute(args: CheckpointArgs, global: &GlobalFlags) -> Result<()> {let checkpoints = rt.checkpoints();match args.command {CheckpointCommand::Create(args) => {- let info = checkpoints.create(&args.source, args.name).await?;+ let options = CheckpointOptions {+ kind: args.kind.map(Into::into),+ };+ let info = checkpoints+ .create_with_options(&args.source, args.name, options)+ .await?;println!("{}", info.id);}CheckpointCommand::List(args) => {@@ -87,11 +109,12 @@ pub async fn execute(args: CheckpointArgs, global: &GlobalFlags) -> Result<()> {println!("{}", info.id);}} else {+ let output: Vec<_> = infos.iter().map(CheckpointJson::from).collect();formatter::print_output(&mut std::io::stdout().lock(),- &infos,+ &output,format,- |writer, infos| table(writer, infos),+ |writer, _| table(writer, &infos),)?;}}@@ -100,9 +123,9 @@ pub async fn execute(args: CheckpointArgs, global: &GlobalFlags) -> Result<()> {let info = checkpoints.get(&args.checkpoint).await?;formatter::print_output(&mut std::io::stdout().lock(),- &info,+ &CheckpointJson::from(&info),format,- |writer, info| table(writer, std::slice::from_ref(info)),+ |writer, _| table(writer, std::slice::from_ref(&info)),)?;}CheckpointCommand::Delete(args) => {@@ -115,6 +138,37 @@ pub async fn execute(args: CheckpointArgs, global: &GlobalFlags) -> Result<()> {Ok(())}+#[derive(serde::Serialize)]+struct CheckpointJson<'a> {+ id: &'a str,+ name: &'a str,+ source_box_id: &'a str,+ created_at: &'a chrono::DateTime<chrono::Utc>,+ size_bytes: u64,+ state: &'a CheckpointState,+ #[serde(skip_serializing_if = "Option::is_none")]+ error_reason: Option<&'a str>,+ kind: &'a str,+ #[serde(skip_serializing_if = "Option::is_none")]+ memory_size_bytes: Option<u64>,+}++impl<'a> From<&'a CheckpointInfo> for CheckpointJson<'a> {+ fn from(info: &'a CheckpointInfo) -> Self {+ Self {+ id: &info.id,+ name: &info.name,+ source_box_id: &info.source_box_id,+ created_at: &info.created_at,+ size_bytes: info.size_bytes,+ state: &info.state,+ error_reason: info.error_reason.as_deref(),+ kind: info.kind.as_str(),+ memory_size_bytes: info.memory_size_bytes,+ }+ }+}+#[derive(Tabled)]struct Row {#[tabled(rename = "ID")]@@ -123,6 +177,8 @@ struct Row {name: String,#[tabled(rename = "SOURCE")]source: String,+ #[tabled(rename = "KIND")]+ kind: String,#[tabled(rename = "STATE")]state: String,#[tabled(rename = "SIZE")]@@ -138,6 +194,7 @@ fn table(writer: &mut dyn Write, infos: &[CheckpointInfo]) -> Result<()> {id: info.id.clone(),name: info.name.clone(),source: info.source_box_id.clone(),+ kind: info.kind.as_str().to_string(),state: format!("{:?}", info.state).to_lowercase(),size: crate::commands::volume::ls::format_size(Some(info.size_bytes)),created: formatter::format_time(&info.created_at),diff --git a/src/cli/src/commands/serve/handlers/config.rs b/src/cli/src/commands/serve/handlers/config.rsindex 095197413..1a3307327 100644--- a/src/cli/src/commands/serve/handlers/config.rs+++ b/src/cli/src/commands/serve/handlers/config.rs@@ -8,6 +8,7 @@ pub(in crate::commands::serve) async fn get_config() -> Json<ServerConfig> {Json(ServerConfig {capabilities: ServerCapabilities {checkpoints_enabled: false,+ memory_checkpoints_enabled: false,linux_capabilities_enabled: true,privileged_enabled: true,snapshots_enabled: true,@@ -35,6 +36,7 @@ mod tests {#[tokio::test]async fn config_does_not_advertise_local_checkpoints() {assert!(!get_config().await.0.capabilities.checkpoints_enabled);+ assert!(!get_config().await.0.capabilities.memory_checkpoints_enabled);}#[tokio::test]diff --git a/src/cli/src/commands/serve/types.rs b/src/cli/src/commands/serve/types.rsindex 6ca2f38b6..6af9b35b8 100644--- a/src/cli/src/commands/serve/types.rs+++ b/src/cli/src/commands/serve/types.rs@@ -391,6 +391,7 @@ pub(super) struct ServerConfig {#[derive(Serialize)]pub(super) struct ServerCapabilities {pub checkpoints_enabled: bool,+ pub memory_checkpoints_enabled: bool,pub linux_capabilities_enabled: bool,pub privileged_enabled: bool,pub snapshots_enabled: bool,diff --git a/src/cli/tests/checkpoint.rs b/src/cli/tests/checkpoint.rsindex 2f0a8b3a2..2df5d327e 100644--- a/src/cli/tests/checkpoint.rs+++ b/src/cli/tests/checkpoint.rs@@ -143,11 +143,14 @@ async fn checkpoint_create_list_get_delete_use_the_tenant_and_expected_request_s}}).await;- cli(&home, &server)- .args(["checkpoint", "create", "source-box", "--name", "base"])- .assert()- .success()- .stdout("checkpoint-1\n");+ for kind in [None, Some("disk")] {+ let mut command = cli(&home, &server);+ command.args(["checkpoint", "create", "source", "--name", "base"]);+ if let Some(kind) = kind {+ command.args(["--kind", kind]);+ }+ command.assert().success().stdout("checkpoint-1\n");+ }cli(&home, &server).args(["checkpoint", "list", "--format", "json"]).assert()@@ -164,20 +167,75 @@ async fn checkpoint_create_list_get_delete_use_the_tenant_and_expected_request_s.success().stdout("checkpoint-1\n");let requests = server.requests.lock().unwrap();- assert_eq!(requests.len(), 4);+ assert_eq!(requests.len(), 5);assert!(requests.iter().all(|request| request.bearer == "Bearer cp-key"));- assert_eq!(requests[0].path, "/v1/tenant/checkpoints");- assert_eq!(- requests[0].body,- json!({"source_box_id":"source-box","name":"base"})- );- assert_eq!(requests[1].path, "/v1/tenant/checkpoints");- assert_eq!(requests[2].path, "/v1/tenant/checkpoints/checkpoint-1");- assert_eq!(requests[3].method, "DELETE");+ for request in &requests[..2] {+ assert_eq!(request.method, "POST");+ assert_eq!(request.path, "/v1/tenant/checkpoints");+ assert_eq!(+ request.body,+ json!({"source_box_id":"source","name":"base"})+ );+ }+ assert_eq!(requests[2].path, "/v1/tenant/checkpoints");+ assert_eq!(requests[3].path, "/v1/tenant/checkpoints/checkpoint-1");+ assert_eq!(requests[4].method, "DELETE");+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn full_checkpoint_creation_checks_server_capability_before_posting() {+ let home = TempDir::new().unwrap();+ for enabled in [true, false] {+ let server = Server::start(move |request| {+ if request.path == "/v1/config" {+ return (+ StatusCode::OK,+ json!({"capabilities":{"memory_checkpoints_enabled":enabled}}),+ );+ }+ let mut checkpoint = info("checkpoint-1");+ checkpoint["kind"] = json!("full");+ (StatusCode::CREATED, checkpoint)+ })+ .await;+ let result = cli(&home, &server)+ .args(["checkpoint", "create", "source", "--kind", "full"])+ .assert();+ let requests = server.requests.lock().unwrap();+ if enabled {+ result.success().stdout("checkpoint-1\n");+ assert_eq!(requests.len(), 2);+ assert_eq!(requests[1].method, "POST");+ assert_eq!(requests[1].path, "/v1/tenant/checkpoints");+ assert_eq!(+ requests[1].body,+ json!({"source_box_id":"source","kind":"full"})+ );+ } else {+ result+ .failure()+ .stderr(contains("does not support full checkpoint"));+ assert_eq!(requests.len(), 1);+ }+ assert_eq!(requests[0].method, "GET");+ assert_eq!(requests[0].path, "/v1/config");+ }+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn checkpoint_create_rejects_an_invalid_kind_before_http() {+ let home = TempDir::new().unwrap();+ let server = Server::start(|_| (StatusCode::CREATED, info("checkpoint-1"))).await;+ cli(&home, &server)+ .args(["checkpoint", "create", "source", "--kind", "bogus"])+ .assert()+ .failure()+ .stderr(contains("invalid value 'bogus' for '--kind <KIND>'"));+ assert!(server.requests.lock().unwrap().is_empty());}#[tokio::test(flavor = "multi_thread", worker_threads = 2)]@@ -199,32 +257,87 @@ async fn create_from_a_checkpoint_sends_only_the_checkpoint_and_name() {}#[tokio::test(flavor = "multi_thread", worker_threads = 2)]-async fn checkpoint_list_and_get_render_captured_metadata_as_tables() {+async fn checkpoint_list_and_get_render_kind_and_memory_metadata() {let home = TempDir::new().unwrap();- let server = Server::start(|request| {+ let mut full = info("checkpoint-2");+ full["kind"] = json!("full");+ full["memory_size_bytes"] = json!(8192);+ let mut zero = full.clone();+ zero["id"] = json!("checkpoint-3");+ zero["memory_size_bytes"] = json!(0);+ let mut future = info("checkpoint-4");+ future["kind"] = json!("future");+ let mut expected = [info("checkpoint-1"), full, zero, future];+ let responses = expected.clone();+ let server = Server::start(move |request| {let body = if request.path.ends_with("/checkpoints") {- json!({"checkpoints":[info("checkpoint-1")]})+ json!({"checkpoints": responses})} else {- info("checkpoint-1")+ let id = request.path.rsplit('/').next().unwrap();+ responses+ .iter()+ .find(|info| info["id"] == id)+ .unwrap()+ .clone()};(StatusCode::OK, body)}).await;- for arguments in [- vec!["checkpoint", "list"],- vec!["checkpoint", "get", "checkpoint-1", "--format", "table"],- ] {+ cli(&home, &server)+ .args(["checkpoint", "list"])+ .assert()+ .success()+ .stdout(contains("KIND"))+ .stdout(contains(" disk "))+ .stdout(contains(" full "))+ .stdout(contains(" unknown "));+ expected[0]["kind"] = json!("disk");+ expected[3]["kind"] = json!("unknown");+ for format in ["json", "yaml"] {+ let list = cli(&home, &server)+ .args(["checkpoint", "list", "--format", format])+ .assert()+ .success();+ let stdout = &list.get_output().stdout;+ let actual: Value = if format == "json" {+ serde_json::from_slice(stdout).unwrap()+ } else {+ serde_yaml::from_slice(stdout).unwrap()+ };+ assert_eq!(actual, json!(expected), "list --format {format}");+ }+ for checkpoint in expected {+ let id = checkpoint["id"].as_str().unwrap();+ let kind = checkpoint["kind"].as_str().unwrap();cli(&home, &server)- .args(arguments)+ .args(["checkpoint", "get", id, "--format", "table"]).assert().success().stdout(contains("ID")).stdout(contains("SOURCE"))- .stdout(contains("checkpoint-1"))+ .stdout(contains("KIND"))+ .stdout(contains(format!(" {kind} ")))+ .stdout(contains(id)).stdout(contains("source-box")).stdout(contains("ready"));+ let get = cli(&home, &server)+ .args(["checkpoint", "get", id])+ .assert()+ .success();+ assert_eq!(+ serde_json::from_slice::<Value>(&get.get_output().stdout).unwrap(),+ checkpoint+ );+ let get = cli(&home, &server)+ .args(["checkpoint", "get", id, "--format", "yaml"])+ .assert()+ .success();+ assert_eq!(+ serde_yaml::from_slice::<Value>(&get.get_output().stdout).unwrap(),+ checkpoint,+ "get {id} --format yaml"+ );}- assert_eq!(server.requests.lock().unwrap().len(), 2);}#[tokio::test(flavor = "multi_thread", worker_threads = 2)]