From 2eba81d524969d2e5c8af23d33362c9ff3eff131 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Fri, 28 Aug 2026 13:05:56 -0400 Subject: [PATCH] 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. --- backend/src/index.ts | 8 ++-- .../src/services/opencode-single-server.ts | 5 ++ backend/src/services/sandbox/command.ts | 4 ++ backend/src/services/sandbox/runtime.ts | 12 ++++- .../services/opencode-single-server.test.ts | 8 +++- backend/test/services/sandbox/command.test.ts | 5 ++ backend/test/services/sandbox/runtime.test.ts | 48 +++++++++++++++++-- docs/features/sandboxing.md | 4 +- 8 files changed, 82 insertions(+), 12 deletions(-) diff --git a/backend/src/index.ts b/backend/src/index.ts index 9b3f008b..ddbc7784 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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}`) diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 9f2796f5..df7a28e6 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -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'}`) } diff --git a/backend/src/services/sandbox/command.ts b/backend/src/services/sandbox/command.ts index 1bb406c2..54a2a7ea 100644 --- a/backend/src/services/sandbox/command.ts +++ b/backend/src/services/sandbox/command.ts @@ -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()] } diff --git a/backend/src/services/sandbox/runtime.ts b/backend/src/services/sandbox/runtime.ts index 9a1324d7..1d4aa772 100644 --- a/backend/src/services/sandbox/runtime.ts +++ b/backend/src/services/sandbox/runtime.ts @@ -16,6 +16,7 @@ import { buildSandboxInspectArgs, buildSandboxListArgs, buildSandboxProvisionArgs, + buildSandboxPullArgs, buildSandboxRemoveArgs, buildSandboxStartArgs, buildSandboxStopManagedArgs, @@ -542,6 +543,14 @@ async function attestWorkspaceSandbox(running: boolean): Promise { + 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 { const provisionArgs = buildSandboxProvisionArgs() if (provisionArgs.length === 0) { @@ -649,11 +658,12 @@ async function startWorkspaceSandbox(): Promise { export class SandboxRuntimeService { constructor(private readonly db: Database) {} - async provisionWorkspaceSandboxOnBoot(): Promise { + async prepareWorkspaceSandboxOnBoot(): Promise { 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 diff --git a/backend/test/services/opencode-single-server.test.ts b/backend/test/services/opencode-single-server.test.ts index e5a40649..7cb0315e 100644 --- a/backend/test/services/opencode-single-server.test.ts +++ b/backend/test/services/opencode-single-server.test.ts @@ -104,11 +104,17 @@ const sandboxRuntimeServiceMock = vi.hoisted(() => ({ SandboxRuntimeService: vi.fn<() => { isEnabled: () => boolean stopWorkspaceSandboxForToggle?: () => Promise + prepareWorkspaceSandboxOnBoot?: () => Promise }>(() => ({ 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' diff --git a/backend/test/services/sandbox/command.test.ts b/backend/test/services/sandbox/command.test.ts index 80944cb1..1f7ce444 100644 --- a/backend/test/services/sandbox/command.test.ts +++ b/backend/test/services/sandbox/command.test.ts @@ -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']) }) diff --git a/backend/test/services/sandbox/runtime.test.ts b/backend/test/services/sandbox/runtime.test.ts index 5dea8baf..967b7943 100644 --- a/backend/test/services/sandbox/runtime.test.ts +++ b/backend/test/services/sandbox/runtime.test.ts @@ -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[]) => { diff --git a/docs/features/sandboxing.md b/docs/features/sandboxing.md index 5dd7240b..f916b6cf 100644 --- a/docs/features/sandboxing.md +++ b/docs/features/sandboxing.md @@ -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.