Skip to content

Commit b161e52

Browse files
mchwangclaude
andcommitted
Refuse every launch path for a profile that settled with leftovers
Review fix (Copilot, #69): the guard against relaunching a profile whose invocation settled with `unreleased` resources lived only in startProfileInvocation. createValidatedContainer, startValidatedContainer and runContainer could still create or start the leftover container that recovery owns. The retired-profile state now lives in run.ts and every launch entry point checks it before doing any work; cleanup remains allowed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5a942dc commit b161e52

4 files changed

Lines changed: 30 additions & 8 deletions

File tree

‎agents/adapters/supervisor.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { InvocationHandle, InvocationInput, InvocationResult, StopReason,
33
UnreleasedResource } from '../contract.ts';
44
import { assertPhasePolicy } from '../policy.ts';
55
import { agentContainerId, agentContainerResources, createValidatedContainer, disposeValidatedContainer,
6-
validateContainer } from '../container/run.ts';
6+
isContainerProfileRetired, retireContainerProfile, validateContainer } from '../container/run.ts';
77
import { assertContainerProfileAuthenticity, containerProfileResources, disposeContainerProfile,
88
isContainerProfileAuthentic, type ContainerProfile } from '../container/profile.ts';
99
import { removeVendorNetwork, vendorNetworkResources, type VendorNetwork } from '../network/network.ts';
@@ -18,8 +18,6 @@ const CAPTURE_ABORT_GRACE_MS = 1_000;
1818
const DIAGNOSTIC_BYTES = 1024;
1919
const active = new Map<string, InvocationHandle>();
2020
const activeProfiles = new WeakSet<ContainerProfile>();
21-
// Profiles that settled with cleanup unconfirmed. They stay authentic, so this stops a second launch from reusing one.
22-
const spentProfiles = new WeakSet<ContainerProfile>();
2321
const cleanupRecoveries = new Set<InvocationHandle>();
2422
const hasCleanupRecovery = (attemptId: string) =>
2523
Array.from(cleanupRecoveries).some(handle => handle.attemptId === attemptId);
@@ -176,7 +174,7 @@ const retainCleanupOwnership = (profile: ContainerProfile, detail: string, regis
176174
return retainCleanup(invocation, budget => cleanup(profile, budget), detail, () => profileResources(profile),
177175
register, unreleased => {
178176
activeProfiles.delete(profile);
179-
if (unreleased) spentProfiles.add(profile);
177+
if (unreleased) retireContainerProfile(profile);
180178
});
181179
};
182180

