diff --git a/test/agent-container.test.ts b/test/agent-container.test.ts index 7b6ef613..83646a9e 100644 --- a/test/agent-container.test.ts +++ b/test/agent-container.test.ts @@ -1,4 +1,5 @@ import { execFileSync, spawnSync } from 'node:child_process'; +import { removeRunnerObjects } from './fixtures/docker-sweep.ts'; import { fixtureGit } from './fixtures/git.ts'; import { createHash, randomBytes, randomUUID } from 'node:crypto'; import { chmodSync, existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, @@ -39,7 +40,8 @@ vi.mock('node:fs', async importOriginal => { return actual.realpathSync(path); }) as typeof actual.realpathSync }; }); -const TEST_RUNNER_OWNER = '0123456789abcdef0123456789abcdef'; +// Each run has its own runner owner, so counting the storage it owns ignores what a concurrent or failed run holds. +const TEST_RUNNER_OWNER = randomBytes(16).toString('hex'); const testOwner = (attemptId = 'fixture') => ({ runnerOwner: TEST_RUNNER_OWNER, attemptId, allocationId: randomUUID() }); const roots: string[] = []; @@ -52,9 +54,16 @@ const git = fixtureGit; const docker = (...args: string[]) => execFileSync('docker', args, { encoding: 'utf8', timeout: 60_000, stdio: ['ignore', 'pipe', 'pipe'], }).trim(); +// Every volume, network and container of one allocation, found by that label alone: another run's objects never +// count, and neither a missing nor a wrong runner label can hide one. +const byAllocation = (allocationId: string) => ['volume', 'network'].flatMap(kind => docker(kind, 'ls', '--quiet', + '--filter', `label=io.codeboost.allocation=${allocationId}`).split('\n').filter(Boolean)) + .concat(docker('ps', '--all', '--quiet', '--filter', `label=io.codeboost.allocation=${allocationId}`).split('\n') + .filter(Boolean)); function fixture(options: { limits?: Parameters[1]; historyBytes?: number; - hostile?: (source: string, root: string) => void; beforeSeed?: (clone: string) => void; objectFormat?: 'sha256' } = {}) { + hostile?: (source: string, root: string) => void; beforeSeed?: (clone: string) => void; objectFormat?: 'sha256'; + owner?: ReturnType } = {}) { const root = mkdtempSync(join(tmpdir(), 'agent-container-')); roots.push(root); const source = join(root, 'source'), staging = join(root, 'staging'), input = join(root, 'input'); mkdirSync(source); mkdirSync(staging); mkdirSync(input); @@ -75,7 +84,7 @@ function fixture(options: { limits?: Parameters[1 options.beforeSeed?.(clone.directory); const filesystems = prepareTaskFilesystems(clone, options.limits ?? { workBytes: 16 * 1024 * 1024, workInodes: 512, metadataBytes: 16 * 1024 * 1024, metadataInodes: 512, - }, imageId, testOwner()); + }, imageId, options.owner ?? testOwner()); taskFilesystems.push(filesystems); const fakeAuth = join(root, 'auth.json'); writeFileSync(fakeAuth, '{}', { mode: 0o600 }); return { root, source, input, clone, filesystems, fakeAuth }; @@ -124,13 +133,20 @@ afterEach(async () => { for (const network of vendorNetworks.splice(0).reverse()) await removeVendorNetwork(network); }, 120_000); afterAll(async () => { - for (const container of containers) spawnSync('docker', ['rm', '--force', container], { stdio: 'ignore' }); - for (const filesystems of taskFilesystems.reverse()) removeTaskFilesystems(filesystems); - for (const profile of profiles) await disposeContainerProfile(profile); - for (const network of vendorNetworks.splice(0).reverse()) await removeVendorNetwork(network); - for (const root of roots.reverse()) { - chmodSync(join(root, 'input'), 0o700); - rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }); + try { + for (const container of containers) spawnSync('docker', ['rm', '--force', container], { stdio: 'ignore' }); + for (const filesystems of taskFilesystems.reverse()) removeTaskFilesystems(filesystems); + for (const profile of profiles) await disposeContainerProfile(profile); + for (const network of vendorNetworks.splice(0).reverse()) await removeVendorNetwork(network); + for (const root of roots.reverse()) { + chmodSync(join(root, 'input'), 0o700); + rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }); + } + } finally { + // The runner owner is this run's own, so nothing else would find what this run leaves behind. Objects a test + // makes under another owner or without the runner label are not found here; those tests remove their own. It may + // not run before a hook timeout. + removeRunnerObjects(TEST_RUNNER_OWNER); } }, 120_000); @@ -282,14 +298,12 @@ describe('real Docker agent isolation', () => { symlinkSync(target, join(source, 'L')); }] as const), ] as const)('refuses to seed a repository with %s, and leaves no storage behind', async (_label, hostile) => { - const owned = () => [docker('volume', 'ls', '--quiet', '--filter', 'label=io.codeboost.allocation'), - docker('ps', '--all', '--quiet', '--filter', 'label=io.codeboost.allocation')].join('\n').split('\n').filter(Boolean); - const before = new Set(owned()); - const refused = (() => { try { fixture({ hostile }); } catch (error) { return error; } })(); + const owner = testOwner(); + const refused = (() => { try { fixture({ hostile, owner }); } catch (error) { return error; } })(); // Its own error type, so a caller can tell an unusable repository from a Docker failure, with the reason first. expect(refused).toBeInstanceOf(UnusableRepositoryError); expect((refused as Error).message).toMatch(/^Repository link leaves the checkout: /); - expect(owned().filter(id => !before.has(id))).toEqual([]); + expect(byAllocation(owner.allocationId)).toEqual([]); }, 60_000); // Names are bytes: a link whose name is not UTF-8, beside a file named what a decoder turns it into. Linux only: a @@ -307,16 +321,14 @@ describe('real Docker agent isolation', () => { head: git(data.source, 'rev-parse', 'HEAD') }); // /work/.git is mounted read-only, which stops writes but not reads through a link. symlinkSync('/run/codeboost-auth/codex/auth.json', join(clone.directory, '.git', 'credential')); - const owned = () => [docker('volume', 'ls', '--quiet', '--filter', 'label=io.codeboost.allocation'), - docker('ps', '--all', '--quiet', '--filter', 'label=io.codeboost.allocation')].join('\n').split('\n').filter(Boolean); - const before = new Set(owned()); + const owner = testOwner(); const refused = (() => { try { prepareTaskFilesystems(clone, { workBytes: 16 * 1024 * 1024, workInodes: 512, metadataBytes: 16 * 1024 * 1024, - metadataInodes: 512 }, imageId, testOwner()); } catch (error) { return error; } + metadataInodes: 512 }, imageId, owner); } catch (error) { return error; } })(); expect(refused).toBeInstanceOf(UnusableRepositoryError); expect((refused as Error).message).toMatch(/^Repository Git metadata contains a link: /); - expect(owned().filter(id => !before.has(id))).toEqual([]); + expect(byAllocation(owner.allocationId)).toEqual([]); }, 60_000); it('seeds links that stay inside the checkout, including loops and not-yet-existing targets', async () => { @@ -336,13 +348,11 @@ describe('real Docker agent isolation', () => { }, 60_000); it('fails closed without leaving storage when a repository exceeds its allocation', async () => { - const owned = () => [docker('volume', 'ls', '--quiet', '--filter', 'label=io.codeboost.allocation'), - docker('ps', '--all', '--quiet', '--filter', 'label=io.codeboost.allocation')].join('\n').split('\n').filter(Boolean); - const before = new Set(owned()); - expect(() => fixture({ historyBytes: 4 * 1024 * 1024, limits: { + const owner = testOwner(); + expect(() => fixture({ owner, historyBytes: 4 * 1024 * 1024, limits: { workBytes: 16 * 1024 * 1024, workInodes: 512, metadataBytes: 1024 * 1024, metadataInodes: 512, } })).toThrow(); - expect(owned().filter(id => !before.has(id))).toEqual([]); + expect(byAllocation(owner.allocationId)).toEqual([]); }, 60_000); it('persists execution changes while replacing HOME and scratch for each invocation', async () => { @@ -634,13 +644,13 @@ describe('real Docker agent isolation', () => { }; it('rejects a vendor network or proxy without its runner label, and removes them', async () => { - const data = fixture(), egress = () => docker('network', 'ls', '--quiet', '--filter', 'label=io.codeboost.egress'); - const before = egress(); + // Counted by allocation, not by runner: first the network, then the proxy, is made without the runner label. + const data = fixture(), allocations = [randomUUID(), randomUUID()]; await withoutRunnerLabel([['network', 'create']], () => expect(createVendorNetwork(invocation(data.clone, 'planning'), - imageId, randomUUID())).rejects.toThrow('changed after allocation')); + imageId, allocations[0]!)).rejects.toThrow('changed after allocation')); await withoutRunnerLabel([['create', '--name']], () => expect(createVendorNetwork(invocation(data.clone, 'planning'), - imageId, randomUUID())).rejects.toThrow('changed after allocation')); - expect(egress()).toBe(before); + imageId, allocations[1]!)).rejects.toThrow('changed after allocation')); + expect(allocations.flatMap(byAllocation)).toEqual([]); }, 120_000); // Storage has no captured IDs, so cleanup refuses an object without every owner label; the test removes its own. @@ -707,10 +717,6 @@ describe('real Docker agent isolation', () => { "const allocation = args.find(arg => arg.startsWith('io.codeboost.allocation='));", `run(['volume', 'create', '--label', 'io.codeboost.runner=${'f'.repeat(32)}', '--label', allocation, '${name}']);`, ].join('\n'); - const byAllocation = (allocationId: string) => ['volume', 'network'].flatMap(kind => docker(kind, 'ls', '--quiet', - '--filter', `label=io.codeboost.allocation=${allocationId}`).split('\n').filter(Boolean)) - .concat(docker('ps', '--all', '--quiet', '--filter', `label=io.codeboost.allocation=${allocationId}`).split('\n') - .filter(Boolean)); it('backs out of task storage when a concurrent process claims the same allocation ID', async () => { const data = fixture(), owner = testOwner('storage-race'), rival = `codeboost-race-${randomUUID()}`; @@ -2382,8 +2388,9 @@ describe('real Docker agent isolation', () => { const data = fixture(); const clone = createTaskClone({ source: data.source, parent: join(data.root, 'staging'), taskId: 'task-late', head: git(data.source, 'rev-parse', 'HEAD') }); - const keepers = () => new Set(docker('ps', '--all', '--quiet', '--filter', 'label=io.codeboost.task-storage=keeper') - .split('\n').filter(Boolean)); + // Only this run's keepers: the orphans found are force-removed, so another run's must never be among them. + const keepers = () => new Set(docker('ps', '--all', '--quiet', '--filter', 'label=io.codeboost.task-storage=keeper', + '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`).split('\n').filter(Boolean)); const before = keepers(); const shim = join(data.root, 'docker-shim'); mkdirSync(shim); const realDocker = execFileSync('sh', ['-c', 'command -v docker'], { encoding: 'utf8' }).trim(); diff --git a/test/agent-supervisor.test.ts b/test/agent-supervisor.test.ts index c7532d51..1db2faa0 100644 --- a/test/agent-supervisor.test.ts +++ b/test/agent-supervisor.test.ts @@ -1,5 +1,6 @@ -import { randomUUID } from 'node:crypto'; +import { randomBytes, randomUUID } from 'node:crypto'; import { execFileSync, spawnSync } from 'node:child_process'; +import { removeRunnerObjects } from './fixtures/docker-sweep.ts'; import { fixtureGit } from './fixtures/git.ts'; import { chmodSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -18,8 +19,13 @@ import { createValidatedContainer, disposeValidatedContainer, prepareTaskFilesys import { createVendorNetwork } from '../agents/network/network.ts'; import { createIsolationProbeCommand, createPhasePolicy, type IsolationProbe } from '../agents/policy.ts'; import type { ProcessGroupLifecycle, ProcessGroupOwner } from '../agents/tracked-docker.ts'; +import { RUNNER_LABEL } from '../agents/labels.ts'; import { createTaskClone } from '../git/clone.ts'; -const TEST_RUNNER_OWNER = '0123456789abcdef0123456789abcdef'; +// Container names come from attempt IDs, so each run gets its own suffix and runner owner: a container a failed or +// concurrent run leaves behind can neither take this run's names nor count as this run's resources. +const TEST_RUNNER_OWNER = randomBytes(16).toString('hex'); +const RUN = randomBytes(4).toString('hex'); +const attempt = (name: string) => `${name}-${RUN}`; const testOwner = (attemptId = 'fixture') => ({ runnerOwner: TEST_RUNNER_OWNER, attemptId, allocationId: randomUUID() }); const roots: string[] = [], profiles: ContainerProfile[] = []; @@ -44,14 +50,14 @@ function fixture(schema = '{"probe":"codeboost-adapter-schema-marker"}\n') { function invocation(data: ReturnType, attemptId: string, deadlineMs = 2 * 60_000, vendor: InvocationInput['vendor'] = 'codex', phase: Phase = 'planning'): InvocationInput { return captureInvocation({ runnerOwner: TEST_RUNNER_OWNER, clone: data.clone, phase, vendor, approvedArgv: [], - deadline: Date.now() + deadlineMs, attemptId, + deadline: Date.now() + deadlineMs, attemptId: attempt(attemptId), context: { snapshotId: 'snapshot', planId: 'plan', planRevision: 1, assignmentId: 'assignment', referencedCodeHash: 'code', stateVersion: 1 } }); } async function profile(data: ReturnType, probe: IsolationProbe, - attempt: string | InvocationInput = `attempt-${Math.random()}`, deadlineMs = 2 * 60_000, deferredOutput = false) { + attemptId: string | InvocationInput = `attempt-${Math.random()}`, deadlineMs = 2 * 60_000, deferredOutput = false) { // An attempt can be captured once, so a duplicate-attempt profile reuses the captured invocation. - const captured = typeof attempt === 'string' ? invocation(data, attempt, deadlineMs) : attempt; + const captured = typeof attemptId === 'string' ? invocation(data, attemptId, deadlineMs) : attemptId; const policy = createPhasePolicy(captured); const network = await createVendorNetwork(captured, imageId, randomUUID()); const value = await createContainerProfile({ invocation: captured, policy, network, filesystems: data.filesystems, @@ -63,11 +69,17 @@ async function profile(data: ReturnType, probe: IsolationProbe, beforeAll(async () => { imageId = buildAgentImage(); }, 10 * 60_000); afterAll(async () => { - for (const profile of profiles) await disposeContainerProfile(profile); - for (const allocation of allocations.reverse()) removeTaskFilesystems(allocation); - for (const root of roots.reverse()) { - chmodSync(join(root, 'input'), 0o700); - rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }); + try { + for (const profile of profiles) await disposeContainerProfile(profile); + for (const allocation of allocations.reverse()) removeTaskFilesystems(allocation); + for (const root of roots.reverse()) { + chmodSync(join(root, 'input'), 0o700); + rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }); + } + } finally { + // Then remove whatever this run still owns, even when a test failed or the cleanup above threw: an agent that + // ignores SIGTERM, or storage whose removal did not settle. It may not run before a hook timeout. + removeRunnerObjects(TEST_RUNNER_OWNER); } }, 3 * 60_000); @@ -86,18 +98,18 @@ describe('container invocation supervisor', () => { expect(result.stopReason).toBe('shutdown'); expect(result.stderr).toContain('[codeboost: shutdown:'); expect(attempts).toBe(1); - expect(isInvocationActive('cancel-setup-cleanup')).toBe(false); - }); + expect(isInvocationActive(attempt('cancel-setup-cleanup'))).toBe(false); + }, 60_000); // the fixture creates task storage in Docker, which can take longer than Vitest's 5 s default it('captures finite output and releases ownership only after cleanup', async () => { const current = await profile(fixture(), 'finite-output', 'finite'); const handle = startProfileInvocation(current); - expect(isInvocationActive('finite')).toBe(true); + expect(isInvocationActive(attempt('finite'))).toBe(true); const result = await handle.settled; - expect(result).toMatchObject({ attemptId: 'finite', exitCode: 0, signal: null, + expect(result).toMatchObject({ attemptId: attempt('finite'), exitCode: 0, signal: null, stdout: 'stdout-marker', stderr: 'stderr-marker' }); expect(result.stopReason).toBeUndefined(); - expect(isInvocationActive('finite')).toBe(false); + expect(isInvocationActive(attempt('finite'))).toBe(false); expect(spawnSync('docker', ['container', 'inspect', current.name]).status).not.toBe(0); expect(spawnSync('docker', ['network', 'inspect', current.network.name]).status).not.toBe(0); }, 60_000); @@ -133,7 +145,7 @@ describe('container invocation supervisor', () => { expect(Buffer.byteLength(result.stdout)).toBeLessThanOrEqual(limits.stdoutBytes); expect(Buffer.byteLength(result.stderr)).toBeLessThanOrEqual(limits.stderrBytes); expect(Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr)).toBeLessThanOrEqual(limits.combinedBytes); - expect(isInvocationActive(attemptId)).toBe(false); + expect(isInvocationActive(attempt(attemptId))).toBe(false); }, 60_000); it('drains finite command diagnostics past their capture limits without changing exit-0 success', async () => { @@ -193,7 +205,7 @@ describe('container invocation supervisor', () => { // The decoded text is discarded; the result keeps the probe's raw stdout. expect(result.stdout).toBe('stdout-marker'); } - expect(isInvocationActive(attemptId)).toBe(false); + expect(isInvocationActive(attempt(attemptId))).toBe(false); } }, 120_000); @@ -207,7 +219,7 @@ describe('container invocation supervisor', () => { const result = await handle.settled; expect(result.stopReason).toBe('output-limit'); expect(Buffer.byteLength(result.stderr)).toBeLessThanOrEqual(32 * 1024); - expect(isInvocationActive(attemptId)).toBe(false); + expect(isInvocationActive(attempt(attemptId))).toBe(false); }, 60_000); it('preserves the first cancellation reason until an ignored SIGTERM fully settles', async () => { @@ -218,11 +230,11 @@ describe('container invocation supervisor', () => { handle.cancel('cancelled'); handle.cancel('shutdown'); await Promise.resolve(); expect(settled).toBe(false); - expect(isInvocationActive('cancelled')).toBe(true); + expect(isInvocationActive(attempt('cancelled'))).toBe(true); const result = await handle.settled; expect(result.stopReason).toBe('cancelled'); expect(result.stderr).toContain('[codeboost: cancelled]'); - expect(isInvocationActive('cancelled')).toBe(false); + expect(isInvocationActive(attempt('cancelled'))).toBe(false); }, 60_000); // A rejected start settles (after releasing the profile) instead of throwing. @@ -281,7 +293,7 @@ describe('container invocation supervisor', () => { expect(result.stopReason).toBe('shutdown'); expect(result.stderr).toContain('cleanup was not confirmed within 60 s'); expect(result.unreleased).toEqual(expected); - expect(isInvocationActive('unreachable-daemon')).toBe(false); + expect(isInvocationActive(attempt('unreachable-daemon'))).toBe(false); expect(() => startProfileInvocation(current)).toThrow('settled without confirmed cleanup'); // Every launch path refuses it, before touching the leftover container that recovery still owns. await expect(startValidatedContainer(current)).rejects.toThrow('settled without confirmed cleanup'); @@ -335,7 +347,7 @@ describe('container invocation supervisor', () => { const started = performance.now(); const handle = startProfileInvocation(current, { timeoutMs: 2 * 60_000 }); expect(performance.now() - started).toBeLessThan(250); - expect(isInvocationActive('setup-cancel')).toBe(true); + expect(isInvocationActive(attempt('setup-cancel'))).toBe(true); await new Promise(resolve => setTimeout(resolve, 1_000)); // the create is now hanging expect(await loopLag()).toBeLessThan(250); handle.cancel('shutdown'); @@ -343,7 +355,7 @@ describe('container invocation supervisor', () => { }); expect(result.stopReason).toBe('shutdown'); expect(result.unreleased).toBeUndefined(); - expect(isInvocationActive('setup-cancel')).toBe(false); + expect(isInvocationActive(attempt('setup-cancel'))).toBe(false); expect(isContainerProfileAuthentic(current)).toBe(false); expect(spawnSync('docker', ['container', 'inspect', current.name]).status).not.toBe(0); expect(spawnSync('docker', ['network', 'inspect', current.network.name]).status).not.toBe(0); @@ -351,15 +363,15 @@ describe('container invocation supervisor', () => { it('returns the adapter handle at once and cancels it during network creation', async () => { const data = fixture(), captured = invocation(data, 'adapter-setup-cancel', 2 * 60_000, 'claude', 'review'); - const egress = () => spawnSync('docker', ['network', 'ls', '--quiet', '--filter', 'label=io.codeboost.egress'], - { encoding: 'utf8' }).stdout.trim().split('\n').filter(Boolean).sort(); + const egress = () => spawnSync('docker', ['network', 'ls', '--quiet', '--filter', 'label=io.codeboost.egress', + '--filter', `label=${RUNNER_LABEL}=${TEST_RUNNER_OWNER}`], { encoding: 'utf8' }).stdout.trim().split('\n').filter(Boolean).sort(); const before = egress(); const result = await withEnvironment('PATH', hangingDocker('network\\ create*'), async () => { const started = performance.now(); const handle = startClaudeInvocation({ invocation: captured, filesystems: data.filesystems, inputDirectory: data.input, imageId, prompt: 'unused', networkAllocationId: randomUUID() }, 'unused', { timeoutMs: 2 * 60_000 }); expect(performance.now() - started).toBeLessThan(250); - expect(isInvocationActive('adapter-setup-cancel')).toBe(true); + expect(isInvocationActive(attempt('adapter-setup-cancel'))).toBe(true); await new Promise(resolve => setTimeout(resolve, 1_000)); expect(await loopLag()).toBeLessThan(250); handle.cancel('cancelled'); @@ -367,7 +379,7 @@ describe('container invocation supervisor', () => { }); expect(result.stopReason).toBe('cancelled'); expect(result.unreleased).toBeUndefined(); - expect(isInvocationActive('adapter-setup-cancel')).toBe(false); + expect(isInvocationActive(attempt('adapter-setup-cancel'))).toBe(false); expect(egress()).toEqual(before); }, 2 * 60_000); @@ -380,7 +392,7 @@ describe('container invocation supervisor', () => { expect(result.stopReason).toBe('capture-failure'); expect(result.stderr).toMatch(/already in use|Conflict/); expect(result.unreleased).toBeUndefined(); - expect(isInvocationActive('foreign-name')).toBe(false); + expect(isInvocationActive(attempt('foreign-name'))).toBe(false); expect(isContainerProfileAuthentic(current)).toBe(false); expect(spawnSync('docker', ['network', 'inspect', current.network.name], { stdio: 'ignore' }).status).not.toBe(0); expect(execFileSync('docker', ['container', 'inspect', '--format', @@ -396,7 +408,7 @@ describe('container invocation supervisor', () => { const result = await handle.settled; expect(result.stopReason).toBe('timeout'); expect(Date.now() - started).toBeLessThan(20_000); - expect(isInvocationActive('timeout')).toBe(false); + expect(isInvocationActive(attempt('timeout'))).toBe(false); }, 60_000); it('records timeout when close delivery resumes after the monotonic deadline', async () => { @@ -437,7 +449,7 @@ describe('container invocation supervisor', () => { const data = fixture(), duplicate = invocation(data, 'duplicate'); const first = startProfileInvocation(await profile(data, 'ignore-term', duplicate), { timeoutMs: 30_000 }); await expectRejected(startProfileInvocation(await profile(data, 'finite-output', duplicate)), 'still active'); - expect(isInvocationActive('duplicate')).toBe(true); + expect(isInvocationActive(attempt('duplicate'))).toBe(true); first.cancel('shutdown'); expect((await first.settled).stopReason).toBe('shutdown'); }, 60_000); @@ -446,7 +458,7 @@ describe('container invocation supervisor', () => { const current = await profile(fixture(), 'ignore-term', 'same-profile-duplicate'); const first = startProfileInvocation(current, { timeoutMs: 30_000 }); expect(() => startProfileInvocation(current)).toThrow('already owns the active invocation'); - expect(isInvocationActive('same-profile-duplicate')).toBe(true); + expect(isInvocationActive(attempt('same-profile-duplicate'))).toBe(true); await waitRunning(current.name); expect(spawnSync('docker', ['container', 'inspect', current.name]).status).toBe(0); first.cancel('shutdown'); @@ -460,7 +472,7 @@ describe('container invocation supervisor', () => { const clone = Object.freeze({ ...current }); await expect(disposeValidatedContainer(clone)).rejects.toThrow('not created by the trusted profile builder'); expect(() => startProfileInvocation(clone)).toThrow('not created by the trusted profile builder'); - expect(isInvocationActive('cloned-profile')).toBe(true); + expect(isInvocationActive(attempt('cloned-profile'))).toBe(true); expect(spawnSync('docker', ['container', 'inspect', current.name]).status).toBe(0); first.cancel('shutdown'); expect((await first.settled).stopReason).toBe('shutdown'); @@ -473,7 +485,7 @@ describe('container invocation supervisor', () => { const result = await handle.settled; expect(result.stopReason).toBe('capture-failure'); expect(result.stderr).toContain('[codeboost: capture-failure'); - expect(isInvocationActive('capture-failure')).toBe(false); + expect(isInvocationActive(attempt('capture-failure'))).toBe(false); }, 60_000); it('preserves cancellation while post-close decoding is still unsettled', async () => { @@ -500,7 +512,7 @@ describe('container invocation supervisor', () => { }).settled; expect(result.stopReason).toBe('timeout'); expect(Date.now() - started).toBeLessThan(15_000); - expect(isInvocationActive('decode-timeout')).toBe(false); + expect(isInvocationActive(attempt('decode-timeout'))).toBe(false); }, 30_000); it('does not wedge when an injected decoder ignores abort', async () => { @@ -511,7 +523,7 @@ describe('container invocation supervisor', () => { }).settled; expect(result.stopReason).toBe('timeout'); expect(Date.now() - started).toBeLessThan(15_000); - expect(isInvocationActive('decode-ignores-abort')).toBe(false); + expect(isInvocationActive(attempt('decode-ignores-abort'))).toBe(false); }, 30_000); it('settles cancellation promptly when an injected decoder ignores abort', async () => { @@ -527,7 +539,7 @@ describe('container invocation supervisor', () => { const result = await handle.settled; expect(result.stopReason).toBe('cancelled'); expect(performance.now() - cancelledAt).toBeLessThan(5_000); - expect(isInvocationActive('cancel-ignored-decode')).toBe(false); + expect(isInvocationActive(attempt('cancel-ignored-decode'))).toBe(false); }, 15_000); it('does not publish a synchronous decode that finishes after the monotonic deadline', async () => { diff --git a/test/fixtures/docker-sweep.ts b/test/fixtures/docker-sweep.ts new file mode 100644 index 00000000..97c0bf0e --- /dev/null +++ b/test/fixtures/docker-sweep.ts @@ -0,0 +1,25 @@ +import { spawnSync } from 'node:child_process'; +import { RUNNER_LABEL } from '../../agents/labels.ts'; + +/** + * Removes the containers, networks and volumes labelled with one runner owner, containers first, as they hold the + * others in use. Containers and volumes go by force; a network that another container still uses stays. It reports + * what it finds and any Docker call that fails, and never throws, so a test file's afterAll can call it in a finally + * block without hiding an error from its ordinary cleanup. Each call has a 30 s limit, so all six can take up to + * 3 minutes. + */ +export function removeRunnerObjects(runnerOwner: string): void { + const run = (args: string[]) => { + const result = spawnSync('docker', args, { encoding: 'utf8', timeout: 30_000, killSignal: 'SIGKILL' }); + if (result.status !== 0) console.warn(`afterAll: docker ${args.slice(0, 2).join(' ')} failed:`, + result.error?.message ?? result.stderr.trim()); + return result.status === 0 ? result.stdout.split('\n').filter(Boolean) : []; + }; + for (const kind of ['container', 'network', 'volume'] as const) { + const ids = run([kind, 'ls', ...(kind === 'container' ? ['--all'] : []), '--quiet', '--filter', + `label=${RUNNER_LABEL}=${runnerOwner}`]); + if (!ids.length) continue; + console.warn(`afterAll removes this run's leftover ${kind}s: ${ids.join(' ')}`); + run([kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids]); + } +}