feat(sandbox): cache the guest image at startup instead of on first command

Pull the configured guest image in the background when the Manager boots and
when sandbox enforcement is switched on, so a sandboxed command no longer
pays the multi-gigabyte download. msb pull is a no-op once cached, startup is
never blocked by it, and a command racing the pull joins the same in-flight
boot.
This commit is contained in:
Chris Scott committed 2026-08-28 13:05:56 -04:00
1 parent 5beb3432d4
commit 2eba81d524
8 files changed
+82 -12

No files matched your search

+3 -5
View File
@@ -296,11 +296,9 @@ try {
opencodeServerManager.setDatabase(db)
detectSandboxCapability()
try {
await new SandboxRuntimeService(db).provisionWorkspaceSandboxOnBoot()
} catch (error) {
logger.warn('Workspace sandbox provisioning skipped:', error)
}
void new SandboxRuntimeService(db).prepareWorkspaceSandboxOnBoot().catch((error) => {
logger.warn('Workspace sandbox preparation failed:', error)
})
const openCodeStatus = await openCodeSupervisor.start()
if (openCodeStatus.healthy) {
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
@@ -414,6 +414,11 @@ class OpenCodeServerManager {
this.failNonRecoverable(`Failed to stop the workspace sandbox while disabling enforcement: ${error instanceof Error ? error.message : String(error)}`)
}
}
if (sandboxEnforced && !this.sandboxEnforced) {
void new SandboxRuntimeService(this.db).prepareWorkspaceSandboxOnBoot().catch((error) => {
logger.warn('Sandbox enforcement enabled but preparing the guest image failed:', error)
})
}
logger.info(`OpenCode sandbox enforcement: ${sandboxEnforced ? 'enabled' : 'disabled'}`)
}
+4
View File
@@ -120,6 +120,10 @@ export function buildSandboxVersionArgs(): string[] {
return ['--version']
}
export function buildSandboxPullArgs(): string[] {
return ['pull', ENV.SANDBOX.IMAGE]
}
export function sandboxMountRoots(): string[] {
return [getReposPath(), getScheduleWorktreesPath()]
}
+11 -1
View File
@@ -16,6 +16,7 @@ import {
buildSandboxInspectArgs,
buildSandboxListArgs,
buildSandboxProvisionArgs,
buildSandboxPullArgs,
buildSandboxRemoveArgs,
buildSandboxStartArgs,
buildSandboxStopManagedArgs,
@@ -542,6 +543,14 @@ async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestat
return await attestWorkspaceSandboxConfig(outcome.record.config)
}
async function cacheSandboxImage(): Promise<void> {
logger.info(`Caching the sandbox guest image ${ENV.SANDBOX.IMAGE}`)
await executeCommand([sandboxExecutablePath(), ...buildSandboxPullArgs()], {
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
})
logger.info(`Sandbox guest image ${ENV.SANDBOX.IMAGE} is cached`)
}
async function provisionSandboxExecUserPasswd(): Promise<void> {
const provisionArgs = buildSandboxProvisionArgs()
if (provisionArgs.length === 0) {
@@ -649,11 +658,12 @@ async function startWorkspaceSandbox(): Promise<void> {
export class SandboxRuntimeService {
constructor(private readonly db: Database) {}
async provisionWorkspaceSandboxOnBoot(): Promise<void> {
async prepareWorkspaceSandboxOnBoot(): Promise<void> {
if (!this.isSandboxEnabled()) return
const capability = detectSandboxCapability()
if (!capability.available) return
if (getProcessIdentityAttestationError() !== null) return
await cacheSandboxImage()
if (buildSandboxProvisionArgs().length === 0) return
const entry = findWorkspaceSandboxEntry(await listSandboxes())
if (entry === null || !entry.running) return
@@ -104,11 +104,17 @@ const sandboxRuntimeServiceMock = vi.hoisted(() => ({
SandboxRuntimeService: vi.fn<() => {
isEnabled: () => boolean
stopWorkspaceSandboxForToggle?: () => Promise<void>
prepareWorkspaceSandboxOnBoot?: () => Promise<void>
}>(() => ({ isEnabled: () => false })),
}))
vi.mock('../../src/services/sandbox/runtime', () => ({
SandboxRuntimeService: sandboxRuntimeServiceMock.SandboxRuntimeService,
SandboxRuntimeService: function SandboxRuntimeServiceStub() {
return {
prepareWorkspaceSandboxOnBoot: async () => undefined,
...sandboxRuntimeServiceMock.SandboxRuntimeService(),
}
},
}))
import { promises as fs, accessSync, readdirSync } from 'fs'
@@ -13,6 +13,7 @@ import {
buildSandboxInspectArgs,
buildSandboxListArgs,
buildSandboxProvisionArgs,
buildSandboxPullArgs,
buildSandboxRemoveArgs,
buildSandboxStartArgs,
buildSandboxStopManagedArgs,
@@ -36,6 +37,10 @@ describe('sandbox command builders', () => {
expect(buildSandboxVersionArgs()).toEqual(['--version'])
})
it('builds pull args for the configured guest image', () => {
expect(buildSandboxPullArgs()).toEqual(['pull', ENV.SANDBOX.IMAGE])
})
it('builds inspect args targeting the shared workspace sandbox with JSON output', () => {
expect(buildSandboxInspectArgs()).toEqual(['inspect', WORKSPACE_SANDBOX_NAME, '--format', 'json'])
})
+45 -3
View File
@@ -351,7 +351,7 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
await service.provisionWorkspaceSandboxOnBoot()
await service.prepareWorkspaceSandboxOnBoot()
const provisionCall = mockExecuteCommand.mock.calls.find((call) => call[0].includes('exec'))
expect(provisionCall).toBeDefined()
@@ -364,7 +364,7 @@ describe('SandboxRuntimeService', () => {
throw new Error('msb must not be invoked when sandboxing is disabled')
})
await service.provisionWorkspaceSandboxOnBoot()
await service.prepareWorkspaceSandboxOnBoot()
expect(mockExecuteCommand).not.toHaveBeenCalled()
})
@@ -378,11 +378,53 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
await service.provisionWorkspaceSandboxOnBoot()
await service.prepareWorkspaceSandboxOnBoot()
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('exec'))).toHaveLength(0)
})
it('caches the guest image at boot before touching the microVM', async () => {
enableEnforcement()
mockExecuteCommand.mockImplementation(async (args: string[]) => {
if (args.includes('ls')) {
return { exitCode: 0, stdout: stoppedListingOutput(), stderr: '' }
}
return { exitCode: 0, stdout: '', stderr: '' }
})
await service.prepareWorkspaceSandboxOnBoot()
expect(mockExecuteCommand).toHaveBeenCalledWith(
[sandboxExecutablePath(), 'pull', ENV.SANDBOX.IMAGE],
expect.objectContaining({ timeout: ENV.SANDBOX.START_TIMEOUT_MS }),
)
const pullIndex = mockExecuteCommand.mock.calls.findIndex((call) => call[0].includes('pull'))
const listIndex = mockExecuteCommand.mock.calls.findIndex((call) => call[0].includes('ls'))
expect(pullIndex).toBeGreaterThanOrEqual(0)
expect(pullIndex).toBeLessThan(listIndex)
})
it('never pulls the guest image at boot when the sandbox preference is off', async () => {
mockExecuteCommand.mockImplementation(async () => ({ exitCode: 0, stdout: '', stderr: '' }))
await service.prepareWorkspaceSandboxOnBoot()
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('pull'))).toHaveLength(0)
})
it('surfaces a failed boot image pull to the caller', async () => {
enableEnforcement()
mockExecuteCommand.mockImplementation(async (args: string[]) => {
if (args.includes('pull')) {
throw new Error('msb pull failed: registry unreachable')
}
return { exitCode: 0, stdout: '', stderr: '' }
})
await expect(service.prepareWorkspaceSandboxOnBoot()).rejects.toThrow('registry unreachable')
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(0)
})
it('returns blocked with the start stderr when a stopped sandbox fails to start', async () => {
enableEnforcement()
mockExecuteCommand.mockImplementation(async (args: string[]) => {
+2 -2
View File
@@ -191,7 +191,7 @@ The guest runs every command as a numeric host uid that has no `/etc/passwd` ent
Chromium launches headless as the non-root exec user without extra flags. If your host kernel restricts user namespaces so Chromium's own sandbox fails, pass `--no-sandbox` — the microVM is already the isolation boundary.
The image is over 3 GB against a 1.6 GB `node:24` baseline, almost entirely Chromium and its dependencies. The first pull is bounded by `SANDBOX_START_TIMEOUT_MS`; raise it on slow links.
The image is over 3 GB against a 1.6 GB `node:24` baseline, almost entirely Chromium and its dependencies. The Manager caches it ahead of first use: at startup, and whenever sandbox enforcement is switched on, it runs `msb pull` in the background (bounded by `SANDBOX_START_TIMEOUT_MS`; raise it on slow links). The pull is a no-op once the image is cached, and `docker-compose.sandbox.yml` persists the microsandbox store in the `microsandbox-data` volume so the download survives container replacement. Because it runs in the background, server startup is never blocked by it, and a sandboxed command issued while the pull is still running joins the same in-flight boot instead of starting a second download.
### Using your own image
@@ -210,7 +210,7 @@ Override the Playwright version at build time with `--build-arg PLAYWRIGHT_VERSI
## Caveats
- The first command pays image pull and microVM boot latency, bounded by `SANDBOX_START_TIMEOUT_MS`.
- The first command pays microVM boot latency, bounded by `SANDBOX_START_TIMEOUT_MS`. The guest image itself is pulled in the background at startup, so it only pays a download too if it runs before that pull finishes.
- `SANDBOX_IMAGE` must contain every tool the agent expects to run.
- `SANDBOX_EXEC_USER` must match the workspace owner so commands can write mounted files.
- A `shell` the user configured does not apply to slash-command shell templates while enforcement is on, and is bypassed for `!command` shell mode because that surface is routed into the microVM.