mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
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.
This commit is contained in:
1 parent
052218d5d6
commit
27c673d830
4 files changed
+123
-6
No files matched your search
@@ -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',
|
||||
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
await runSandboxRemoval(buildSandboxRemoveArgs(name), SANDBOX_REMOVAL_MISSING_PATTERN, 'msb rm')
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
|
||||
|
||||
@@ -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<string, FakeVm>()
|
||||
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 {
|
||||
|
||||
Reference in new issue
Block a user