Skip to content

Commit 8f853d6

Browse files
mchwangclaude
andcommitted
Release the profile if the supervisor handoff throws; add signals to runContainer
Review fixes (Copilot, #70): - setUpProfile returned `start(profile)` unguarded. If the handoff threw after the profile was created, the launcher treated it as a failure with nothing allocated and the profile's network and staging leaked. It now disposes the profile, or hands a retryable cleanup to the launcher. - startValidatedContainer and runContainer, the lower-level launch path, took no AbortSignal. Both now accept one and pass it to create, validate and start; cleanup still runs after a cancel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 20256a9 commit 8f853d6

3 files changed

Lines changed: 49 additions & 12 deletions

File tree

‎agents/adapters/setup.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { InvocationHandle } from '../contract.ts';
2-
import { createContainerProfile, ProfileCreationCleanupError, type ContainerProfile,
3-
type ProfileOptions } from '../container/profile.ts';
2+
import { containerProfileResources, createContainerProfile, disposeContainerProfile, ProfileCreationCleanupError,
3+
type ContainerProfile, type ProfileOptions } from '../container/profile.ts';
44
import { createVendorNetwork, removeVendorNetwork, vendorNetworkResources,
55
type VendorNetwork } from '../network/network.ts';
66
import { AdapterSetupCleanupError } from './supervisor.ts';
@@ -34,5 +34,15 @@ export async function setUpProfile(request: AgentAdapterRequest, remaining: () =
3434
}
3535
throw error;
3636
}
37-
return start(profile);
37+
// The profile owns the network and staging now. If the handoff itself throws, nothing else will release them:
38+
// the launcher treats a failure without a handle as "nothing allocated", so release (or retain) them here.
39+
try { return start(profile); }
40+
catch (error) {
41+
try { await disposeContainerProfile(profile, CLEANUP_TIMEOUT_MS); }
42+
catch (cleanupError) {
43+
throw new AdapterSetupCleanupError(error, cleanupError,
44+
(budgetMs = CLEANUP_TIMEOUT_MS) => disposeContainerProfile(profile, budgetMs), () => containerProfileResources(profile));
45+
}
46+
throw error;
47+
}
3848
}

‎agents/container/run.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -379,17 +379,21 @@ export async function createValidatedContainer(profile: ContainerProfile, timeou
379379
}
380380
}
381381

382+
/**
383+
* Validate and start the created container, then remove it. `signal` stops the run: the in-flight Docker call is
384+
* killed, and the container is still removed (cleanup is never cancelled) before the promise rejects.
385+
*/
382386
export async function startValidatedContainer(profile: ContainerProfile, timeoutMs = 60_000,
383-
secrets: Readonly<Record<string, string>> = {}): Promise<string> {
387+
secrets: Readonly<Record<string, string>> = {}, signal?: AbortSignal): Promise<string> {
384388
assertLaunchable(profile);
385389
const remaining = createDeadline(profileTimeout(profile, timeoutMs));
386390
let failure: unknown;
387391
try {
388392
validateSecrets(profile, secrets);
389393
// Validate and start the container this profile created, by ID: a same-named replacement must never run.
390394
const id = requireContainerId(profile);
391-
await validateContainer(id, profile, remaining());
392-
const output = await docker(['start', '--attach', id], { timeoutMs: remaining(), secrets });
395+
await validateContainer(id, profile, remaining(), signal);
396+
const output = await docker(['start', '--attach', id], { timeoutMs: remaining(), secrets, signal });
393397
remaining();
394398
return output;
395399
}
@@ -403,16 +407,17 @@ export async function startValidatedContainer(profile: ContainerProfile, timeout
403407
}
404408
}
405409

410+
/** Create, validate, start and remove the container. `signal` cancels at any step; cleanup still runs. */
406411
export async function runContainer(profile: ContainerProfile, timeoutMs = 60_000,
407-
secrets: Readonly<Record<string, string>> = {}): Promise<string> {
412+
secrets: Readonly<Record<string, string>> = {}, signal?: AbortSignal): Promise<string> {
408413
const remaining = createDeadline(profileTimeout(profile, timeoutMs));
409-
await createValidatedContainer(profile, remaining(), secrets);
414+
await createValidatedContainer(profile, remaining(), secrets, signal);
410415
let startBudget: number;
411416
try { startBudget = remaining(); }
412417
catch (error) {
413418
try { await removeContainerOrThrow(profile); }
414419
catch (cleanupError) { throw new AggregateError([error, cleanupError], 'Agent deadline and cleanup both failed.'); }
415420
throw error;
416421
}
417-
return startValidatedContainer(profile, startBudget, secrets);
422+
return startValidatedContainer(profile, startBudget, secrets, signal);
418423
}

