Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(api): add full checkpoint persistence, capability flag, admission, and restore routing (#3107)

lfld287af3ed9fd4bb0
diff --git a/apps/api/README.md b/apps/api/README.md
index efa0caf73..87e2682df 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -358,30 +358,38 @@ Coverage runs bypass the cache.
`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"`.
+
+- `disk` requires an idle, `stopped` source Box. Stop the Box and wait for `stopped`
+ before capture.
+- `full` returns `400 Bad Request` with `code: "unsupported"` when checkpoints are
+ disabled, `MEMORY_CHECKPOINTS_ENABLED=true` is not set, or the source runner
+ lacks `memory_checkpoint`. When enabled, full capture requires an idle, running
+ (`started`) Box on a runner with `memory_checkpoint`. Its responses include
+ `kind: "full"` and omit `memory_size_bytes` while `creating`. Once `ready`, they
+ report the known memory size, including `0`.
+
+`GET /api/v1/config` reports `capabilities.memory_checkpoints_enabled: false` when
+full capture is disabled and `true` when it is enabled.
`GET /api/v1/checkpoints` and `GET /api/v1/checkpoints/{id-or-name}` read the
-organization's records. Create, list and detail responses include `kind: "disk"`.
-List and detail responses omit stored environment values and internal object locations.
+organization's records. Create, list and detail responses include the checkpoint's
+`kind`. Disk checkpoints omit `memory_size_bytes`. 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. 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 slot
-until native export completes. The completion transaction clears its checkpoint
-ownership marker and creates an `UPLOAD_CHECKPOINT` job under `CHECKPOINT`;
-the source can then start while upload runs. Only a matching successful upload
-makes the checkpoint `ready`. Runner failures or invalid archive metadata make
-it `failed`; they do not recreate or destroy the source.
+Both kinds require a source on a ready v2 runner, without volumes or secrets.
+A source state mismatch returns HTTP 409 with `code: "invalid_state"`.
+Checkpoint capture does not automatically stop the source. Creating a checkpoint
+holds the source's `BOX` job slot until native export completes. The completion
+transaction clears its checkpoint ownership marker and creates an
+`UPLOAD_CHECKPOINT` job under `CHECKPOINT`, so upload does not hold the source's
+job slot. Only a matching successful upload makes the checkpoint `ready`. Runner
+failures or invalid archive metadata make it `failed`; they do not recreate or
+destroy the source.
The checkpoint persists its captured execution settings and immutable archive
identity. It has no source Box foreign key: deleting the source after export
@@ -495,7 +503,8 @@ deleting records all count. Quota and name checks run in the transaction that
creates the export job. An unset prefix returns 503 before source mutation.
Apply the checkpoint pre-deploy migration before API instances that map its
-archive, operation and coordination tables. Enable capture after compatible runners are
+archive, operation and coordination tables, and before enabling
+`MEMORY_CHECKPOINTS_ENABLED=true`. Enable capture after compatible runners are
available. Rollback refuses while checkpoints or incomplete checkpoint jobs
remain; it retains the additive, unused PostgreSQL job-resource enum value.
diff --git a/apps/api/src/box/dto/job-type-map.dto.ts b/apps/api/src/box/dto/job-type-map.dto.ts
index 15df972d2..d69ce746b 100644
--- a/apps/api/src/box/dto/job-type-map.dto.ts
+++ b/apps/api/src/box/dto/job-type-map.dto.ts
@@ -6,6 +6,7 @@
import { JobType } from '../enums/job-type.enum'
import { ResourceType } from '../enums/resource-type.enum'
+import { CheckpointArchive, CheckpointKind } from '../entities/checkpoint.entity'
/**
* Type-safe mapping between JobType and its corresponding ResourceType(s) + Payload
@@ -21,12 +22,26 @@ import { ResourceType } from '../enums/resource-type.enum'
export interface JobTypeMap {
[JobType.EXPORT_CHECKPOINT]: {
resourceType: [ResourceType.BOX]
+ payload?: {
+ checkpointId: string
+ arcPath: string
+ kind?: CheckpointKind
+ }
}
[JobType.UPLOAD_CHECKPOINT]: {
resourceType: [ResourceType.CHECKPOINT]
}
[JobType.IMPORT_CHECKPOINT]: {
resourceType: [ResourceType.BOX]
+ payload?: {
+ operationId: string
+ targetSequence: number
+ targetBoxId: string
+ mode: string
+ archive: CheckpointArchive | null
+ kind?: CheckpointKind
+ platformEnv: Record<string, string>
+ }
}
[JobType.CREATE_BOX]: {
resourceType: [ResourceType.BOX]
diff --git a/apps/api/src/box/entities/checkpoint.entity.ts b/apps/api/src/box/entities/checkpoint.entity.ts
index 4a84daa3a..dd59fd47b 100644
--- a/apps/api/src/box/entities/checkpoint.entity.ts
+++ b/apps/api/src/box/entities/checkpoint.entity.ts
@@ -5,6 +5,7 @@ import { Check, Column, CreateDateColumn, Entity, Index, PrimaryColumn, UpdateDa
import { Box } from './box.entity'
import { BoxState } from '../enums/box-state.enum'
+export type CheckpointKind = 'disk' | 'full'
export type CheckpointState = 'creating' | 'ready' | 'failed' | 'deleting'
export type CheckpointEnvironment = Pick<
Box,
@@ -42,10 +43,14 @@ export interface CheckpointArchive {
sizeBytes: number
sha256: string
pinnedImage: string
+ kind?: CheckpointKind
+ memorySizeBytes?: number
}
@Entity('checkpoint')
@Check('checkpoint_state_check', `"state" IN ('creating','ready','failed','deleting')`)
+@Check('checkpoint_kind_check', `"kind" IN ('disk','full')`)
+@Check('checkpoint_memory_size_bytes_check', `"memorySizeBytes" IS NULL OR "memorySizeBytes" >= 0`)
@Index('checkpoint_org_name_key', ['organizationId', 'name'], { unique: true })
@Index('checkpoint_active_job_key', ['activeJobId'], { unique: true, where: '"activeJobId" IS NOT NULL' })
export class Checkpoint {
@@ -57,6 +62,13 @@ export class Checkpoint {
@Column('uuid') sourceRunnerId: string
@Column('varchar') sourceState: BoxState
@Column({ type: 'varchar', default: 'creating' }) state: CheckpointState
+ @Column({ type: 'varchar', default: 'disk' }) kind: CheckpointKind
+ @Column({
+ type: 'bigint',
+ nullable: true,
+ transformer: { to: (v: number | null) => v, from: (v: string | null) => (v === null ? null : Number(v)) },
+ })
+ memorySizeBytes: number | null
@Column() arcPath: string
@Column({ type: 'uuid', nullable: true }) exportJobId: string | null
@Column({ type: 'uuid', nullable: true }) activeJobId: string | null
diff --git a/apps/api/src/box/services/box-state-waiter.service.spec.ts b/apps/api/src/box/services/box-state-waiter.service.spec.ts
index 4abb31c74..815bf9129 100644
--- a/apps/api/src/box/services/box-state-waiter.service.spec.ts
+++ b/apps/api/src/box/services/box-state-waiter.service.spec.ts
@@ -42,8 +42,8 @@ describe('BoxStateWaiterService', () => {
})
it('returns the failed Box identity and a stable error code', async () => {
- const { waiter } = makeWaiter(BoxState.ERROR)
- ;(waiter as any).boxService.findOneByIdOrName.mockResolvedValue({
+ const { waiter, boxService } = makeWaiter(BoxState.ERROR)
+ boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-1',
state: BoxState.ERROR,
errorReason: 'runner has not declared filestore',
@@ -103,6 +103,22 @@ describe('BoxStateWaiterService', () => {
expect(notify.mock.calls[0][0]).toEqual({ lastActivityAt: 'enriched' })
})
+ it('waits through checkpoint import and the stopped state until the Box starts', async () => {
+ const { waiter, subscriber, boxService } = makeWaiter(BoxState.RESTORING)
+ const started = jest.fn()
+ const pending = waiter.waitForStarted('box-1', 'org-1', 5).then(started)
+ await new Promise((resolve) => setImmediate(resolve))
+
+ const emit = (state: BoxState) =>
+ subscriber.emit('message', BOX_EVENT_CHANNEL, JSON.stringify({ box: { id: 'box-1', state } }))
+ emit(BoxState.STOPPED)
+ await new Promise((resolve) => setImmediate(resolve))
+ expect(boxService.toBoxDto).not.toHaveBeenCalled()
+ emit(BoxState.STARTED)
+ await pending
+ expect(started).toHaveBeenCalledWith({ id: 'box-1', state: BoxState.STARTED })
+ })
+
it('rejects instead of returning a non-target state on timeout', async () => {
jest.useFakeTimers()
const { waiter } = makeWaiter()
diff --git a/apps/api/src/box/services/checkpoint-job-receiver.service.ts b/apps/api/src/box/services/checkpoint-job-receiver.service.ts
index c2f5bfafd..589d5e0f0 100644
--- a/apps/api/src/box/services/checkpoint-job-receiver.service.ts
+++ b/apps/api/src/box/services/checkpoint-job-receiver.service.ts
@@ -92,7 +92,9 @@ export class CheckpointJobReceiver {
checkpoint.archive &&
archive.sizeBytes === checkpoint.archive.sizeBytes &&
archive.sha256 === checkpoint.archive.sha256 &&
- archive.pinnedImage === checkpoint.archive.pinnedImage
+ archive.pinnedImage === checkpoint.archive.pinnedImage &&
+ archive.kind === (checkpoint.archive.kind ?? 'disk') &&
+ archive.memorySizeBytes === checkpoint.archive.memorySizeBytes
if (job.status === JobStatus.FAILED || !archive || (!exporting && !unchangedArchive)) {
checkpoint.state = 'failed'
checkpoint.activeJobId = null
@@ -105,6 +107,7 @@ export class CheckpointJobReceiver {
}
if (exporting) {
checkpoint.archive = archive
+ checkpoint.memorySizeBytes = archive.memorySizeBytes ?? null
const upload = new Job({
type: JobType.UPLOAD_CHECKPOINT,
runnerId: checkpoint.sourceRunnerId,
@@ -282,6 +285,9 @@ export class CheckpointJobReceiver {
}
function validateArchive(value: Record<string, unknown> | null, checkpoint: Checkpoint): CheckpointArchive | null {
+ const kind = checkpoint.kind ?? 'disk'
+ const reportedKind = value?.kind === undefined ? 'disk' : value.kind
+ const memorySizeBytes = value?.memorySizeBytes
if (
!checkpoint.exportJobId ||
!value ||
@@ -289,6 +295,10 @@ function validateArchive(value: Record<string, unknown> | null, checkpoint: Chec
value.exportJobId !== checkpoint.exportJobId ||
value.sourceBoxId !== checkpoint.sourceBoxId ||
value.arcPath !== checkpoint.arcPath ||
+ reportedKind !== kind ||
+ (kind === 'full'
+ ? typeof memorySizeBytes !== 'number' || !Number.isSafeInteger(memorySizeBytes) || memorySizeBytes < 0
+ : memorySizeBytes !== undefined) ||
!Number.isSafeInteger(value.sizeBytes) ||
(value.sizeBytes as number) <= 0 ||
typeof value.sha256 !== 'string' ||
@@ -305,5 +315,7 @@ function validateArchive(value: Record<string, unknown> | null, checkpoint: Chec
sizeBytes: value.sizeBytes as number,
sha256: value.sha256,
pinnedImage: value.pinnedImage,
+ kind,
+ ...(typeof memorySizeBytes === 'number' ? { memorySizeBytes } : {}),
}
}
diff --git a/apps/api/src/box/services/checkpoint-recover.service.ts b/apps/api/src/box/services/checkpoint-recover.service.ts
index 82b33a4e9..5a572d5d1 100644
--- a/apps/api/src/box/services/checkpoint-recover.service.ts
+++ b/apps/api/src/box/services/checkpoint-recover.service.ts
@@ -59,6 +59,7 @@ export class CheckpointRecoverService {
regions: [selected.environment.region],
boxClass: selected.environment.class,
requiresPrivileged: selected.environment.privileged,
+ ...(selected.kind === 'full' ? { requiredCapability: 'memory_checkpoint' } : {}),
})
if (runner.apiVersion !== '2') throw new ConflictException('Checkpoint creation requires a v2 runner')
const box = Object.assign(new Box(selected.environment.region, name), selected.environment, {
@@ -115,6 +116,7 @@ export class CheckpointRecoverService {
this.checkpoints.assertEnabled()
this.organizations.assertOrganizationIsNotSuspended(organization)
const checkpoint = await this.checkpoints.get(organization.id, key)
+ if (checkpoint.kind === 'full') this.checkpoints.assertMemoryEnabled()
if (checkpoint.state !== 'ready' || !checkpoint.archive) throw new ConflictException('Checkpoint is not ready')
if (!checkpoint.environment.image) throw new BadRequestException('Checkpoint has no OCI image')
const limits = await this.limits.resolve(organization)
@@ -136,6 +138,7 @@ export class CheckpointRecoverService {
runner.apiVersion !== '2' ||
runner.draining ||
runner.unschedulable ||
+ (checkpoint.kind === 'full' && !runner.capabilities?.includes('memory_checkpoint')) ||
runner.region !== env.region ||
runner.class !== env.class ||
(env.privileged && !runner.supportsPrivileged) ||
@@ -175,6 +178,7 @@ export class CheckpointRecoverService {
targetBoxId: box.id,
mode: operation.mode,
archive: checkpoint.archive,
+ kind: checkpoint.kind,
platformEnv: operation.platformEnv,
})
Object.assign(operation, { jobId: job.id, state: 'pending', errorReason: null })
diff --git a/apps/api/src/box/services/checkpoint.integration.spec.ts b/apps/api/src/box/services/checkpoint.integration.spec.ts
index b24f5eca9..164dbad00 100644
--- a/apps/api/src/box/services/checkpoint.integration.spec.ts
+++ b/apps/api/src/box/services/checkpoint.integration.spec.ts
@@ -68,7 +68,7 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>
const imageAdmission = { assert: jest.fn() }
const runnerSelection = { getRandomAvailableRunner: jest.fn() }
const archiveStore = { remove: jest.fn() }
- let settings: { archivePrefix?: string; maxPerOrganization: number; enabled?: boolean }
+ let settings: { archivePrefix?: string; maxPerOrganization: number; enabled?: boolean; memoryEnabled?: boolean }
const cache = { invalidate: jest.fn() }
const jobNotifications: { visible: boolean; boxUnlocked: boolean }[] = []
const uploadNotifications = { lpush: jest.fn() }
@@ -239,6 +239,7 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>
sizeBytes: 1024,
sha256: 'a'.repeat(64),
pinnedImage: 'registry.example/app@sha256:' + 'b'.repeat(64),
+ kind: checkpoint.kind,
}
}
@@ -263,6 +264,121 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>
return service.get(organizationId, checkpoint.id)
}
+ async function fullSource(name?: string): Promise<Box> {
+ const box = await source(name)
+ await boxes.update(box.id, { state: BoxState.STARTED, desiredState: BoxDesiredState.STARTED })
+ return box
+ }
+
+ async function enableRunnerMemory(): Promise<void> {
+ runner.capabilities = ['memory_checkpoint']
+ await dataSource.getRepository(Runner).save(runner)
+ }
+
+ it('requires full rollout, a started source and runner capability for full capture', async () => {
+ const box = await source()
+ const capture = () => service.create(organizationId, box.id, undefined, 'full')
+ await expect(capture()).rejects.toMatchObject({ status: 400, response: { code: 'unsupported' } })
+ settings.memoryEnabled = true
+ await expect(capture()).rejects.toMatchObject({ status: 409, response: { code: 'invalid_state' } })
+ await boxes.update(box.id, { state: BoxState.STARTED, desiredState: BoxDesiredState.STARTED })
+ await expect(capture()).rejects.toMatchObject({
+ status: 400,
+ response: { message: 'Source runner does not support full checkpoints', code: 'unsupported' },
+ })
+ expect(await checkpoints.count()).toBe(0)
+ })
+
+ it('persists full metadata and routes restore only to a memory-capable runner', async () => {
+ settings.memoryEnabled = true
+ await enableRunnerMemory()
+ const box = await fullSource()
+ const checkpoint = await service.create(organizationId, box.id, 'full-base', 'full')
+ const exportJob = await jobs.findOneByOrFail({ id: checkpoint.exportJobId! })
+ expect(exportJob.getPayload()).toEqual({ checkpointId: checkpoint.id, arcPath: checkpoint.arcPath, kind: 'full' })
+ expect(checkpoint).toMatchObject({ kind: 'full', memorySizeBytes: null })
+
+ const metadata = { ...archive(checkpoint), memorySizeBytes: 0 }
+ await finish(exportJob.id, metadata)
+ const uploading = await service.get(organizationId, checkpoint.id)
+ expect(uploading).toMatchObject({ kind: 'full', memorySizeBytes: 0, archive: metadata })
+ const controller = new BoxliteCheckpointController(service)
+ const auth = { organizationId } as never
+ const response = await controller.get(auth, checkpoint.id)
+ expect(response).toMatchObject({ kind: 'full', state: 'creating' })
+ expect(response).not.toHaveProperty('memory_size_bytes')
+ expect(await boxes.findOneByOrFail({ id: box.id })).toMatchObject({ state: BoxState.STARTED, pending: false })
+ await finish(uploading.activeJobId!, metadata)
+ expect(await controller.get(auth, checkpoint.id)).toMatchObject({ state: 'ready', memory_size_bytes: 0 })
+
+ const restore = () => recovery.createBox(organization, checkpoint.id, 'full-target', undefined)
+ settings.memoryEnabled = false
+ await expect(restore()).rejects.toMatchObject({ status: 400, response: { code: 'unsupported' } })
+ expect(runnerSelection.getRandomAvailableRunner).not.toHaveBeenCalled()
+ settings.memoryEnabled = true
+ await dataSource.getRepository(Runner).update(runner.id, { capabilities: [] })
+ await expect(restore()).rejects.toMatchObject({ status: 409 })
+ expect(runnerSelection.getRandomAvailableRunner).toHaveBeenCalledWith(
+ expect.objectContaining({ requiredCapability: 'memory_checkpoint' }),
+ )
+ await enableRunnerMemory()
+ const target = await restore().then(withCheckpointState)
+ const importJob = await jobs.findOneByOrFail({ id: target.activeJobId! })
+ expect(importJob.getPayload()).toMatchObject({ kind: 'full', archive: metadata })
+ })
+
+ it.each([
+ ['full', 'export', undefined],
+ ['full', 'export', -1],
+ ['full', 'export', Number.MAX_SAFE_INTEGER + 1],
+ ['full', 'upload', 2],
+ ['disk', 'export', 0],
+ ] as const)('rejects invalid %s %s memory metadata (%s)', async (kind, phase, memorySizeBytes) => {
+ settings.memoryEnabled = true
+ await enableRunnerMemory()
+ const box = await (kind === 'full' ? fullSource() : source())
+ const checkpoint = await service.create(organizationId, box.id, undefined, kind)
+ let jobId = checkpoint.exportJobId!
+ if (phase === 'upload') {
+ await finish(jobId, { ...archive(checkpoint), memorySizeBytes: 1 })
+ jobId = (await service.get(organizationId, checkpoint.id)).activeJobId!
+ }
+ await finish(jobId, { ...archive(checkpoint), memorySizeBytes })
+ expect(await service.get(organizationId, checkpoint.id)).toMatchObject({ state: 'failed', activeJobId: null })
+ })
+
+ it('rejects omitted kind on full receipts and null kind on all receipts while keeping legacy disk omission', async () => {
+ settings.memoryEnabled = true
+ await enableRunnerMemory()
+
+ const fullExportBox = await fullSource('full-export-omitted-kind')
+ const fullExportCp = await service.create(organizationId, fullExportBox.id, undefined, 'full')
+ const { kind: _omit1, ...fullExportNoKind } = archive(fullExportCp)
+ await finish(fullExportCp.exportJobId!, { ...fullExportNoKind, memorySizeBytes: 0 })
+ expect(await service.get(organizationId, fullExportCp.id)).toMatchObject({ state: 'failed', activeJobId: null })
+
+ const fullUploadBox = await fullSource('full-upload-omitted-kind')
+ const fullUploadCp = await service.create(organizationId, fullUploadBox.id, undefined, 'full')
+ await finish(fullUploadCp.exportJobId!, { ...archive(fullUploadCp), memorySizeBytes: 0 })
+ const uploading = await service.get(organizationId, fullUploadCp.id)
+ const { kind: _omit2, ...fullUploadNoKind } = archive(fullUploadCp)
+ await finish(uploading.activeJobId!, { ...fullUploadNoKind, memorySizeBytes: 0 })
+ expect(await service.get(organizationId, fullUploadCp.id)).toMatchObject({ state: 'failed', activeJobId: null })
+
+ const diskBox = await source('legacy-disk-omitted-kind')
+ const diskCp = await service.create(organizationId, diskBox.id)
+ const { kind: _omit3, ...diskNoKind } = archive(diskCp)
+ await finish(diskCp.exportJobId!, diskNoKind)
+ const diskUploading = await service.get(organizationId, diskCp.id)
+ await finish(diskUploading.activeJobId!, diskNoKind)
+ expect(await service.get(organizationId, diskCp.id)).toMatchObject({ state: 'ready', kind: 'disk' })
+
+ const nullKindBox = await source('null-kind')
+ const nullKindCp = await service.create(organizationId, nullKindBox.id)
+ await finish(nullKindCp.exportJobId!, { ...archive(nullKindCp), kind: null })
+ expect(await service.get(organizationId, nullKindCp.id)).toMatchObject({ state: 'failed', activeJobId: null })
+ })
+
it('notifies checkpoint export and import only after their transactions commit', async () => {
const checkpoint = await readyCheckpoint()
await recovery.createBox(organization, checkpoint.id, 'notification-target', undefined)
diff --git a/apps/api/src/box/services/checkpoint.service.ts b/apps/api/src/box/services/checkpoint.service.ts
index bb2d0b41b..41be13070 100644
--- a/apps/api/src/box/services/checkpoint.service.ts
+++ b/apps/api/src/box/services/checkpoint.service.ts
@@ -15,7 +15,7 @@ import { isUUID } from 'class-validator'
import { Box } from '../entities/box.entity'
import { memoryMibOf } from '../utils/memory-allocation'
import { BoxCheckpointState } from '../entities/box-checkpoint-state.entity'
-import { Checkpoint, CheckpointEnvironment } from '../entities/checkpoint.entity'
+import { Checkpoint, CheckpointEnvironment, CheckpointKind } from '../entities/checkpoint.entity'
import { Runner } from '../entities/runner.entity'
import { BoxState } from '../enums/box-state.enum'
import { RunnerState } from '../enums/runner-state.enum'
@@ -48,7 +48,20 @@ export class CheckpointService {
return settings
}
- async create(organizationId: string, source: string, name?: string): Promise<Checkpoint> {
+ assertMemoryEnabled(): void {
+ const settings = this.config.get<ReturnType<typeof checkpointConfig>>('checkpoint')
+ if (!settings?.memoryEnabled) {
+ throw new BadRequestException({ message: 'Full checkpoints are not supported', code: 'unsupported' })
+ }
+ }
+
+ async create(
+ organizationId: string,
+ source: string,
+ name?: string,
+ kind: CheckpointKind = 'disk',
+ ): Promise<Checkpoint> {
+ if (kind === 'full') this.assertMemoryEnabled()
if (!source || source.includes('\0') || source.length > 128) throw new BadRequestException('Invalid source box')
if (name !== undefined && !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name))
throw new BadRequestException('Invalid checkpoint name')
@@ -80,10 +93,13 @@ export class CheckpointService {
box.pending ||
checkpointState.activeJobId ||
String(box.state) !== String(box.desiredState) ||
- box.state !== BoxState.STOPPED
+ box.state !== (kind === 'full' ? BoxState.STARTED : BoxState.STOPPED)
) {
throw new ConflictException({
- message: 'Checkpoint source must be idle and stopped; stop the Box before creating a checkpoint',
+ message:
+ kind === 'full'
+ ? 'Full checkpoint source must be idle and started'
+ : 'Checkpoint source must be idle and stopped; stop the Box before creating a checkpoint',
code: 'invalid_state',
})
}
@@ -104,6 +120,11 @@ export class CheckpointService {
})
: null
if (!runner) throw new ConflictException('Source runner is not ready for checkpoint jobs')
+ if (kind === 'full' && !runner.capabilities?.includes('memory_checkpoint'))
+ throw new BadRequestException({
+ message: 'Source runner does not support full checkpoints',
+ code: 'unsupported',
+ })
if (
await manager.exists(Job, {
where: {
@@ -132,12 +153,15 @@ export class CheckpointService {
state: 'creating',
arcPath: `${settings.archivePrefix}${organizationId}/${id}/archive.boxlite`,
environment: captureEnvironment(box),
+ kind,
+ memorySizeBytes: null,
archive: null,
errorReason: null,
})
const job = await this.jobs.createJob(manager, JobType.EXPORT_CHECKPOINT, runner.id, ResourceType.BOX, box.id, {
checkpointId: id,
arcPath: checkpoint.arcPath,
+ kind,
})
checkpoint.exportJobId = job.id
checkpoint.activeJobId = job.id
diff --git a/apps/api/src/box/services/runner.service.capabilities.spec.ts b/apps/api/src/box/services/runner.service.capabilities.spec.ts
index b8ffbb9f2..236b49e18 100644
--- a/apps/api/src/box/services/runner.service.capabilities.spec.ts
+++ b/apps/api/src/box/services/runner.service.capabilities.spec.ts
@@ -7,6 +7,42 @@ import { validateSync } from 'class-validator'
import { RunnerService } from './runner.service'
import { RunnerHealthcheckDto } from '../dto/runner-health.dto'
import { RunnerState } from '../enums/runner-state.enum'
+import type { Runner } from '../entities/runner.entity'
+
+describe('RunnerService.findAvailableRunners capability filtering', () => {
+ const capable = { id: 'memory-runner', availabilityScore: 50, capabilities: ['filestore', 'memory_checkpoint'] }
+ const undeclared = { id: 'undeclared-runner', availabilityScore: 90, capabilities: null }
+ const unrelated = { id: 'filestore-runner', availabilityScore: 80, capabilities: ['filestore'] }
+
+ function serviceWithRunners(runners: Pick<Runner, 'id' | 'availabilityScore' | 'capabilities'>[]): RunnerService {
+ const service = Object.create(RunnerService.prototype) as RunnerService
+ return Object.assign(service, { runnerRepository: { find: jest.fn().mockResolvedValue(runners) } })
+ }
+
+ it('excludes runners with no declaration or without the required capability', async () => {
+ const service = serviceWithRunners([undeclared, capable, unrelated])
+ await expect(
+ service.findAvailableRunners({ availabilityScoreThreshold: 1, requiredCapability: 'memory_checkpoint' }),
+ ).resolves.toEqual([capable])
+ })
+
+ it('filters out higher-scoring incompatible runners before taking the top ten', async () => {
+ const incompatible = Array.from({ length: 10 }, (_, index) => ({ ...unrelated, id: `filestore-${index}` }))
+ const service = serviceWithRunners([...incompatible, capable])
+ await expect(
+ service.findAvailableRunners({ availabilityScoreThreshold: 1, requiredCapability: 'memory_checkpoint' }),
+ ).resolves.toEqual([capable])
+ })
+
+ it('keeps runners regardless of capability when none is required', async () => {
+ const service = serviceWithRunners([capable, unrelated, undeclared])
+ await expect(service.findAvailableRunners({ availabilityScoreThreshold: 1 })).resolves.toEqual([
+ undeclared,
+ unrelated,
+ capable,
+ ])
+ })
+})
describe('Runner capability declarations', () => {
it.each([[undefined], [['filestore']], [[]]] as [string[] | undefined][])(
@@ -65,13 +101,14 @@ describe('Runner capability declarations', () => {
expect(write.mock.calls[0][1]).not.toHaveProperty('capabilities')
})
- it.each([null, 'filestore', 1, ['filestore', 1]])('rejects invalid capabilities %p on the heartbeat boundary', (value) => {
- const dto = Object.assign(new RunnerHealthcheckDto(), {
- appVersion: 'dev',
- capabilities: value,
- })
- expect(validateSync(dto).map((error) => error.property)).toEqual(
- expect.arrayContaining(['capabilities']),
- )
- })
+ it.each([null, 'filestore', 1, ['filestore', 1]])(
+ 'rejects invalid capabilities %p on the heartbeat boundary',
+ (value) => {
+ const dto = Object.assign(new RunnerHealthcheckDto(), {
+ appVersion: 'dev',
+ capabilities: value,
+ })
+ expect(validateSync(dto).map((error) => error.property)).toEqual(expect.arrayContaining(['capabilities']))
+ },
+ )
})
diff --git a/apps/api/src/box/services/runner.service.ts b/apps/api/src/box/services/runner.service.ts
index b6b31b9a1..62d571bb8 100644
--- a/apps/api/src/box/services/runner.service.ts
+++ b/apps/api/src/box/services/runner.service.ts
@@ -312,7 +312,11 @@ export class RunnerService {
where: runnerFilter,
})
- return runners.sort((a, b) => b.availabilityScore - a.availabilityScore).slice(0, 10)
+ const { requiredCapability } = params
+ return runners
+ .filter((runner) => requiredCapability === undefined || runner.capabilities?.includes(requiredCapability))
+ .sort((a, b) => b.availabilityScore - a.availabilityScore)
+ .slice(0, 10)
}
/**
@@ -1048,6 +1052,7 @@ export class GetRunnerParams {
excludedRunnerIds?: string[]
availabilityScoreThreshold?: number
requiresPrivileged?: boolean
+ requiredCapability?: string
}
interface AvailabilityScoreParams {
diff --git a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
index f5de536fe..2f3f104ae 100644
--- a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
@@ -260,7 +260,7 @@ describe('Checkpoint REST authentication and request admission', () => {
})
}
expect(checkpoints.create.mock.calls).toEqual(
- Array.from({ length: 3 }, () => [organizationId, 'source-id', 'base']),
+ Array.from({ length: 3 }, () => [organizationId, 'source-id', 'base', 'disk']),
)
})
@@ -271,7 +271,7 @@ describe('Checkpoint REST authentication and request admission', () => {
})
expect(result.status).toBe(201)
expect(await result.json()).toMatchObject({ id: record.id, kind: 'disk' })
- expect(checkpoints.create).toHaveBeenCalledWith(organizationId, 'source-id', undefined)
+ expect(checkpoints.create).toHaveBeenCalledWith(organizationId, 'source-id', undefined, 'disk')
})
it('preserves the invalid_state code from a checkpoint source state conflict', async () => {
@@ -298,14 +298,58 @@ describe('Checkpoint REST authentication and request admission', () => {
expect(body).not.toHaveProperty('code')
})
- it('rejects full capture before calling the service', async () => {
+ it('passes full capture to the service and preserves its unsupported error', async () => {
+ checkpoints.create.mockRejectedValueOnce(
+ new BadRequestException({ message: 'Full checkpoints are not supported', code: 'unsupported' }),
+ )
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()
+ expect(checkpoints.create).toHaveBeenCalledWith(organizationId, 'source-id', undefined, 'full')
+ })
+
+ it.each([0, 42])(
+ 'omits a known memory size of %i bytes while creating a full checkpoint',
+ async (memorySizeBytes) => {
+ checkpoints.create.mockResolvedValueOnce({ ...record, kind: 'full', memorySizeBytes })
+ const result = await request('/v1/checkpoints', 'checkpoint-write-key', {
+ source_box_id: 'source-id',
+ kind: 'full',
+ })
+ expect(result.status).toBe(201)
+ const body = await result.json()
+ expect(body).toMatchObject({ kind: 'full', state: 'creating' })
+ expect(body).not.toHaveProperty('memory_size_bytes')
+ },
+ )
+
+ it.each([0, 42])('returns a known memory size of %i bytes for a ready full checkpoint', async (memorySizeBytes) => {
+ checkpoints.get.mockResolvedValueOnce({ ...record, kind: 'full', state: 'ready', memorySizeBytes })
+ const result = await request('/v1/checkpoints/base', 'checkpoint-read-key')
+ expect(result.status).toBe(200)
+ expect(await result.json()).toMatchObject({ kind: 'full', state: 'ready', memory_size_bytes: memorySizeBytes })
+ })
+
+ it.each([
+ ['disk', 42],
+ ['full', null],
+ ['full', undefined],
+ ])('omits memory_size_bytes for a ready %s checkpoint with memorySizeBytes=%p', async (kind, memorySizeBytes) => {
+ checkpoints.get.mockResolvedValueOnce({
+ ...record,
+ kind,
+ state: 'ready',
+ memorySizeBytes,
+ archive: { sizeBytes: 100, memorySizeBytes: 42 },
+ })
+ const result = await request('/v1/checkpoints/base', 'checkpoint-read-key')
+ expect(result.status).toBe(200)
+ const body = await result.json()
+ expect(body).toMatchObject({ kind, state: 'ready', size_bytes: 100 })
+ expect(body).not.toHaveProperty('memory_size_bytes')
})
it.each([null, 'bogus', 123])('rejects invalid checkpoint kind %j before calling the service', async (kind) => {
diff --git a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts
index 003eca7ee..b867fca32 100644
--- a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts
+++ b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: AGPL-3.0
import {
- BadRequestException,
Body,
Controller,
Delete,
@@ -23,7 +22,7 @@ import { RequiredOrganizationResourcePermissions } from '../organization/decorat
import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'
import { AuthContext } from '../common/decorators/auth-context.decorator'
import { OrganizationAuthContext } from '../common/interfaces/auth-context.interface'
-import { Checkpoint } from '../box/entities/checkpoint.entity'
+import { Checkpoint, CheckpointKind } from '../box/entities/checkpoint.entity'
import { CheckpointService } from '../box/services/checkpoint.service'
import { ReplayParseBoolPipe, ReplayValidationPipe } from '../common/replay-validation.pipe'
@@ -32,7 +31,7 @@ class CreateCheckpointRequest {
@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'
+ kind?: CheckpointKind
}
@Controller(['v1/checkpoints', 'v1/:prefix/checkpoints'])
@@ -46,11 +45,13 @@ 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),
+ await this.checkpoints.create(
+ auth.organizationId,
+ request.source_box_id,
+ request.name ?? undefined,
+ request.kind ?? 'disk',
+ ),
)
}
@@ -84,14 +85,18 @@ export class BoxliteCheckpointController {
}
function response(checkpoint: Checkpoint) {
+ const { kind, state, memorySizeBytes } = checkpoint
return {
id: checkpoint.id,
name: checkpoint.name,
source_box_id: checkpoint.sourceBoxId,
- state: checkpoint.state,
- kind: 'disk',
+ state,
+ kind: kind ?? 'disk',
created_at: checkpoint.createdAt.toISOString(),
size_bytes: checkpoint.archive?.sizeBytes ?? 0,
+ ...(kind === 'full' && state !== 'creating' && memorySizeBytes != null
+ ? { memory_size_bytes: memorySizeBytes }
+ : {}),
...(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.ts
index 224703ccb..5000907f3 100644
--- a/apps/api/src/boxlite-rest/boxlite-config.controller.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-config.controller.spec.ts
@@ -2,7 +2,7 @@ import { TypedConfigService } from '../config/typed-config.service'
import { BoxliteConfigController } from './boxlite-config.controller'
function createConfig(values: {
- checkpoint?: { archivePrefix?: string; enabled?: boolean }
+ checkpoint?: { archivePrefix?: string; enabled?: boolean; memoryEnabled?: boolean }
objectStorageConfigured?: boolean
filestoreSupported?: boolean
filestoreInstanceCount?: number
@@ -10,6 +10,7 @@ function createConfig(values: {
return {
get: (key: string) => {
if (key === 'checkpoint.enabled') return values.checkpoint?.enabled
+ if (key === 'checkpoint.memoryEnabled') return values.checkpoint?.memoryEnabled
if (key === 'checkpoint.archivePrefix') return values.checkpoint?.archivePrefix
if (key === 's3.endpoint') return values.objectStorageConfigured ? 'http://object-storage.test' : undefined
if (key === 'volume.filestoreSupported') return values.filestoreSupported ?? true
@@ -41,6 +42,15 @@ describe('checkpoint capability discovery', () => {
expect(controller.getConfig().capabilities.memory_checkpoints_enabled).toBe(false)
expect(controller.getConfig().capabilities.import_enabled).toBe(false)
})
+
+ it.each([
+ { enabled: true, memoryEnabled: true, archivePrefix: undefined, expected: false },
+ { enabled: false, memoryEnabled: true, archivePrefix: 'gs://checkpoint-test/archives/', expected: false },
+ { enabled: true, memoryEnabled: true, archivePrefix: 'gs://checkpoint-test/archives/', expected: true },
+ ])('advertises memory checkpoints only when fully enabled: %j', ({ expected, ...checkpoint }) => {
+ const controller = new BoxliteConfigController(createConfig({ checkpoint }))
+ expect(controller.getConfig().capabilities.memory_checkpoints_enabled).toBe(expected)
+ })
})
describe('volume storage capability discovery', () => {
diff --git a/apps/api/src/boxlite-rest/boxlite-config.controller.ts b/apps/api/src/boxlite-rest/boxlite-config.controller.ts
index c6ac0d79f..45ad82674 100644
--- a/apps/api/src/boxlite-rest/boxlite-config.controller.ts
+++ b/apps/api/src/boxlite-rest/boxlite-config.controller.ts
@@ -22,11 +22,13 @@ export class BoxliteConfigController {
@Get('config')
getConfig() {
+ const checkpointsEnabled =
+ this.config?.get('checkpoint.enabled') === true && !!this.config?.get('checkpoint.archivePrefix')
+
return {
capabilities: {
- checkpoints_enabled:
- this.config?.get('checkpoint.enabled') === true && !!this.config?.get('checkpoint.archivePrefix'),
- memory_checkpoints_enabled: false,
+ checkpoints_enabled: checkpointsEnabled,
+ memory_checkpoints_enabled: checkpointsEnabled && this.config?.get('checkpoint.memoryEnabled') === true,
object_storage_enabled: this.config ? isVolumeStorageConfigured(this.config) : false,
filestore_enabled:
this.config?.get('volume.filestoreSupported') !== false &&
diff --git a/apps/api/src/config/checkpoint-config.spec.ts b/apps/api/src/config/checkpoint-config.spec.ts
index 746d1bde3..b5fe9f47c 100644
--- a/apps/api/src/config/checkpoint-config.spec.ts
+++ b/apps/api/src/config/checkpoint-config.spec.ts
@@ -2,7 +2,12 @@ import { checkpointConfig } from './checkpoint-config'
describe('checkpoint storage configuration', () => {
it('stays disabled without a bucket-qualified prefix', () => {
- expect(checkpointConfig({})).toEqual({ archivePrefix: undefined, maxPerOrganization: 10, enabled: false })
+ expect(checkpointConfig({})).toEqual({
+ archivePrefix: undefined,
+ maxPerOrganization: 10,
+ enabled: false,
+ memoryEnabled: false,
+ })
})
it.each(['gs://checkpoint-bucket/checkpoints', 'gs://checkpoint-bucket/checkpoints/'])('normalizes %s', (prefix) => {
@@ -10,6 +15,7 @@ describe('checkpoint storage configuration', () => {
archivePrefix: 'gs://checkpoint-bucket/checkpoints/',
maxPerOrganization: 20,
enabled: false,
+ memoryEnabled: false,
})
})
@@ -22,6 +28,21 @@ describe('checkpoint storage configuration', () => {
expect(() => checkpointConfig({ ...storage, CHECKPOINTS_ENABLED: 'yes' })).toThrow('CHECKPOINTS_ENABLED')
})
+ it('enables memory only with both rollout flags and archive storage', () => {
+ const storage = { CHECKPOINT_ARCHIVE_PREFIX: 'gs://checkpoint-bucket/checkpoints' }
+ const enabled = { ...storage, CHECKPOINTS_ENABLED: 'true' }
+ const memory = { MEMORY_CHECKPOINTS_ENABLED: 'true' }
+ expect(checkpointConfig(enabled).memoryEnabled).toBe(false)
+ expect(checkpointConfig({ ...enabled, MEMORY_CHECKPOINTS_ENABLED: 'false' }).memoryEnabled).toBe(false)
+ expect(checkpointConfig({ ...storage, ...memory }).memoryEnabled).toBe(false)
+ expect(checkpointConfig({ CHECKPOINTS_ENABLED: 'true', ...memory }).memoryEnabled).toBe(false)
+ expect(checkpointConfig({ ...enabled, ...memory }).memoryEnabled).toBe(true)
+ })
+
+ it.each(['', 'TRUE', '1', ' true '])('rejects invalid memory flag %j', (flag) => {
+ expect(() => checkpointConfig({ MEMORY_CHECKPOINTS_ENABLED: flag })).toThrow('MEMORY_CHECKPOINTS_ENABLED')
+ })
+
it.each([
's3://bucket/prefix',
'gs:///prefix',
diff --git a/apps/api/src/config/checkpoint-config.ts b/apps/api/src/config/checkpoint-config.ts
index 95d1a16b2..8981cd737 100644
--- a/apps/api/src/config/checkpoint-config.ts
+++ b/apps/api/src/config/checkpoint-config.ts
@@ -5,13 +5,18 @@ export function checkpointConfig(env: NodeJS.ProcessEnv = process.env) {
const flag = env.CHECKPOINTS_ENABLED?.trim()
if (flag && flag !== 'true' && flag !== 'false') throw new Error('CHECKPOINTS_ENABLED must be true or false')
const enabled = flag === 'true'
+ const memoryFlag = env.MEMORY_CHECKPOINTS_ENABLED ?? 'false'
+ if (memoryFlag !== 'true' && memoryFlag !== 'false')
+ throw new Error('MEMORY_CHECKPOINTS_ENABLED must be true or false')
const rawLimit = env.CHECKPOINT_MAX_PER_ORGANIZATION?.trim()
const maxPerOrganization = rawLimit ? Number(rawLimit) : 10
if ((rawLimit && !/^\d+$/.test(rawLimit)) || !Number.isSafeInteger(maxPerOrganization) || maxPerOrganization < 1) {
throw new Error('CHECKPOINT_MAX_PER_ORGANIZATION must be a positive safe integer')
}
const raw = env.CHECKPOINT_ARCHIVE_PREFIX?.trim()
- if (!raw) return { archivePrefix: undefined as string | undefined, maxPerOrganization, enabled: false }
+ if (!raw) {
+ return { archivePrefix: undefined as string | undefined, maxPerOrganization, enabled: false, memoryEnabled: false }
+ }
const match = /^gs:\/\/([a-z0-9][a-z0-9._-]{1,61}[a-z0-9])(?:\/(.*))?$/.exec(raw)
const suffix = match?.[2]?.replace(/\/+$/, '') ?? ''
const segments = suffix ? suffix.split('/') : []
@@ -22,5 +27,6 @@ export function checkpointConfig(env: NodeJS.ProcessEnv = process.env) {
archivePrefix: `gs://${match[1]}/${segments.length ? segments.join('/') + '/' : ''}`,
maxPerOrganization,
enabled,
+ memoryEnabled: enabled && memoryFlag === 'true',
}
}
diff --git a/apps/api/src/migrations/pre-deploy/1795564800000-add-checkpoint-kind-migration.integration.spec.ts b/apps/api/src/migrations/pre-deploy/1795564800000-add-checkpoint-kind-migration.integration.spec.ts
new file mode 100644
index 000000000..f9904c0d1
--- /dev/null
+++ b/apps/api/src/migrations/pre-deploy/1795564800000-add-checkpoint-kind-migration.integration.spec.ts
@@ -0,0 +1,102 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+import { randomUUID } from 'node:crypto'
+import { DataSource, QueryRunner } from 'typeorm'
+import { AddCheckpoints1793923200000 } from './1793923200000-add-checkpoints-migration'
+import { AddCheckpointKind1795564800000 } from './1795564800000-add-checkpoint-kind-migration'
+
+const describeWithDatabase = process.env.DB_HOST ? describe : describe.skip
+const schema = `checkpoint_kind_migration_${process.pid}_${randomUUID().replaceAll('-', '')}`
+
+describeWithDatabase('checkpoint kind migration (real PostgreSQL)', () => {
+ let dataSource: DataSource
+ let runner: QueryRunner
+ const baseMigration = new AddCheckpoints1793923200000()
+ const migration = new AddCheckpointKind1795564800000()
+
+ beforeAll(async () => {
+ dataSource = await new DataSource({
+ type: 'postgres',
+ host: process.env.DB_HOST,
+ port: Number(process.env.DB_PORT || 5432),
+ username: process.env.DB_USERNAME,
+ password: process.env.DB_PASSWORD,
+ database: process.env.DB_DATABASE,
+ schema,
+ extra: { options: `-c search_path=${schema},public` },
+ }).initialize()
+ runner = dataSource.createQueryRunner()
+ await runner.connect()
+ })
+
+ beforeEach(async () => {
+ await runner.query(`CREATE SCHEMA "${schema}"`)
+ await runner.query(`CREATE TYPE "${schema}"."job_resourcetype_enum" AS ENUM ('BOX','ARTIFACT','BACKUP')`)
+ await runner.query(`CREATE TABLE "${schema}"."box" ("id" varchar PRIMARY KEY)`)
+ await runner.query(
+ `CREATE TABLE "${schema}"."job" ("type" varchar, "resourceType" "${schema}"."job_resourcetype_enum", "completedAt" timestamptz)`,
+ )
+ await baseMigration.up(runner)
+ })
+
+ afterEach(async () => {
+ await runner.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)
+ })
+
+ afterAll(async () => {
+ await runner?.release()
+ await dataSource?.destroy()
+ })
+
+ it('backfills existing rows as disk and enforces kind and memorySizeBytes constraints', async () => {
+ const existingId = randomUUID()
+ await runner.query(
+ `INSERT INTO "checkpoint" ("id","organizationId","name","sourceBoxId","sourceRunnerId","sourceState","arcPath","environment")
+ VALUES ($1,$2,'legacy','source-1',$3,'stopped','gs://bucket/legacy','{}')`,
+ [existingId, randomUUID(), randomUUID()],
+ )
+
+ await migration.up(runner)
+
+ const [legacy] = await runner.query(`SELECT "kind", "memorySizeBytes" FROM "checkpoint" WHERE "id" = $1`, [
+ existingId,
+ ])
+ expect(legacy).toEqual({ kind: 'disk', memorySizeBytes: null })
+
+ await expect(
+ runner.query(
+ `INSERT INTO "checkpoint" ("id","organizationId","name","sourceBoxId","sourceRunnerId","sourceState","kind","arcPath","environment")
+ VALUES ($1,$2,'bad-kind','source-2',$3,'started','snapshot','gs://bucket/bad','{}')`,
+ [randomUUID(), randomUUID(), randomUUID()],
+ ),
+ ).rejects.toMatchObject({ code: '23514' })
+
+ await expect(
+ runner.query(
+ `INSERT INTO "checkpoint" ("id","organizationId","name","sourceBoxId","sourceRunnerId","sourceState","kind","memorySizeBytes","arcPath","environment")
+ VALUES ($1,$2,'neg-mem','source-3',$3,'started','full',-1,'gs://bucket/neg','{}')`,
+ [randomUUID(), randomUUID(), randomUUID()],
+ ),
+ ).rejects.toMatchObject({ code: '23514' })
+ })
+
+ it('refuses rollback while full checkpoints exist and drops columns once removed', async () => {
+ await migration.up(runner)
+ const fullId = randomUUID()
+ await runner.query(
+ `INSERT INTO "checkpoint" ("id","organizationId","name","sourceBoxId","sourceRunnerId","sourceState","kind","memorySizeBytes","arcPath","environment")
+ VALUES ($1,$2,'full-1','source-1',$3,'started','full',4096,'gs://bucket/full','{}')`,
+ [fullId, randomUUID(), randomUUID()],
+ )
+
+ await expect(migration.down(runner)).rejects.toThrow('Delete full checkpoints')
+ expect(await runner.hasColumn('checkpoint', 'kind')).toBe(true)
+ expect(await runner.hasColumn('checkpoint', 'memorySizeBytes')).toBe(true)
+
+ await runner.query(`DELETE FROM "checkpoint" WHERE "id" = $1`, [fullId])
+ await migration.down(runner)
+ expect(await runner.hasColumn('checkpoint', 'kind')).toBe(false)
+ expect(await runner.hasColumn('checkpoint', 'memorySizeBytes')).toBe(false)
+ })
+})
diff --git a/apps/api/src/migrations/pre-deploy/1795564800000-add-checkpoint-kind-migration.ts b/apps/api/src/migrations/pre-deploy/1795564800000-add-checkpoint-kind-migration.ts
new file mode 100644
index 000000000..430d25ccc
--- /dev/null
+++ b/apps/api/src/migrations/pre-deploy/1795564800000-add-checkpoint-kind-migration.ts
@@ -0,0 +1,28 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+import { MigrationInterface, QueryRunner } from 'typeorm'
+
+export class AddCheckpointKind1795564800000 implements MigrationInterface {
+ async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`ALTER TABLE "checkpoint"
+ ADD COLUMN "kind" varchar NOT NULL DEFAULT 'disk',
+ ADD COLUMN "memorySizeBytes" bigint,
+ ADD CONSTRAINT "checkpoint_kind_check" CHECK ("kind" IN ('disk','full')),
+ ADD CONSTRAINT "checkpoint_memory_size_bytes_check" CHECK ("memorySizeBytes" IS NULL OR "memorySizeBytes" >= 0)`)
+ }
+
+ async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DO $$ BEGIN
+ LOCK TABLE "checkpoint" IN ACCESS EXCLUSIVE MODE;
+ IF EXISTS (SELECT 1 FROM "checkpoint" WHERE "kind" = 'full') THEN
+ RAISE EXCEPTION 'Delete full checkpoints before reverting checkpoint kind storage';
+ END IF;
+ ALTER TABLE "checkpoint"
+ DROP CONSTRAINT "checkpoint_kind_check",
+ DROP CONSTRAINT "checkpoint_memory_size_bytes_check",
+ DROP COLUMN "kind",
+ DROP COLUMN "memorySizeBytes";
+ END; $$`)
+ }
+}
diff --git a/apps/infra/docs/configuration.md b/apps/infra/docs/configuration.md
index 41baa7f7e..04ffa894f 100644
--- a/apps/infra/docs/configuration.md
+++ b/apps/infra/docs/configuration.md
@@ -145,7 +145,10 @@ Groups in `mstage.env.json` define what each consumer may receive:
`CHECKPOINTS_ENABLED` is an optional `api` key. After deploying a compatible runner,
store `CHECKPOINTS_ENABLED=true` and redeploy the API to enable managed checkpoints.
-The API group forwards this value on AWS and GCP; an omitted key or `false` keeps
+`MEMORY_CHECKPOINTS_ENABLED` is an optional `api` key for full (memory + disk)
+checkpoints. Apply the database migrations and deploy memory-capable runners before
+storing `MEMORY_CHECKPOINTS_ENABLED=true` and redeploying the API. The API group
+forwards both values on AWS and GCP; an omitted key or `false` keeps the corresponding
admission disabled. Changing the stage store alone does not update an existing API revision.
An array group makes every key required. An object distinguishes `required` from `optional`.
diff --git a/apps/infra/mdeploy/stack/index.ts b/apps/infra/mdeploy/stack/index.ts
index 154bf5b4c..069e17a4b 100644
--- a/apps/infra/mdeploy/stack/index.ts
+++ b/apps/infra/mdeploy/stack/index.ts
@@ -472,6 +472,7 @@ export const deployStack = ({
S3_DEFAULT_BUCKET: storage.name,
// Storage may precede runner rollout. Admission requires a separate opt-in.
CHECKPOINTS_ENABLED: inputs.apiEnvironment.CHECKPOINTS_ENABLED ?? 'false',
+ MEMORY_CHECKPOINTS_ENABLED: inputs.apiEnvironment.MEMORY_CHECKPOINTS_ENABLED ?? 'false',
// Supply the archive prefix wherever storage provides the dedicated bucket.
...(storage.checkpoints.active ? { CHECKPOINT_ARCHIVE_PREFIX: storage.checkpoints.archivePrefix } : {}),
}
diff --git a/apps/infra/mdeploy/test/api-environment.test.ts b/apps/infra/mdeploy/test/api-environment.test.ts
index c06b090e5..d95ed1868 100644
--- a/apps/infra/mdeploy/test/api-environment.test.ts
+++ b/apps/infra/mdeploy/test/api-environment.test.ts
@@ -18,33 +18,35 @@ const assemble = (environment: Record<string, string | undefined>, declaration =
apiEnvironmentFrom({ environment, declaration, region: 'ap-southeast-1', stage: 'dev', home: 'aws' })
for (const home of ['aws', 'gcp'] as const) {
- for (const enabled of [undefined, 'false', 'true']) {
- test(`${home} delivers checkpoint admission ${enabled ?? '(unset)'} through the stage API group`, () => {
- const path = new URL('../../mstage.env.json', import.meta.url)
- const declared = parseBase(path.pathname, readFileSync(path, 'utf8'))
- const required = Object.fromEntries(
- declared.envSelectGroup
- .api!.filter((name) => !declared.envOptional.api!.includes(name))
- .map((name) => [name, 'fixture']),
- )
- const selected = valuesOfGroup({
- group: 'api',
- groups: declared.envSelectGroup,
- optional: declared.envOptional.api,
- where: path.pathname,
- values: { ...required, ...(enabled === undefined ? {} : { CHECKPOINTS_ENABLED: enabled }) },
- })
- const { environment, secrets } = apiEnvironmentFrom({
- environment: { ...base, ...selected },
- declaration: { groups: declared.envSelectGroup, optional: declared.envOptional, where: path.pathname },
- region: home === 'aws' ? 'us-east-1' : 'us-east1',
- stage: 'dev',
- home,
+ for (const key of ['CHECKPOINTS_ENABLED', 'MEMORY_CHECKPOINTS_ENABLED'] as const) {
+ for (const enabled of [undefined, 'false', 'true']) {
+ test(`${home} delivers ${key}=${enabled ?? '(unset)'} through the stage API group`, () => {
+ const path = new URL('../../mstage.env.json', import.meta.url)
+ const declared = parseBase(path.pathname, readFileSync(path, 'utf8'))
+ const required = Object.fromEntries(
+ declared.envSelectGroup
+ .api!.filter((name) => !declared.envOptional.api!.includes(name))
+ .map((name) => [name, 'fixture']),
+ )
+ const selected = valuesOfGroup({
+ group: 'api',
+ groups: declared.envSelectGroup,
+ optional: declared.envOptional.api,
+ where: path.pathname,
+ values: { ...required, ...(enabled === undefined ? {} : { [key]: enabled }) },
+ })
+ const { environment, secrets } = apiEnvironmentFrom({
+ environment: { ...base, ...selected },
+ declaration: { groups: declared.envSelectGroup, optional: declared.envOptional, where: path.pathname },
+ region: home === 'aws' ? 'us-east-1' : 'us-east1',
+ stage: 'dev',
+ home,
+ })
+ assert.equal(environment[key], enabled)
+ assert.equal(Object.hasOwn(environment, key), enabled !== undefined)
+ assert.equal(Object.hasOwn(secrets, key), false)
})
- assert.equal(environment.CHECKPOINTS_ENABLED, enabled)
- assert.equal(Object.hasOwn(environment, 'CHECKPOINTS_ENABLED'), enabled !== undefined)
- assert.equal(Object.hasOwn(secrets, 'CHECKPOINTS_ENABLED'), false)
- })
+ }
}
}
diff --git a/apps/infra/mdeploy/test/stack.test.ts b/apps/infra/mdeploy/test/stack.test.ts
index 00e4cff3e..b13d09316 100644
--- a/apps/infra/mdeploy/test/stack.test.ts
+++ b/apps/infra/mdeploy/test/stack.test.ts
@@ -376,6 +376,19 @@ test('checkpoint admission stays off until the API environment explicitly enable
inputs: inputs({ apiEnvironment: enabled === undefined ? {} : { CHECKPOINTS_ENABLED: enabled } }),
})
assert.equal(seen.api.request.environment.CHECKPOINTS_ENABLED, enabled ?? 'false')
+ assert.equal(seen.api.request.environment.MEMORY_CHECKPOINTS_ENABLED, 'false')
+ }
+})
+
+test('memory checkpoint admission stays off until the API environment explicitly enables it', () => {
+ for (const enabled of [undefined, 'false', 'true']) {
+ const { providers, seen } = bundle()
+ deployStack({
+ providers,
+ config,
+ inputs: inputs({ apiEnvironment: enabled === undefined ? {} : { MEMORY_CHECKPOINTS_ENABLED: enabled } }),
+ })
+ assert.equal(seen.api.request.environment.MEMORY_CHECKPOINTS_ENABLED, enabled ?? 'false')
}
})
diff --git a/apps/infra/mstage.env.json b/apps/infra/mstage.env.json
index 643b8ce0a..8b3755fe2 100644
--- a/apps/infra/mstage.env.json
+++ b/apps/infra/mstage.env.json
@@ -120,6 +120,7 @@
"PLATFORM_SUBDOMAIN_MIN_LENGTH",
"DB_POOL_MAX",
"CHECKPOINTS_ENABLED",
+ "MEMORY_CHECKPOINTS_ENABLED",
"FILESTORE_INSTANCES",
"BOXLITE_SYSTEM_SOURCE_REGISTRY_PASSWORD",
"GHCR_USERNAME",
diff --git a/docs/contributing/architecture/platform/api.md b/docs/contributing/architecture/platform/api.md
index 7234f6660..9463f6a98 100644
--- a/docs/contributing/architecture/platform/api.md
+++ b/docs/contributing/architecture/platform/api.md
@@ -88,10 +88,10 @@ disabled. Checkpoint capture and box creation from a checkpoint are a separate c
`checkpoints_enabled` requires both `CHECKPOINTS_ENABLED=true` and a configured
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.
+Hosted `GET /v1/config` reports `memory_checkpoints_enabled: true` only when
+checkpoints are enabled, storage is configured, and `MEMORY_CHECKPOINTS_ENABLED=true`
+(the default is `false`). Full capture and restore also require a runner that
+advertises `memory_checkpoint`.
Private tunnels are enabled. Clients check that capability before every private
prepare.
@@ -796,9 +796,9 @@ writes; returning to a version that ignores valid keys can duplicate effects.
| Method | Path | What it does |
| ------ | ---- | ------------ |
-| `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`. |
+| `POST` | `/v1[/{prefix}]/checkpoints` | Takes `source_box_id`, optional `name`, and optional `kind` (defaults to `disk`). Returns `201` for accepted capture, `409` with `code: "invalid_state"` for a source state mismatch, or `400` with `code: "unsupported"` when full capture is disabled or the source runner lacks `memory_checkpoint`. |
| `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`. |
+| `GET` | `/v1[/{prefix}]/checkpoints/{key}` | Gets checkpoint metadata by ID or name, including state, `kind`, `memory_size_bytes` once known for full captures, 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`. |
| `POST` | `/v1[/{prefix}]/boxes` | With `checkpoint_id`, creates a Box from a checkpoint; returns `201`. |
@@ -808,11 +808,12 @@ 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 Box
from a checkpoint.
-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
+Disk capture requires an idle, stopped source. Full capture requires an idle,
+started source on a memory-capable runner. 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.
+lock before native export. Full restores are routed only to runners with
+`memory_checkpoint`. Turning off memory checkpoint admission blocks new full
+captures and restores without changing access to retained checkpoint metadata.
Capture, creation from a checkpoint, and deletion require `write:boxes`; reads require
organization membership. Turning off checkpoint admission leaves reads, deletion, and
diff --git a/docs/contributing/architecture/platform/schema.md b/docs/contributing/architecture/platform/schema.md
index d6ebcc8fa..9453d2850 100644
--- a/docs/contributing/architecture/platform/schema.md
+++ b/docs/contributing/architecture/platform/schema.md
@@ -907,6 +907,34 @@ Job types: `CREATE_BOX`, `START_BOX`, `STOP_BOX`, `DESTROY_BOX`, `EXPORT_BOX`,
**Indexes:** `(runnerId, status)` · `(status, createdAt)` ·
`(resourceType, resourceId)`.
+### `checkpoint`
+
+Durable metadata for captured Box checkpoints, independent of the source Box's
+lifetime. Created by `1793923200000-add-checkpoints-migration.ts` and extended
+by `1795564800000-add-checkpoint-kind-migration.ts`.
+
+| Column | Type | Notes |
+| ------ | ---- | ----- |
+| `id` | `uuid` | primary key |
+| `organizationId` | `uuid` | |
+| `name` | `character varying` | unique per organization |
+| `sourceBoxId` | `character varying` | historical source identity; no FK |
+| `sourceRunnerId` | `uuid` | |
+| `sourceState` | `character varying` | source Box state at capture |
+| `state` | `character varying` | `creating` \| `ready` \| `failed` \| `deleting`, default `creating` |
+| `kind` | `character varying` | `disk` \| `full`, default `disk`; check-constrained |
+| `memorySizeBytes` | `bigint` | nullable; check-constrained `>= 0`; populated for `full` checkpoints |
+| `arcPath` | `character varying` | object store URI |
+| `exportJobId` / `activeJobId` | `uuid` | nullable; `activeJobId` has a partial unique index when non-null |
+| `environment` / `archive` | `jsonb` | captured Box environment and immutable export artifact metadata |
+| `errorReason` | `text` | nullable |
+| `createdAt` / `updatedAt` | `timestamptz` | |
+
+The migration defaults existing checkpoints to `disk`. An accepted full export
+records its memory size both in `memorySizeBytes` and in the archive JSON; disk
+archives omit it. Reverting the migration locks the table and refuses rollback if
+any row has `kind = 'full'`.
+
### `box_migration`
A box in flight between runners, one row per box being moved. The row _is_ the