From 27c673d8301e1313e6cd6b9293b529e8e29a610f Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:17:23 -0400 Subject: [PATCH] fix(sandbox): recreate orphaned microVMs with --replace A session VM create that fails partway leaves an orphaned msb sandbox that msb ls omits but every later create rejects as already existing, so the session could never get a VM again. Retry the create once with --replace when msb reports the name already exists. --- backend/src/services/sandbox/command.ts | 3 +- backend/src/services/sandbox/runtime.ts | 30 ++++++-- backend/test/services/sandbox/command.test.ts | 28 ++++++++ backend/test/services/sandbox/runtime.test.ts | 68 +++++++++++++++++++ 4 files changed, 123 insertions(+), 6 deletions(-) diff --git a/backend/src/services/sandbox/command.ts b/backend/src/services/sandbox/command.ts index ba90181f..27ec59dc 100644 --- a/backend/src/services/sandbox/command.ts +++ b/backend/src/services/sandbox/command.ts @@ -214,7 +214,7 @@ function parseSandboxNamedMountSpec(spec: string): { name: string; guest: string return { name, guest } } -export function buildSandboxCreateArgs(spec: SandboxVmSpec): string[] { +export function buildSandboxCreateArgs(spec: SandboxVmSpec, options: { replace?: boolean } = {}): string[] { const tmpfsSizeMib = resolveSandboxRuntimeTmpfsSizeMib(spec.memoryMib) if (tmpfsSizeMib === null) throw new Error('sandbox memory must be positive to size the runtime tmpfs') const workdir = spec.projectMounts[0] @@ -222,6 +222,7 @@ export function buildSandboxCreateArgs(spec: SandboxVmSpec): string[] { return [ 'run', '-d', + ...(options.replace === true ? ['--replace'] : []), '--name', spec.name, '--label', diff --git a/backend/src/services/sandbox/runtime.ts b/backend/src/services/sandbox/runtime.ts index 8cd8fdb7..b6ab83e2 100644 --- a/backend/src/services/sandbox/runtime.ts +++ b/backend/src/services/sandbox/runtime.ts @@ -56,6 +56,7 @@ const SANDBOX_IDLE_SWEEP_INTERVAL_MS = 60000 const SANDBOX_RUNTIME_TMPFS_GUEST = path.resolve('/tmp') const SANDBOX_REMOVAL_MISSING_PATTERN = /not found|no such sandbox|unknown sandbox|does not exist/i const SANDBOX_VOLUME_REMOVAL_MISSING_PATTERN = /not found|no such volume|unknown volume|does not exist/i +const SANDBOX_CREATE_EXISTS_PATTERN = /already exists/i export type SandboxShellTarget = { rootSessionId: string @@ -798,11 +799,7 @@ function scheduleBackgroundProvisionRetry(name: string): void { } async function createSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): Promise { - await withStartAdmission(spec.name, maxRunningVms, async () => { - await executeCommand([sandboxExecutablePath(), ...buildSandboxCreateArgs(spec)], { - timeout: ENV.SANDBOX.START_TIMEOUT_MS, - }) - }) + await withStartAdmission(spec.name, maxRunningVms, () => runSandboxCreate(spec)) await provisionSandboxExecUser(spec.name) const attestation = await attestSessionSandbox(spec, true) if (!attestation.trusted) { @@ -810,6 +807,29 @@ async function createSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): } } +async function runSandboxCreate(spec: SandboxVmSpec): Promise { + const first = await executeSandboxCreate(buildSandboxCreateArgs(spec)) + if (first.exitCode === 0) return + if (!SANDBOX_CREATE_EXISTS_PATTERN.test(`${first.stdout}\n${first.stderr}`)) { + throw new Error(`Command failed with code ${first.exitCode}: ${first.stderr || first.stdout}`) + } + logger.warn( + `Sandbox ${spec.name} already exists as an orphaned msb sandbox; recreating it with --replace: ${first.stderr || first.stdout}`, + ) + const replaced = await executeSandboxCreate(buildSandboxCreateArgs(spec, { replace: true })) + if (replaced.exitCode !== 0) { + throw new Error(`Command failed with code ${replaced.exitCode}: ${replaced.stderr || replaced.stdout}`) + } +} + +async function executeSandboxCreate(args: string[]): Promise<{ exitCode: number; stdout: string; stderr: string }> { + const result = (await executeCommand([sandboxExecutablePath(), ...args], { + ignoreExitCode: true, + timeout: ENV.SANDBOX.START_TIMEOUT_MS, + })) as string | { exitCode: number; stdout: string; stderr: string } + return typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result +} + async function removeSessionSandboxVm(name: string): Promise { await runSandboxRemoval(buildSandboxRemoveArgs(name), SANDBOX_REMOVAL_MISSING_PATTERN, 'msb rm') } diff --git a/backend/test/services/sandbox/command.test.ts b/backend/test/services/sandbox/command.test.ts index 892bc408..01201054 100644 --- a/backend/test/services/sandbox/command.test.ts +++ b/backend/test/services/sandbox/command.test.ts @@ -197,6 +197,34 @@ describe('sandbox command builders', () => { expect(() => buildSandboxCreateArgs(vmSpec({ projectMounts: [] }))).toThrow('at least one project mount') }) + it('inserts --replace immediately after -d before the image and never after --', () => { + const plain = buildSandboxCreateArgs(vmSpec()) + const replace = buildSandboxCreateArgs(vmSpec(), { replace: true }) + + expect(plain).not.toContain('--replace') + expect(plain.slice(0, 3)).toEqual(['run', '-d', '--name']) + expect(replace.slice(0, 4)).toEqual(['run', '-d', '--replace', '--name']) + expect(replace.filter((token) => token === '--replace')).toHaveLength(1) + + const imageIndex = replace.indexOf(ENV.SANDBOX.IMAGE) + const separatorIndex = replace.indexOf('--') + const replaceIndex = replace.indexOf('--replace') + expect(replaceIndex).toBeLessThan(imageIndex) + expect(replaceIndex).toBeLessThan(separatorIndex) + expect(replace.slice(replaceIndex + 1)).toEqual(plain.slice(2)) + }) + + it('keeps the canonical spec free of the --replace flag', () => { + const canonical = buildCanonicalSandboxSpec(vmSpec()) + + expect(JSON.stringify(canonical)).not.toContain('--replace') + expect(canonical.name).toBe(VM_NAME) + expect((canonical.image as { Oci: { reference: string } }).Oci.reference).toBe(ENV.SANDBOX.IMAGE) + expect((canonical.runtime as { cmd: string[] }).cmd).toEqual(['sleep', 'infinity']) + expect((canonical.runtime as { workdir: string }).workdir).toBe(getReposPath()) + expect(canonical.labels).toEqual({ 'ocm.managed': 'true', 'ocm.net': ENV.SANDBOX.NET, 'ocm.session': ROOT_SESSION_ID }) + }) + it('never masks the assistant .opencode directory with a tmpfs overlay', () => { const args = buildSandboxCreateArgs(vmSpec()) diff --git a/backend/test/services/sandbox/runtime.test.ts b/backend/test/services/sandbox/runtime.test.ts index 77c58436..5f24b914 100644 --- a/backend/test/services/sandbox/runtime.test.ts +++ b/backend/test/services/sandbox/runtime.test.ts @@ -852,6 +852,74 @@ describe('SandboxRuntimeService', () => { expect(msbCalls('run')).toHaveLength(2) }) + it('retries the create with --replace when msb reports the sandbox already exists', async () => { + enableEnforcement() + const vms = new Map() + installFakeMsb(vms) + const baseHandler = execHandler + let firstRun = true + execHandler = (args) => { + if (args[1] === 'run') { + if (firstRun) { + firstRun = false + return { exitCode: 1, stdout: '', stderr: `error: sandbox already exists: sandbox '${VM_NAME}' already exists` } + } + if (!args.includes('--replace')) { + return { exitCode: 1, stdout: '', stderr: 'retried without --replace' } + } + } + return baseHandler(args) + } + + const plan = await service.planShell(repoADir, shellTarget(repoADir)) + + expect(plan).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir }) + const runs = msbCalls('run') + expect(runs).toHaveLength(2) + expect(runs[0]).not.toContain('--replace') + expect(runs[1]).toContain('--replace') + expect(vms.has(VM_NAME)).toBe(true) + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('already exists as an orphaned msb sandbox')) + }) + + it('does not retry a create that fails for another reason', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const baseHandler = execHandler + execHandler = (args) => { + if (args[1] === 'run') return { exitCode: 1, stdout: '', stderr: 'no KVM acceleration available' } + return baseHandler(args) + } + + const plan = await service.planShell(repoADir, shellTarget(repoADir)) + + expect(plan).toEqual({ mode: 'blocked', reason: 'Command failed with code 1: no KVM acceleration available' }) + const runs = msbCalls('run') + expect(runs).toHaveLength(1) + expect(runs[0]).not.toContain('--replace') + expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('orphaned msb sandbox')) + }) + + it('surfaces a failing replace create as a blocked plan', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const baseHandler = execHandler + execHandler = (args) => { + if (args[1] === 'run') { + if (!args.includes('--replace')) { + return { exitCode: 1, stdout: '', stderr: `error: sandbox already exists: sandbox '${VM_NAME}' already exists` } + } + return { exitCode: 1, stdout: '', stderr: 'replace failed: sandbox busy' } + } + return baseHandler(args) + } + + const plan = await service.planShell(repoADir, shellTarget(repoADir)) + + expect(plan).toEqual({ mode: 'blocked', reason: 'Command failed with code 1: replace failed: sandbox busy' }) + expect(msbCalls('run')).toHaveLength(2) + }) + it('stops the least recently used idle VM when the running cap is reached', async () => { vi.useFakeTimers() try {