‎test/agent-adapter-cleanup.test.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import type { InvocationResult } from '../agents/contract.ts';
33

44
// When profile creation and its cleanup both fail, the adapter keeps retrying that one cleanup inside the bounded
55
// window. It must not add a second network removal with a fresh deadline on every retry (#51 item 1).
6-
const state = vi.hoisted(() => ({ budgets: [] as { at: number; budget: number }[], networkRemovals: 0 }));
6+
const state = vi.hoisted(() => ({ budgets: [] as { at: number; budget: number }[], networkRemovals: 0,
7+
profileFails: true, profileDisposals: 0 }));
78
vi.mock('../agents/network/network.ts', async importOriginal => ({
89
...await importOriginal<typeof import('../agents/network/network.ts')>(),
910
createVendorNetwork: () => ({ name: 'codeboost-egress-codex-x', proxyContainer: 'codeboost-proxy-codex-x',
@@ -16,7 +17,10 @@ vi.mock('../agents/container/image.ts', async importOriginal => ({
1617
}));
1718
vi.mock('../agents/container/profile.ts', async importOriginal => {
1819
const actual = await importOriginal<typeof import('../agents/container/profile.ts')>();
19-
return { ...actual, createContainerProfile: () => {
20+
return { ...actual, disposeContainerProfile: async () => { state.profileDisposals += 1; },
21+
createContainerProfile: () => {
22+
// Otherwise a profile the supervisor refuses at handoff (not issued by the real builder).
23+
if (!state.profileFails) return { name: 'codeboost-agent-x', network: {}, policy: {} };
2024
throw new actual.ProfileCreationCleanupError(new Error('schema input is not readable'),
2125
new Error('daemon unreachable'), (budgetMs?: number) => {
2226
state.budgets.push({ at: performance.now(), budget: budgetMs ?? 30_000 });
@@ -31,7 +35,7 @@ const { captureInvocation } = await import('../agents/contract.ts');
3135
describe('adapter profile-creation cleanup', () => {
3236
beforeEach(() => {
3337
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });
34-
state.budgets = []; state.networkRemovals = 0;
38+
state.budgets = []; state.networkRemovals = 0; state.profileFails = true; state.profileDisposals = 0;
3539
});
3640
afterEach(() => { vi.useRealTimers(); });
3741

@@ -53,4 +57,22 @@ describe('adapter profile-creation cleanup', () => {
5357
expect(state.budgets.length).toBeGreaterThan(1);
5458
for (const call of state.budgets) expect(call.at + call.budget).toBeLessThanOrEqual(started + CLEANUP_RETRY_WINDOW_MS);
5559
});
60+
61+
it('releases a created profile when the handoff to the supervisor throws', async () => {
62+
state.profileFails = false;
63+
const invocation = captureInvocation({
64+
clone: { id: 'clone', taskId: 'task', directory: '/tmp/task', head: 'a'.repeat(40) },
65+
phase: 'planning', vendor: 'codex', approvedArgv: [], deadline: Date.now() + 10 * 60_000,
66+
attemptId: 'adapter-handoff-throws',
67+
context: { snapshotId: 's', planId: 'p', planRevision: 1, assignmentId: 'a', referencedCodeHash: 'c', stateVersion: 1 },
68+
});
69+
const handle = startCodexInvocation({ invocation, filesystems: {} as never, inputDirectory: '/unused',
70+
imageId: `sha256:${'a'.repeat(64)}`, prompt: 'unused' }, '/unused/auth.json');
71+
const box: { result?: InvocationResult } = {};
72+
void handle.settled.then(result => { box.result = result; });
73+
await vi.advanceTimersByTimeAsync(0);
74+
expect(box.result?.stopReason).toBe('capture-failure');
75+
expect(box.result?.stderr).toContain('trusted profile builder');
76+
expect(state.profileDisposals).toBe(1);
77+
});
5678
});

0 commit comments

Comments
 (0)