From 5a1f3a07206002673c38295046fd403b3f6cc401 Mon Sep 17 00:00:00 2001 From: mchwang Date: Tue, 20 Oct 2026 13:07:46 -0700 Subject: [PATCH 1/5] Keep each Docker test run's containers and counts to itself The supervisor tests named agent containers from fixed attempt IDs under one fixed runner owner, so a container that a failed run left behind (an agent that ignores SIGTERM keeps running) took the next run's name and failed it with a name conflict. Each run now has its own attempt suffix and runner owner, and afterAll force-removes every container, network and volume labelled with that owner after the ordinary cleanup, even when that cleanup throws. The storage, egress-network and keeper counts in both files counted every object on the daemon, so a concurrent run's objects failed them; the keeper test would also force-remove another run's keepers. They now count only this run's objects, by runner owner, or by allocation where the objects are made without the runner label on purpose. The first supervisor test had no timeout of its own and could exceed Vitest's 5 s default while its fixture created task storage. Ported from fix/supervisor-test-cleanup (84dd662). Its macOS /var versus /private/var fix for the unreleased-inventory tests is not needed: main records the resolved directories already. Co-Authored-By: Claude Opus 5.5 --- test/agent-container.test.ts | 32 +++++++------ test/agent-supervisor.test.ts | 85 +++++++++++++++++++++-------------- 2 files changed, 69 insertions(+), 48 deletions(-) diff --git a/test/agent-container.test.ts b/test/agent-container.test.ts index 7b6ef613..fd88fc75 100644 --- a/test/agent-container.test.ts +++ b/test/agent-container.test.ts @@ -39,7 +39,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[] = []; @@ -282,8 +283,8 @@ 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 owned = () => [docker('volume', 'ls', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`), + docker('ps', '--all', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`)].join('\n').split('\n').filter(Boolean); const before = new Set(owned()); const refused = (() => { try { fixture({ hostile }); } catch (error) { return error; } })(); // Its own error type, so a caller can tell an unusable repository from a Docker failure, with the reason first. @@ -307,8 +308,8 @@ 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 owned = () => [docker('volume', 'ls', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`), + docker('ps', '--all', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`)].join('\n').split('\n').filter(Boolean); const before = new Set(owned()); const refused = (() => { try { prepareTaskFilesystems(clone, { workBytes: 16 * 1024 * 1024, workInodes: 512, metadataBytes: 16 * 1024 * 1024, @@ -336,8 +337,8 @@ 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 owned = () => [docker('volume', 'ls', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`), + docker('ps', '--all', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`)].join('\n').split('\n').filter(Boolean); const before = new Set(owned()); expect(() => fixture({ historyBytes: 4 * 1024 * 1024, limits: { workBytes: 16 * 1024 * 1024, workInodes: 512, metadataBytes: 1024 * 1024, metadataInodes: 512, @@ -634,13 +635,15 @@ 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: these networks are created without the runner label on purpose. + const data = fixture(), allocations = [randomUUID(), randomUUID()]; + const egress = () => allocations.map(allocation => docker('network', 'ls', '--quiet', '--filter', 'label=io.codeboost.egress', + '--filter', `label=io.codeboost.allocation=${allocation}`)).join(''); 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(egress()).toBe(''); }, 120_000); // Storage has no captured IDs, so cleanup refuses an object without every owner label; the test removes its own. @@ -2382,8 +2385,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..e2ef386f 100644 --- a/test/agent-supervisor.test.ts +++ b/test/agent-supervisor.test.ts @@ -1,4 +1,4 @@ -import { randomUUID } from 'node:crypto'; +import { randomBytes, randomUUID } from 'node:crypto'; import { execFileSync, spawnSync } from 'node:child_process'; import { fixtureGit } from './fixtures/git.ts'; import { chmodSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; @@ -18,8 +18,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,7 +49,7 @@ 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 } }); } @@ -63,11 +68,23 @@ 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 or the cleanup above failed first: an agent that + // ignores SIGTERM, or storage whose removal did not settle. Containers go first, as they hold the others in use. + for (const kind of ['container', 'network', 'volume'] as const) { + const ids = spawnSync('docker', [kind, 'ls', ...(kind === 'container' ? ['--all'] : []), '--quiet', '--filter', + `label=${RUNNER_LABEL}=${TEST_RUNNER_OWNER}`], { encoding: 'utf8', timeout: 30_000, killSignal: 'SIGKILL' }) + .stdout?.split('\n').filter(Boolean) ?? []; + if (ids.length) spawnSync('docker', [kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids], + { stdio: 'ignore', timeout: 30_000, killSignal: 'SIGKILL' }); + } } }, 3 * 60_000); @@ -86,18 +103,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 +150,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 +210,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 +224,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 +235,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 +298,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 +352,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 +360,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 +368,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 +384,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 +397,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 +413,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 +454,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 +463,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 +477,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 +490,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 +517,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 +528,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 +544,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 () => { From 523a4da490ab40b5f62fbb4197917ce5d6481b97 Mon Sep 17 00:00:00 2001 From: mchwang Date: Tue, 20 Oct 2026 13:18:59 -0700 Subject: [PATCH 2/5] Count refused storage by its allocation, and report what the sweep removes Independent review (round 1) found the runner-scoped storage counts would miss a leaked object whose runner label was wrong or missing; the three tests now count their own allocation's objects. The afterAll sweep now reports each removal, its comment says a hook timeout skips it, and profile()'s parameter no longer shadows attempt(). Co-Authored-By: Claude Opus 5.5 --- test/agent-container.test.ts | 39 ++++++++++++++++------------------- test/agent-supervisor.test.ts | 13 +++++++----- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/test/agent-container.test.ts b/test/agent-container.test.ts index fd88fc75..ae40e972 100644 --- a/test/agent-container.test.ts +++ b/test/agent-container.test.ts @@ -53,9 +53,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); @@ -76,7 +83,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 }; @@ -283,14 +290,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.runner=${TEST_RUNNER_OWNER}`), - docker('ps', '--all', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`)].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 @@ -308,16 +313,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.runner=${TEST_RUNNER_OWNER}`), - docker('ps', '--all', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`)].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 () => { @@ -337,13 +340,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.runner=${TEST_RUNNER_OWNER}`), - docker('ps', '--all', '--quiet', '--filter', `label=io.codeboost.runner=${TEST_RUNNER_OWNER}`)].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 () => { @@ -710,10 +711,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()}`; diff --git a/test/agent-supervisor.test.ts b/test/agent-supervisor.test.ts index e2ef386f..b6ad98aa 100644 --- a/test/agent-supervisor.test.ts +++ b/test/agent-supervisor.test.ts @@ -54,9 +54,9 @@ function invocation(data: ReturnType, attemptId: string, deadlin 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, @@ -76,13 +76,16 @@ afterAll(async () => { rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }); } } finally { - // Then remove whatever this run still owns, even when a test or the cleanup above failed first: an agent that - // ignores SIGTERM, or storage whose removal did not settle. Containers go first, as they hold the others in use. + // 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. A hook timeout skips this. Containers go first, as + // they hold the others in use. Each removal is reported, so a leak is not hidden. for (const kind of ['container', 'network', 'volume'] as const) { const ids = spawnSync('docker', [kind, 'ls', ...(kind === 'container' ? ['--all'] : []), '--quiet', '--filter', `label=${RUNNER_LABEL}=${TEST_RUNNER_OWNER}`], { encoding: 'utf8', timeout: 30_000, killSignal: 'SIGKILL' }) .stdout?.split('\n').filter(Boolean) ?? []; - if (ids.length) spawnSync('docker', [kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids], + if (!ids.length) continue; + console.warn(`afterAll removes this run's leftover ${kind}s: ${ids.join(' ')}`); + spawnSync('docker', [kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids], { stdio: 'ignore', timeout: 30_000, killSignal: 'SIGKILL' }); } } From 7b4a9c3162ef085a1fd776b7ceb729ab3a582dda Mon Sep 17 00:00:00 2001 From: mchwang Date: Tue, 20 Oct 2026 13:25:32 -0700 Subject: [PATCH 3/5] Count the vendor proxy too, and report failed sweep calls Independent review (round 2): the vendor-network test counted only networks, so a leaked unlabelled proxy would pass; it now counts every object of both allocations. The afterAll sweep reports a Docker call that fails, and its comment says it may not run before a hook timeout. Co-Authored-By: Claude Opus 5.5 --- test/agent-container.test.ts | 6 ++---- test/agent-supervisor.test.ts | 18 +++++++++++------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/test/agent-container.test.ts b/test/agent-container.test.ts index ae40e972..ece03499 100644 --- a/test/agent-container.test.ts +++ b/test/agent-container.test.ts @@ -636,15 +636,13 @@ describe('real Docker agent isolation', () => { }; it('rejects a vendor network or proxy without its runner label, and removes them', async () => { - // Counted by allocation, not by runner: these networks are created without the runner label on purpose. + // Counted by allocation, not by runner: first the network, then the proxy, is made without the runner label. const data = fixture(), allocations = [randomUUID(), randomUUID()]; - const egress = () => allocations.map(allocation => docker('network', 'ls', '--quiet', '--filter', 'label=io.codeboost.egress', - '--filter', `label=io.codeboost.allocation=${allocation}`)).join(''); await withoutRunnerLabel([['network', 'create']], () => expect(createVendorNetwork(invocation(data.clone, 'planning'), imageId, allocations[0]!)).rejects.toThrow('changed after allocation')); await withoutRunnerLabel([['create', '--name']], () => expect(createVendorNetwork(invocation(data.clone, 'planning'), imageId, allocations[1]!)).rejects.toThrow('changed after allocation')); - expect(egress()).toBe(''); + 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. diff --git a/test/agent-supervisor.test.ts b/test/agent-supervisor.test.ts index b6ad98aa..520e3710 100644 --- a/test/agent-supervisor.test.ts +++ b/test/agent-supervisor.test.ts @@ -77,16 +77,20 @@ afterAll(async () => { } } 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. A hook timeout skips this. Containers go first, as - // they hold the others in use. Each removal is reported, so a leak is not hidden. + // ignores SIGTERM, or storage whose removal did not settle. It may not run before a hook timeout. Containers go + // first, as they hold the others in use. What it finds, and any Docker call that fails, is reported. + 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 = spawnSync('docker', [kind, 'ls', ...(kind === 'container' ? ['--all'] : []), '--quiet', '--filter', - `label=${RUNNER_LABEL}=${TEST_RUNNER_OWNER}`], { encoding: 'utf8', timeout: 30_000, killSignal: 'SIGKILL' }) - .stdout?.split('\n').filter(Boolean) ?? []; + const ids = run([kind, 'ls', ...(kind === 'container' ? ['--all'] : []), '--quiet', '--filter', + `label=${RUNNER_LABEL}=${TEST_RUNNER_OWNER}`]); if (!ids.length) continue; console.warn(`afterAll removes this run's leftover ${kind}s: ${ids.join(' ')}`); - spawnSync('docker', [kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids], - { stdio: 'ignore', timeout: 30_000, killSignal: 'SIGKILL' }); + run([kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids]); } } }, 3 * 60_000); From 47e8e091d301c070d349421751cc2ac9e31b3601 Mon Sep 17 00:00:00 2001 From: mchwang Date: Tue, 20 Oct 2026 13:28:58 -0700 Subject: [PATCH 4/5] Sweep the container tests' runner owner too, from one shared fixture Independent review (round 3): with a random runner owner, nothing would find what a failed agent-container run leaves behind. Both files' afterAll hooks now call the same removeRunnerObjects fixture after their ordinary cleanup. Co-Authored-By: Claude Opus 5.5 --- test/agent-container.test.ts | 22 +++++++++++++++------- test/agent-supervisor.test.ts | 18 +++--------------- test/fixtures/docker-sweep.ts | 24 ++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 22 deletions(-) create mode 100644 test/fixtures/docker-sweep.ts diff --git a/test/agent-container.test.ts b/test/agent-container.test.ts index ece03499..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, @@ -132,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); diff --git a/test/agent-supervisor.test.ts b/test/agent-supervisor.test.ts index 520e3710..1db2faa0 100644 --- a/test/agent-supervisor.test.ts +++ b/test/agent-supervisor.test.ts @@ -1,5 +1,6 @@ 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'; @@ -77,21 +78,8 @@ afterAll(async () => { } } 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. Containers go - // first, as they hold the others in use. What it finds, and any Docker call that fails, is reported. - 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}=${TEST_RUNNER_OWNER}`]); - if (!ids.length) continue; - console.warn(`afterAll removes this run's leftover ${kind}s: ${ids.join(' ')}`); - run([kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids]); - } + // ignores SIGTERM, or storage whose removal did not settle. It may not run before a hook timeout. + removeRunnerObjects(TEST_RUNNER_OWNER); } }, 3 * 60_000); diff --git a/test/fixtures/docker-sweep.ts b/test/fixtures/docker-sweep.ts new file mode 100644 index 00000000..2dffd61a --- /dev/null +++ b/test/fixtures/docker-sweep.ts @@ -0,0 +1,24 @@ +import { spawnSync } from 'node:child_process'; +import { RUNNER_LABEL } from '../../agents/labels.ts'; + +/** + * Force-removes every container, network and volume labelled with one runner owner, containers first, as they hold + * the others in use. 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]); + } +} From a0c38a33356754f1addb8f540c940075f20f62ed Mon Sep 17 00:00:00 2001 From: mchwang Date: Tue, 20 Oct 2026 13:33:52 -0700 Subject: [PATCH 5/5] Say that the sweep removes networks without force Independent review (round 4): Docker cannot force-remove a network that a container still uses, and the sweep does not try to. Co-Authored-By: Claude Opus 5.5 --- test/fixtures/docker-sweep.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/fixtures/docker-sweep.ts b/test/fixtures/docker-sweep.ts index 2dffd61a..97c0bf0e 100644 --- a/test/fixtures/docker-sweep.ts +++ b/test/fixtures/docker-sweep.ts @@ -2,10 +2,11 @@ import { spawnSync } from 'node:child_process'; import { RUNNER_LABEL } from '../../agents/labels.ts'; /** - * Force-removes every container, network and volume labelled with one runner owner, containers first, as they hold - * the others in use. 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. + * 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[]) => {