@@ -259,7 +257,8 @@ export function isInvocationActive(attemptId: string): boolean {
259257

260258
export function startProfileInvocation(profile: ContainerProfile, options: SupervisorOptions = {}): InvocationHandle {
261259
assertContainerProfileAuthenticity(profile);
262-
if (spentProfiles.has(profile))
260+
// A profile that settled with cleanup unconfirmed is retired for every launch path (run.ts), not only this one.
261+
if (isContainerProfileRetired(profile))
263262
throw new Error('This container profile settled without confirmed cleanup; start a new profile.');
264263
const invocation = assertPhasePolicy(profile.policy);
265264
// Rejections before container creation own no container, so they release (and retry) only the profile's own
@@ -591,7 +590,7 @@ export function startProfileInvocation(profile: ContainerProfile, options: Super
591590
if (budget < 1) {
592591
// The window ended between attempts: report instead of starting one that would run past it.
593592
unreleased = profileResources(profile);
594-
spentProfiles.add(profile);
593+
retireContainerProfile(profile);
595594
failureDetail = `${cleanupWindowDetail()}: ${failureDetail}`;
596595
wakeCleanup = undefined;
597596
break;
@@ -607,7 +606,7 @@ export function startProfileInvocation(profile: ContainerProfile, options: Super
607606
if (performance.now() >= giveUpAt) {
608607
wakeCleanup = undefined;
609608
unreleased = profileResources(profile);
610-
spentProfiles.add(profile);
609+
retireContainerProfile(profile);
611610
failureDetail = `${cleanupWindowDetail()}: ${failureDetail}`;
612611
break;
613612
}

‎agents/container/run.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,18 @@ const requireContainerId = (profile: ContainerProfile) => {
7373
return id;
7474
};
7575

76+
// Profiles that settled with cleanup unconfirmed. They stay authentic so their cleanup can still run and be recovered,
77+
// but no launch path may create or start a container for one again.
78+
const retiredProfiles = new WeakSet<ContainerProfile>();
79+
/** Mark a profile whose invocation settled with `unreleased` resources: it can be cleaned up, never launched. */
80+
export function retireContainerProfile(profile: ContainerProfile): void { retiredProfiles.add(profile); }
81+
export function isContainerProfileRetired(profile: ContainerProfile): boolean { return retiredProfiles.has(profile); }
82+
// Checked before any launch work, so a refusal owns nothing and triggers no cleanup.
83+
const assertLaunchable = (profile: ContainerProfile) => {
84+
if (retiredProfiles.has(profile))
85+
throw new Error('This container profile settled without confirmed cleanup; start a new profile.');
86+
};
87+
7688
/** The agent container this profile may have created, for reporting when its removal is not confirmed. */
7789
export function agentContainerResources(profile: ContainerProfile): readonly UnreleasedResource[] {
7890
if (!createdContainers.has(profile)) return Object.freeze([]);
@@ -336,6 +348,7 @@ export function validateContainer(container: string, profile: ContainerProfile,
336348

337349
export function createValidatedContainer(profile: ContainerProfile, timeoutMs = 30_000,
338350
secrets: Readonly<Record<string, string>> = {}): string {
351+
assertLaunchable(profile);
339352
const remaining = createDeadline(profileTimeout(profile, timeoutMs));
340353
let createUnsettled = false;
341354
try {
@@ -369,6 +382,7 @@ export function createValidatedContainer(profile: ContainerProfile, timeoutMs =
369382

370383
export function startValidatedContainer(profile: ContainerProfile, timeoutMs = 60_000,
371384
secrets: Readonly<Record<string, string>> = {}): string {
385+
assertLaunchable(profile);
372386
const remaining = createDeadline(profileTimeout(profile, timeoutMs));
373387
let failure: unknown;
374388
try {

‎test/agent-settlement-supervisor.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { ContainerProfile } from '../agents/container/profile.ts';
88
// so cleanup can be made to fail forever, and the container exits as soon as it starts.
99
const state = vi.hoisted(() => ({
1010
created: new WeakSet<object>(),
11+
retired: new WeakSet<object>(),
1112
createFails: false,
1213
budgets: [] as number[],
1314
}));
@@ -36,6 +37,8 @@ vi.mock('../agents/container/run.ts', () => ({
3637
state.budgets.push(budget);
3738
throw new Error('Cannot connect to the Docker daemon');
3839
},
40+
retireContainerProfile: (profile: object) => { state.retired.add(profile); },
41+
isContainerProfileRetired: (profile: object) => state.retired.has(profile),
3942
agentContainerId: (profile: object) => state.created.has(profile) ? 'c'.repeat(64) : undefined,
4043
agentContainerResources: (profile: { name: string }) => state.created.has(profile)
4144
? [{ kind: 'container', name: profile.name, id: 'c'.repeat(64),

‎test/agent-supervisor.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ import { captureInvocation, type InvocationInput } from '../agents/contract.ts';
1111
import { buildAgentImage } from '../agents/container/image.ts';
1212
import { createContainerProfile, disposeContainerProfile, isContainerProfileAuthentic,
1313
type ContainerProfile } from '../agents/container/profile.ts';
14-
import { disposeValidatedContainer, prepareTaskFilesystems, removeTaskFilesystems } from '../agents/container/run.ts';
14+
import { createValidatedContainer, disposeValidatedContainer, prepareTaskFilesystems, removeTaskFilesystems, runContainer,
15+
startValidatedContainer } from '../agents/container/run.ts';
1516
import { createVendorNetwork } from '../agents/network/network.ts';
1617
import { createIsolationProbeCommand, createPhasePolicy, type IsolationProbe } from '../agents/policy.ts';
1718
import { createTaskClone } from '../git/clone.ts';
@@ -181,6 +182,11 @@ describe('container invocation supervisor', () => {
181182
expect(result.unreleased).toEqual(expected);
182183
expect(isInvocationActive('unreachable-daemon')).toBe(false);
183184
expect(() => startProfileInvocation(current)).toThrow('settled without confirmed cleanup');
185+
// Every launch path refuses it, before touching the leftover container that recovery still owns.
186+
expect(() => startValidatedContainer(current)).toThrow('settled without confirmed cleanup');
187+
expect(() => createValidatedContainer(current)).toThrow('settled without confirmed cleanup');
188+
expect(() => runContainer(current)).toThrow('settled without confirmed cleanup');
189+
expect(spawnSync('docker', ['container', 'inspect', current.name]).status).toBe(0);
184190
// The container ignored SIGTERM and the stop never reached the daemon, so it is still there to remove.
185191
disposeValidatedContainer(current);
186192
expect(spawnSync('docker', ['container', 'inspect', current.name]).status).not.toBe(0);

0 commit comments

Comments
 (0)