feat(sandbox): remove session VMs when the sandbox is turned off or idle

Turning a session's sandbox off now removes its microVM and Docker data volume in the background. The idle sweep removes idle session VMs instead of stopping them, covering stopped VMs and VMs left from before a Manager restart, and starts when the Manager boots. Removal is serialized against boots so a command planned during a removal gets a fresh VM.
This commit is contained in:
Chris Scott committed 2026-10-15 16:53:49 -04:00
1 parent 493a51f803
commit 1d001bc43e
6 files changed
+390 -52

No files matched your search

+55 -27
View File
@@ -78,6 +78,7 @@ export type SandboxStatus = {
type VmState = {
inFlightBoot: Promise<void> | null
inFlightRemoval: Promise<void> | null
lastKnownRunningAt: number | null
lastUsedAt: number
inFlightProvision: Promise<void> | null
@@ -90,6 +91,7 @@ const vmStates = new Map<string, VmState>()
let shutdownRequested = false
let stopInProgress = false
let idleSweepTimer: ReturnType<typeof setInterval> | null = null
let idleSweepStartedAt = 0
let startAdmission: Promise<void> = Promise.resolve()
function vmState(name: string): VmState {
@@ -97,6 +99,7 @@ function vmState(name: string): VmState {
if (existing !== undefined) return existing
const created: VmState = {
inFlightBoot: null,
inFlightRemoval: null,
lastKnownRunningAt: null,
lastUsedAt: 0,
inFlightProvision: null,
@@ -113,10 +116,12 @@ export function resetSandboxRuntimeState(): void {
state.backgroundProvisionRetry = null
state.inFlightProvision = null
state.inFlightBoot = null
state.inFlightRemoval = null
}
vmStates.clear()
shutdownRequested = false
stopInProgress = false
idleSweepStartedAt = 0
if (idleSweepTimer !== null) {
clearInterval(idleSweepTimer)
idleSweepTimer = null
@@ -161,6 +166,10 @@ function ensureSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): Promi
if (shutdownRequested || stopInProgress) {
throw new Error('sandbox shutdown is in progress; refusing to boot the session sandbox')
}
const inFlightRemoval = state.inFlightRemoval
if (inFlightRemoval !== null) {
await inFlightRemoval.catch(() => undefined)
}
if (state.lastKnownRunningAt !== null && Date.now() - state.lastKnownRunningAt < SANDBOX_LS_CACHE_MS) {
return
}
@@ -834,6 +843,29 @@ async function removeSessionSandboxVm(name: string): Promise<void> {
await runSandboxRemoval(buildSandboxRemoveArgs(name), SANDBOX_REMOVAL_MISSING_PATTERN, 'msb rm')
}
function removeSandboxVmAndVolume(name: string): Promise<void> {
const state = vmState(name)
if (state.inFlightRemoval !== null) {
return state.inFlightRemoval
}
const inFlightBoot = state.inFlightBoot
state.inFlightRemoval = (async () => {
if (inFlightBoot !== null) {
await inFlightBoot.catch(() => undefined)
}
await removeSessionSandboxVm(name)
await runSandboxRemoval(
buildSandboxVolumeRemoveArgs(sandboxDockerDataVolumeName(name)),
SANDBOX_VOLUME_REMOVAL_MISSING_PATTERN,
'msb volume rm',
)
state.lastKnownRunningAt = null
})().finally(() => {
state.inFlightRemoval = null
})
return state.inFlightRemoval
}
async function runSandboxRemoval(args: string[], missingPattern: RegExp, label: string): Promise<void> {
const result = (await executeCommand([sandboxExecutablePath(), ...args], {
ignoreExitCode: true,
@@ -970,6 +1002,7 @@ async function admitVmStart(name: string, maxRunningVms: number): Promise<void>
function ensureIdleSweepStarted(db: Database): void {
if (idleSweepTimer !== null) return
idleSweepStartedAt = Date.now()
idleSweepTimer = setInterval(() => {
void sweepIdleSandboxes(db)
}, SANDBOX_IDLE_SWEEP_INTERVAL_MS)
@@ -981,23 +1014,28 @@ async function sweepIdleSandboxes(db: Database): Promise<void> {
if (shutdownRequested || stopInProgress) return
const idleStopMinutes = sandboxIdleStopMinutes(db)
const threshold = Math.max(idleStopMinutes * 60000, ENV.SANDBOX.EXEC_TIMEOUT_MS)
for (const [name, state] of vmStates) {
if (state.inFlightBoot !== null) continue
if (state.lastKnownRunningAt === null) continue
if (Date.now() - state.lastUsedAt < threshold) continue
let entries: SandboxLsEntry[]
try {
entries = await listSandboxes()
} catch (error) {
logger.warn(`Failed to list sandboxes for the idle sweep: ${error instanceof Error ? error.message : String(error)}`)
return
}
for (const value of entries) {
if (shutdownRequested || stopInProgress) return
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
const entry = value as SandboxLsEntry
const name = entry.name
if (typeof name !== 'string' || !SESSION_SANDBOX_NAME_PATTERN.test(name)) continue
const state = vmStates.get(name)
if (state !== undefined && (state.inFlightBoot !== null || state.inFlightRemoval !== null)) continue
const lastActivity = Math.max(state?.lastUsedAt ?? 0, idleSweepStartedAt)
if (Date.now() - lastActivity < threshold) continue
try {
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStopArgs(name)], {
ignoreExitCode: true,
timeout: SANDBOX_STOP_TIMEOUT_MS,
})) as string | { exitCode: number; stdout: string; stderr: string }
const stopResult = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
if (stopResult.exitCode !== 0) {
logger.warn(`Failed to stop idle sandbox ${name} with code ${stopResult.exitCode}: ${stopResult.stderr || stopResult.stdout}`)
continue
}
state.lastKnownRunningAt = null
await removeSandboxVmAndVolume(name)
logger.info(`Removed idle sandbox ${name} and its Docker data volume`)
} catch (error) {
logger.warn(`Failed to stop idle sandbox ${name}: ${error instanceof Error ? error.message : String(error)}`)
logger.warn(`Failed to remove idle sandbox ${name}: ${error instanceof Error ? error.message : String(error)}`)
}
}
}
@@ -1018,6 +1056,7 @@ export class SandboxRuntimeService {
const capability = detectSandboxCapability()
if (!capability.available) return
if (getProcessIdentityAttestationError() !== null) return
ensureIdleSweepStarted(this.db)
await cacheSandboxImage()
}
@@ -1090,18 +1129,7 @@ export class SandboxRuntimeService {
}
async removeSessionSandbox(rootSessionId: string): Promise<void> {
const name = sessionSandboxName(rootSessionId)
const state = vmStates.get(name)
if (state?.inFlightBoot) {
await state.inFlightBoot.catch(() => undefined)
}
await removeSessionSandboxVm(name)
await runSandboxRemoval(
buildSandboxVolumeRemoveArgs(sandboxDockerDataVolumeName(name)),
SANDBOX_VOLUME_REMOVAL_MISSING_PATTERN,
'msb volume rm',
)
vmStates.delete(name)
await removeSandboxVmAndVolume(sessionSandboxName(rootSessionId))
}
async stopAllSandboxes(): Promise<void> {
+13 -5
View File
@@ -65,11 +65,7 @@ export class SessionSandboxService {
const { sessionID } = event.data
this.ancestry.forget(sessionID)
if (getSessionSandboxMode(this.db, sessionID) !== null && this.sandboxSupported()) {
void this.sandboxes.removeSessionSandbox(sessionID).catch((error) => {
logger.warn(
`Failed to remove the sandbox microVM for deleted session ${sessionID}: ${error instanceof Error ? error.message : String(error)}`,
)
})
this.removeSandboxInBackground(sessionID, `deleted session ${sessionID}`)
}
deleteSessionSandboxMode(this.db, sessionID)
return
@@ -147,6 +143,10 @@ export class SessionSandboxService {
}
})()
if (request.sandboxed === false && available) {
this.removeSandboxInBackground(sessionId, `session ${sessionId} after its sandbox was turned off`)
}
return this.getState(sessionId)
}
@@ -159,6 +159,14 @@ export class SessionSandboxService {
}
}
private removeSandboxInBackground(rootSessionId: string, reason: string): void {
void this.sandboxes.removeSessionSandbox(rootSessionId).catch((error) => {
logger.warn(
`Failed to remove the sandbox microVM for ${reason}: ${error instanceof Error ? error.message : String(error)}`,
)
})
}
private async resolveParentRootRow(parentId: string): Promise<SessionSandboxModeRow | null> {
let rootSessionId: string
try {
+223 -13
View File
@@ -1030,48 +1030,258 @@ describe('SandboxRuntimeService', () => {
expect(vms.has(OTHER_VM_NAME)).toBe(false)
})
it('stops an idle VM from the sweep and restarts it on the next plan', async () => {
it('removes an idle running VM and its Docker data volume from the sweep and boots a fresh VM on the next plan', async () => {
vi.useFakeTimers()
try {
enableEnforcement()
installFakeMsb(new Map([[VM_NAME, vm()]]))
const vms = new Map<string, FakeVm>([[VM_NAME, vm()]])
installFakeMsb(vms)
const first = await service.planShell(repoADir, shellTarget(repoADir))
expect(first).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir })
await vi.advanceTimersByTimeAsync(31 * 60 * 1000)
expect(msbCalls('rm')).toHaveLength(1)
expect(mockExecuteCommand).toHaveBeenCalledWith(
[sandboxExecutablePath(), ...buildSandboxStopArgs(VM_NAME)],
[sandboxExecutablePath(), 'volume', 'rm', sandboxDockerDataVolumeName(VM_NAME)],
expect.objectContaining({ ignoreExitCode: true }),
)
expect(vms.has(VM_NAME)).toBe(false)
expect(logger.info).toHaveBeenCalledWith(`Removed idle sandbox ${VM_NAME} and its Docker data volume`)
const stopsBefore = msbCalls('stop').length
const restarted = await service.planShell(repoADir, shellTarget(repoADir))
expect(restarted).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir })
expect(msbCalls('stop').length).toBe(stopsBefore)
expect(msbCalls('start').length).toBeGreaterThan(0)
const recreated = await service.planShell(repoADir, shellTarget(repoADir))
expect(recreated).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir })
expect(msbCalls('run')).toHaveLength(1)
} finally {
vi.useRealTimers()
}
})
it('logs a warning when the idle sweep stop fails', async () => {
it('removes a session VM that the running cap stopped once it is idle', async () => {
vi.useFakeTimers()
try {
settingsService.updateSettings({ sandbox: { enabled: true, maxRunningVms: 1 } })
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.6.15' })
const vms = new Map<string, FakeVm>([
[VM_NAME, vm({ projectMounts: [repoADir] })],
[OTHER_VM_NAME, vm({ projectMounts: [repoBDir], rootSessionId: OTHER_ROOT_SESSION, running: false })],
])
installFakeMsb(vms)
await service.planShell(repoADir, shellTarget(repoADir))
await vi.advanceTimersByTimeAsync(ENV.SANDBOX.EXEC_TIMEOUT_MS)
const second = await service.planShell(repoBDir, {
rootSessionId: OTHER_ROOT_SESSION,
locationDirectory: repoBDir,
resources: defaultResources(),
})
expect(second).toEqual({ mode: 'sandbox', name: OTHER_VM_NAME, workdir: repoBDir })
expect(vms.get(VM_NAME)?.running).toBe(false)
await vi.advanceTimersByTimeAsync(21 * 60 * 1000)
expect(vms.has(VM_NAME)).toBe(false)
expect(vms.has(OTHER_VM_NAME)).toBe(true)
} finally {
vi.useRealTimers()
}
})
it('removes an untracked session VM only after the threshold from the sweep start and never a non-session VM', async () => {
vi.useFakeTimers()
try {
enableEnforcement()
installFakeMsb(new Map([[VM_NAME, vm()]]))
const vms = new Map<string, FakeVm>([
[VM_NAME, vm()],
['ocm-workspace', vm()],
])
installFakeMsb(vms)
await service.prepareSandboxOnBoot()
await vi.advanceTimersByTimeAsync(20 * 60 * 1000)
expect(vms.has(VM_NAME)).toBe(true)
expect(vms.has('ocm-workspace')).toBe(true)
expect(msbCalls('rm')).toHaveLength(0)
await vi.advanceTimersByTimeAsync(11 * 60 * 1000)
expect(vms.has(VM_NAME)).toBe(false)
expect(vms.has('ocm-workspace')).toBe(true)
} finally {
vi.useRealTimers()
}
})
it('does not remove a VM used within the idle threshold', async () => {
vi.useFakeTimers()
try {
enableEnforcement()
const vms = new Map<string, FakeVm>([[VM_NAME, vm()]])
installFakeMsb(vms)
await service.planShell(repoADir, shellTarget(repoADir))
await vi.advanceTimersByTimeAsync(29 * 60 * 1000)
expect(vms.has(VM_NAME)).toBe(true)
expect(msbCalls('rm')).toHaveLength(0)
} finally {
vi.useRealTimers()
}
})
it('skips a VM with an in-flight boot during the idle sweep', async () => {
vi.useFakeTimers()
try {
enableEnforcement()
const vms = new Map<string, FakeVm>([[VM_NAME, vm()]])
installFakeMsb(vms)
await service.prepareSandboxOnBoot()
let releaseInspect: () => void = () => {}
const inspectGate = new Promise<void>((resolve) => {
releaseInspect = resolve
})
let notifyInspect: () => void = () => {}
const inspectEntered = new Promise<void>((resolve) => {
notifyInspect = resolve
})
const baseHandler = execHandler
execHandler = (args) => {
if (args[1] === 'stop') return { exitCode: 1, stdout: '', stderr: 'failed to stop vm' }
execHandler = async (args) => {
if (args[1] === 'inspect') {
notifyInspect()
await inspectGate
}
return baseHandler(args)
}
const planning = service.planShell(repoADir, shellTarget(repoADir))
await inspectEntered
await vi.advanceTimersByTimeAsync(31 * 60 * 1000)
expect(vms.has(VM_NAME)).toBe(true)
expect(msbCalls('rm')).toHaveLength(0)
releaseInspect()
const plan = await planning
expect(plan).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir })
} finally {
vi.useRealTimers()
}
})
it('logs a warning and continues the sweep when a removal fails', async () => {
vi.useFakeTimers()
try {
enableEnforcement()
const vms = new Map<string, FakeVm>([
[VM_NAME, vm()],
[OTHER_VM_NAME, vm({ projectMounts: [repoBDir], rootSessionId: OTHER_ROOT_SESSION })],
])
installFakeMsb(vms)
const baseHandler = execHandler
execHandler = (args) => {
if (args[1] === 'rm' && args[args.length - 1] === VM_NAME) {
return { exitCode: 1, stdout: '', stderr: 'operation not permitted' }
}
return baseHandler(args)
}
await service.prepareSandboxOnBoot()
await vi.advanceTimersByTimeAsync(31 * 60 * 1000)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('Failed to stop idle sandbox'))
expect(logger.warn).toHaveBeenCalledWith(
`Failed to remove idle sandbox ${VM_NAME}: msb rm failed with code 1: operation not permitted`,
)
expect(vms.has(OTHER_VM_NAME)).toBe(false)
expect(vms.has(VM_NAME)).toBe(true)
} finally {
vi.useRealTimers()
}
})
it('logs a warning when the idle sweep cannot list sandboxes', async () => {
vi.useFakeTimers()
try {
enableEnforcement()
installFakeMsb(new Map(), { lsError: 'failed to connect to supervisor' })
await service.prepareSandboxOnBoot()
await vi.advanceTimersByTimeAsync(31 * 60 * 1000)
expect(logger.warn).toHaveBeenCalledWith(
'Failed to list sandboxes for the idle sweep: msb ls failed with code 1: failed to connect to supervisor',
)
expect(msbCalls('rm')).toHaveLength(0)
} finally {
vi.useRealTimers()
}
})
it('waits for an in-flight removal before booting a fresh VM on the next plan', async () => {
enableEnforcement()
const vms = new Map<string, FakeVm>([[VM_NAME, vm()]])
installFakeMsb(vms)
const first = await service.planShell(repoADir, shellTarget(repoADir))
expect(first).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir })
let releaseRm: () => void = () => {}
const rmGate = new Promise<void>((resolve) => {
releaseRm = resolve
})
let notifyRm: () => void = () => {}
const rmEntered = new Promise<void>((resolve) => {
notifyRm = resolve
})
const baseHandler = execHandler
execHandler = async (args) => {
if (args[1] === 'rm') {
notifyRm()
await rmGate
}
return baseHandler(args)
}
const removal = service.removeSessionSandbox(ROOT_SESSION)
await rmEntered
const planning = service.planShell(repoADir, shellTarget(repoADir))
await new Promise((resolve) => setTimeout(resolve, 0))
releaseRm()
const plan = await planning
await removal
expect(plan).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir })
expect(vms.has(VM_NAME)).toBe(true)
expect(msbCalls('rm')).toHaveLength(1)
expect(msbCalls('run')).toHaveLength(1)
})
it('runs a single removal when the same VM is removed concurrently', async () => {
installFakeMsb(new Map<string, FakeVm>([[VM_NAME, vm()]]))
const first = service.removeSessionSandbox(ROOT_SESSION)
const second = service.removeSessionSandbox(ROOT_SESSION)
await Promise.all([first, second])
expect(msbCalls('rm')).toHaveLength(1)
expect(msbCalls('volume')).toHaveLength(1)
})
it('starts the idle sweep at boot so a stale sandbox is removed without a plan', async () => {
vi.useFakeTimers()
try {
enableEnforcement()
const vms = new Map<string, FakeVm>([[VM_NAME, vm()]])
installFakeMsb(vms)
await service.prepareSandboxOnBoot()
await vi.advanceTimersByTimeAsync(31 * 60 * 1000)
expect(vms.has(VM_NAME)).toBe(false)
expect(logger.info).toHaveBeenCalledWith(`Removed idle sandbox ${VM_NAME} and its Docker data volume`)
} finally {
vi.useRealTimers()
}
@@ -370,6 +370,97 @@ describe('SessionSandboxService', () => {
}
})
it('removes the sandbox microVM when sandboxing is turned off and returns the updated state', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', true)
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await expect(service.update('ses_root', { sandboxed: false })).resolves.toMatchObject({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'user',
available: true,
})
await vi.waitFor(() => {
expect(removed).toEqual(['ses_root'])
})
})
it('does not remove the sandbox microVM when sandboxing is turned on', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await service.update('ses_root', { sandboxed: true })
expect(removed).toEqual([])
})
it('does not remove the sandbox microVM for a resources-only update', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await service.update('ses_root', { resources: { cpus: 4, memoryMib: 8192 } })
expect(removed).toEqual([])
})
it('logs and swallows a failure while removing the sandbox after it is turned off', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', true)
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined)
try {
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async () => {
throw new Error('msb rm failed')
},
})
await expect(service.update('ses_root', { sandboxed: false })).resolves.toMatchObject({ sandboxed: false })
await vi.waitFor(() => {
expect(warn).toHaveBeenCalledWith(expect.stringContaining('msb rm failed'))
})
expect(warn).toHaveBeenCalledWith(expect.stringContaining('ses_root'))
expect(warn).toHaveBeenCalledWith(expect.stringContaining('turned off'))
} finally {
warn.mockRestore()
}
})
it('does not remove the sandbox microVM when sandboxing is turned off and support is disabled', async () => {
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), new SettingsService(db), {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await expect(service.update('ses_root', { sandboxed: false })).resolves.toMatchObject({
sandboxed: false,
available: false,
})
expect(removed).toEqual([])
})
it('rejects updating a child session with 400', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
@@ -254,7 +254,7 @@ describe('SandboxSettings', () => {
expect(screen.getByLabelText('Default CPUs')).toBeInTheDocument()
expect(screen.getByLabelText('Default memory (GiB)')).toBeInTheDocument()
expect(screen.getByLabelText('Stop idle sandbox VMs after (minutes)')).toBeInTheDocument()
expect(screen.getByLabelText('Remove idle sandbox VMs after (minutes)')).toBeInTheDocument()
expect(screen.getByLabelText('Max running sandbox VMs')).toBeInTheDocument()
})
@@ -144,7 +144,7 @@ export function SandboxSettings() {
}))
return
}
void saveSandbox({ idleStopMinutes: value }, 'Idle stop timeout saved')
void saveSandbox({ idleStopMinutes: value }, 'Idle removal timeout saved')
}
const commitMaxRunningVms = () => {
@@ -278,7 +278,7 @@ export function SandboxSettings() {
<div className="flex items-center justify-between gap-3 border-t pt-3">
<Label htmlFor="sandboxIdleStopMinutes" className="min-w-0 text-sm font-semibold">
Stop idle sandbox VMs after (minutes)
Remove idle sandbox VMs after (minutes)
</Label>
<Input
id="sandboxIdleStopMinutes"
@@ -315,10 +315,11 @@ export function SandboxSettings() {
</div>
<p className="text-xs text-muted-foreground @min-[1000px]:col-span-2">
Each sandboxed session gets its own microVM that mounts only that session's repository. Idle VMs stop
automatically and restart on the next command; at most {helperMaxRunningVms} run at once. CPU and
memory changes apply on the session's next sandboxed command and recreate its VM (the Docker data
volume is kept).
Each sandboxed session gets its own microVM that mounts only that session's repository. A VM unused
for this long, or whose session's sandbox is turned off, is removed together with its Docker data, so
installed packages and Docker images are lost; the next sandboxed command creates a fresh VM. At most{' '}
{helperMaxRunningVms} run at once. CPU and memory changes apply on the session's next sandboxed command
and recreate its VM (the Docker data volume is kept).
</p>
</>
)}