Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions agents/adapters/claude.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ export function startClaudeInvocation(request: AgentAdapterRequest,
try { network = createVendorNetwork(request.invocation, request.imageId, Math.min(60_000, remaining())); }
catch (error) {
if (error instanceof VendorNetworkCreationCleanupError)
return retainSetupCleanup(request.invocation, error.retryCleanup, error.startupError, error,
'network creation cleanup');
return retainSetupCleanup(request.invocation, budget => error.retryCleanup(budget), error.startupError, error,
'network creation cleanup', () => error.resources);
throw error;
}
try {
Expand All @@ -38,13 +38,13 @@ export function startClaudeInvocation(request: AgentAdapterRequest,
if (error instanceof ProfileCreationCleanupError) {
const retryCleanup = (networkTimeoutMs = 30_000) => {
const failures: unknown[] = [];
try { error.retryCleanup(); } catch (cleanupError) { failures.push(cleanupError); }
try { error.retryCleanup(networkTimeoutMs); } catch (cleanupError) { failures.push(cleanupError); }
try { removeVendorNetwork(network, networkTimeoutMs); } catch (cleanupError) { failures.push(cleanupError); }
if (failures.length) throw new AggregateError(failures, 'Adapter setup cleanup did not settle.');
};
try { retryCleanup(Math.min(30_000, remaining())); }
catch (cleanupError) { return retainSetupCleanup(request.invocation, () => retryCleanup(),
error.startupError, cleanupError, 'profile and network cleanup'); }
catch (cleanupError) { return retainSetupCleanup(request.invocation, budget => retryCleanup(budget),
error.startupError, cleanupError, 'profile and network cleanup', () => error.resources); }
throw error.startupError;
}
try { removeVendorNetwork(network, Math.min(30_000, remaining())); }
Expand Down
10 changes: 5 additions & 5 deletions agents/adapters/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ export function startCodexInvocation(request: AgentAdapterRequest,
try { network = createVendorNetwork(request.invocation, request.imageId, Math.min(60_000, remaining())); }
catch (error) {
if (error instanceof VendorNetworkCreationCleanupError)
return retainSetupCleanup(request.invocation, error.retryCleanup, error.startupError, error,
'network creation cleanup');
return retainSetupCleanup(request.invocation, budget => error.retryCleanup(budget), error.startupError, error,
'network creation cleanup', () => error.resources);
throw error;
}
try {
Expand All @@ -41,13 +41,13 @@ export function startCodexInvocation(request: AgentAdapterRequest,
if (error instanceof ProfileCreationCleanupError) {
const retryCleanup = (networkTimeoutMs = 30_000) => {
const failures: unknown[] = [];
try { error.retryCleanup(); } catch (cleanupError) { failures.push(cleanupError); }
try { error.retryCleanup(networkTimeoutMs); } catch (cleanupError) { failures.push(cleanupError); }
try { removeVendorNetwork(network, networkTimeoutMs); } catch (cleanupError) { failures.push(cleanupError); }
if (failures.length) throw new AggregateError(failures, 'Adapter setup cleanup did not settle.');
};
try { retryCleanup(Math.min(30_000, remaining())); }
catch (cleanupError) { return retainSetupCleanup(request.invocation, () => retryCleanup(),
error.startupError, cleanupError, 'profile and network cleanup'); }
catch (cleanupError) { return retainSetupCleanup(request.invocation, budget => retryCleanup(budget),
error.startupError, cleanupError, 'profile and network cleanup', () => error.resources); }
throw error.startupError;
}
try { removeVendorNetwork(network, Math.min(30_000, remaining())); }
Expand Down
179 changes: 105 additions & 74 deletions agents/adapters/supervisor.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { execFile, spawn, type ChildProcess } from 'node:child_process';
import type { InvocationHandle, InvocationInput, InvocationResult, StopReason } from '../contract.ts';
import type { InvocationHandle, InvocationInput, InvocationResult, StopReason,
UnreleasedResource } from '../contract.ts';
import { assertPhasePolicy } from '../policy.ts';
import { createValidatedContainer, disposeValidatedContainer, validateContainer } from '../container/run.ts';
import { assertContainerProfileAuthenticity, disposeContainerProfile, isContainerProfileAuthentic,
type ContainerProfile } from '../container/profile.ts';
import { removeVendorNetwork, type VendorNetwork } from '../network/network.ts';
import { agentContainerResources, createValidatedContainer, disposeValidatedContainer,
validateContainer } from '../container/run.ts';
import { assertContainerProfileAuthenticity, containerProfileResources, disposeContainerProfile,
isContainerProfileAuthentic, type ContainerProfile } from '../container/profile.ts';
import { removeVendorNetwork, vendorNetworkResources, type VendorNetwork } from '../network/network.ts';

export const OUTPUT_LIMITS = Object.freeze({
stdoutBytes: 16 * 1024 * 1024,
Expand All @@ -16,6 +18,8 @@ const CAPTURE_ABORT_GRACE_MS = 1_000;
const DIAGNOSTIC_BYTES = 1024;
const active = new Map<string, InvocationHandle>();
const activeProfiles = new WeakSet<ContainerProfile>();
// Profiles that settled with cleanup unconfirmed. They stay authentic, so this stops a second launch from reusing one.
const spentProfiles = new WeakSet<ContainerProfile>();
const cleanupRecoveries = new Set<InvocationHandle>();
const hasCleanupRecovery = (attemptId: string) =>
Array.from(cleanupRecoveries).some(handle => handle.attemptId === attemptId);
Expand Down Expand Up @@ -89,40 +93,61 @@ export class ByteCollector {
get blockCount(): number { return this.blocks.length; }
}

// `cleanup` is what recovery retries: container-level disposal by default, or profile-only disposal for a
// rejection that happened before this profile created any container.
const retainCleanupOwnership = (profile: ContainerProfile, detail: string, register = true,
cleanup: (profile: ContainerProfile) => void = disposeValidatedContainer): InvocationHandle => {
const invocation = assertPhasePolicy(profile.policy);
/** How often unconfirmed cleanup is retried. */
const CLEANUP_RETRY_INTERVAL_MS = 1_000;
/**
* How long cleanup is retried after its first failure before the handle settles anyway, reporting what it could not
* remove. Without this bound an unreachable daemon would keep `settled` pending forever.
*/
export const CLEANUP_RETRY_WINDOW_MS = 60_000;
const cleanupWindowDetail = () => `cleanup was not confirmed within ${CLEANUP_RETRY_WINDOW_MS / 1_000} s`;

/**
* Own an attempt while retrying cleanup that has already failed once. Settles when cleanup succeeds, or when the
* retry window ends, with `unreleased` listing what may remain. `cleanup` receives the budget left in the window.
*/
const retainCleanup = (invocation: InvocationInput, cleanup: (budgetMs: number) => void, detail: string,
resources: () => readonly UnreleasedResource[], register: boolean,
released?: (unreleased: boolean) => void): InvocationHandle => {
let resolveSettled!: (result: InvocationResult) => void, cleaning = false, complete = false;
let cancelReason: StopReason | undefined;
let handle!: InvocationHandle;
let timer: ReturnType<typeof setTimeout> | undefined;
const giveUpAt = performance.now() + CLEANUP_RETRY_WINDOW_MS;
const settled = new Promise<InvocationResult>(resolve => { resolveSettled = resolve; });
const finish = (unreleased: boolean) => {
if (timer) clearTimeout(timer);
timer = undefined;
complete = true;
if (active.get(invocation.attemptId) === handle) active.delete(invocation.attemptId);
cleanupRecoveries.delete(handle);
const remainingResources = unreleased ? resources() : [];
released?.(unreleased);
const reason = cancelReason ?? 'capture-failure';
resolveSettled(Object.freeze({ attemptId: invocation.attemptId, context: invocation.context,
exitCode: null, signal: null, stopReason: reason, stdout: '',
stderr: diagnosticFor(reason, unreleased ? `${cleanupWindowDetail()}: ${detail}` : detail).toString('utf8'),
...(unreleased ? { unreleased: remainingResources } : {}) }));
};
const schedule = () => {
if (timer) return;
timer = setTimeout(() => { timer = undefined; retry(); }, 1_000);
if (timer || complete) return;
timer = setTimeout(() => { timer = undefined; retry(); }, CLEANUP_RETRY_INTERVAL_MS);
};
const retry = () => {
if (cleaning || complete) return;
const budget = cleanupBudget(giveUpAt);
// No attempt starts once the window has ended, so none can run past it.
if (budget < 1) { finish(true); return; }
cleaning = true;
try {
cleanup(profile);
if (timer) clearTimeout(timer);
timer = undefined;
complete = true;
if (active.get(invocation.attemptId) === handle) active.delete(invocation.attemptId);
activeProfiles.delete(profile);
cleanupRecoveries.delete(handle);
resolveSettled(Object.freeze({ attemptId: invocation.attemptId, context: invocation.context,
exitCode: null, signal: null, stopReason: cancelReason ?? 'capture-failure', stdout: '',
stderr: diagnosticFor(cancelReason ?? 'capture-failure', detail).toString('utf8') }));
} catch {
try { cleanup(budget); }
catch {
cleaning = false;
schedule();
if (performance.now() >= giveUpAt) finish(true);
else schedule();
return;
}
cleaning = false;
finish(false);
};
handle = Object.freeze({ attemptId: invocation.attemptId, settled,
cancel: (reason: StopReason) => {
Expand All @@ -131,63 +156,49 @@ const retainCleanupOwnership = (profile: ContainerProfile, detail: string, regis
timer = undefined;
retry();
} });
activeProfiles.add(profile);
if (register) active.set(invocation.attemptId, handle);
else cleanupRecoveries.add(handle);
schedule();
return handle;
};
/** A retry's Docker budget: what is left of the window, at most the usual 30 s; below 1 when the window has ended. */
const cleanupBudget = (giveUpAt: number) => Math.min(30_000, Math.floor(giveUpAt - performance.now()));
/** Everything a profile may still own, including its agent container only if this profile created one. */
const profileResources = (profile: ContainerProfile) =>
Object.freeze([...agentContainerResources(profile), ...containerProfileResources(profile)]);

// `cleanup` is what recovery retries: container-level disposal by default, or profile-only disposal for a
// rejection that happened before this profile created any container.
const retainCleanupOwnership = (profile: ContainerProfile, detail: string, register = true,
cleanup: (profile: ContainerProfile, budgetMs: number) => void = disposeValidatedContainer): InvocationHandle => {
const invocation = assertPhasePolicy(profile.policy);
activeProfiles.add(profile);
return retainCleanup(invocation, budget => cleanup(profile, budget), detail, () => profileResources(profile),
register, unreleased => {
activeProfiles.delete(profile);
if (unreleased) spentProfiles.add(profile);
});
};

/** Retain attempt ownership while retrying a network allocated before profile construction failed. */
export function retainNetworkCleanup(invocation: InvocationInput, network: VendorNetwork,
startupError: unknown, cleanupError: unknown): InvocationHandle {
return retainSetupCleanup(invocation, () => removeVendorNetwork(network), startupError, cleanupError,
'network cleanup');
return retainCleanup(invocation, budget => removeVendorNetwork(network, budget),
`Adapter startup failed and network cleanup remains unsettled: ${String(startupError)}; ${String(cleanupError)}`,
() => vendorNetworkResources(network), !ownsAttempt(invocation.attemptId));
}

/** Retain attempt ownership while retrying resources allocated during synchronous adapter setup. */
export function retainSetupCleanup(invocation: InvocationInput, retryCleanup: () => void,
startupError: unknown, cleanupError: unknown, kind = 'setup cleanup'): InvocationHandle {
const register = !ownsAttempt(invocation.attemptId);
let resolveSettled!: (result: InvocationResult) => void, cleaning = false, complete = false;
let cancelReason: StopReason | undefined;
let handle!: InvocationHandle;
let timer: ReturnType<typeof setTimeout> | undefined;
const settled = new Promise<InvocationResult>(resolve => { resolveSettled = resolve; });
const detail = `Adapter startup failed and ${kind} remains unsettled: ${String(startupError)}; ${String(cleanupError)}`;
const retry = () => {
if (cleaning || complete) return;
cleaning = true;
try {
retryCleanup();
if (timer) clearTimeout(timer);
timer = undefined;
complete = true;
if (active.get(invocation.attemptId) === handle) active.delete(invocation.attemptId);
cleanupRecoveries.delete(handle);
resolveSettled(Object.freeze({ attemptId: invocation.attemptId, context: invocation.context,
exitCode: null, signal: null, stopReason: cancelReason ?? 'capture-failure', stdout: '',
stderr: diagnosticFor(cancelReason ?? 'capture-failure', detail).toString('utf8') }));
} catch {
cleaning = false;
if (!timer) {
timer = setTimeout(() => { timer = undefined; retry(); }, 1_000);
}
return;
}
cleaning = false;
};
handle = Object.freeze({ attemptId: invocation.attemptId, settled,
cancel: (reason: StopReason) => {
cancelReason ??= reason;
if (timer) clearTimeout(timer);
timer = undefined;
retry();
} });
if (register) active.set(invocation.attemptId, handle);
else cleanupRecoveries.add(handle);
timer = setTimeout(() => { timer = undefined; retry(); }, 1_000);
return handle;
/**
* Retain attempt ownership while retrying resources allocated during synchronous adapter setup. `retryCleanup`
* receives the budget left in the retry window and must not run past it. `resources` is read when the window ends,
* so it reports only what is still unconfirmed then.
*/
export function retainSetupCleanup(invocation: InvocationInput, retryCleanup: (budgetMs: number) => void,
startupError: unknown, cleanupError: unknown, kind = 'setup cleanup',
resources: readonly UnreleasedResource[] | (() => readonly UnreleasedResource[]) = []): InvocationHandle {
return retainCleanup(invocation, budget => retryCleanup(budget),
`Adapter startup failed and ${kind} remains unsettled: ${String(startupError)}; ${String(cleanupError)}`,
typeof resources === 'function' ? resources : () => resources, !ownsAttempt(invocation.attemptId));
}
const withDiagnostic = (stderr: Buffer, stdoutBytes: number, reason: StopReason, limits: CaptureLimits,
detail?: string) => {
Expand Down Expand Up @@ -248,6 +259,8 @@ export function isInvocationActive(attemptId: string): boolean {

export function startProfileInvocation(profile: ContainerProfile, options: SupervisorOptions = {}): InvocationHandle {
assertContainerProfileAuthenticity(profile);
if (spentProfiles.has(profile))
throw new Error('This container profile settled without confirmed cleanup; start a new profile.');
const invocation = assertPhasePolicy(profile.policy);
// Rejections before container creation own no container, so they release (and retry) only the profile's own
// staging and network; a name held by another invocation or a failing inspect cannot block that.
Expand Down Expand Up @@ -567,18 +580,36 @@ export function startProfileInvocation(profile: ContainerProfile, options: Super
if (decodedOutput.providerFailed) exitCode = exitCode === 0 ? 1 : exitCode;
}
await Promise.all([...controls]);
let giveUpAt: number | undefined, unreleased: readonly UnreleasedResource[] | undefined;
while (true) {
const budget = giveUpAt === undefined ? 30_000 : cleanupBudget(giveUpAt);
if (budget < 1) {
// The window ended between attempts: report instead of starting one that would run past it.
unreleased = profileResources(profile);
spentProfiles.add(profile);
failureDetail = `${cleanupWindowDetail()}: ${failureDetail}`;
wakeCleanup = undefined;
break;
}
try {
disposeValidatedContainer(profile);
disposeValidatedContainer(profile, budget);
wakeCleanup = undefined;
break;
} catch (error) {
stopReason ??= 'capture-failure';
failureDetail ??= error instanceof Error ? error.message : String(error);
giveUpAt ??= performance.now() + CLEANUP_RETRY_WINDOW_MS;
if (performance.now() >= giveUpAt) {
wakeCleanup = undefined;
unreleased = profileResources(profile);
spentProfiles.add(profile);
failureDetail = `${cleanupWindowDetail()}: ${failureDetail}`;
break;
}
await new Promise<void>(resolve => {
let finished = false;
const wake = () => { if (finished) return; finished = true; clearTimeout(timer); resolve(); };
const timer = setTimeout(wake, 1_000);
const timer = setTimeout(wake, CLEANUP_RETRY_INTERVAL_MS);
wakeCleanup = wake;
});
}
Expand All @@ -600,7 +631,7 @@ export function startProfileInvocation(profile: ContainerProfile, options: Super
if (stopReason) finalStderr = withDiagnostic(finalStderr, finalStdout.length, stopReason, limits, failureDetail);
const result = Object.freeze({ attemptId: invocation.attemptId, context: invocation.context,
exitCode, signal: finalSignal, ...(stopReason ? { stopReason } : {}),
stdout: finalStdout.toString('utf8'), stderr: finalStderr.toString('utf8') });
stdout: finalStdout.toString('utf8'), stderr: finalStderr.toString('utf8'), ...(unreleased ? { unreleased } : {}) });
settlementComplete = true;
activeProfiles.delete(profile);
active.delete(invocation.attemptId);
Expand Down
Loading
Loading