|
| 1 | +import { EventEmitter } from 'node:events'; |
| 2 | +import { PassThrough } from 'node:stream'; |
| 3 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 4 | +import type { InvocationResult } from '../agents/contract.ts'; |
| 5 | +import type { ContainerProfile } from '../agents/container/profile.ts'; |
| 6 | + |
| 7 | +// Replays, without Docker, the interleavings of the deferred-output acknowledgement with the container's exit. The |
| 8 | +// wrapper (probe.sh) exits as soon as it sees the acknowledgement, and that exit can kill the acknowledging |
| 9 | +// `docker exec` before it reports success; CI run 36470233043 failed that way. |
| 10 | +type FakeChild = EventEmitter & { stdout: PassThrough; stderr: PassThrough; kill: ReturnType<typeof vi.fn> }; |
| 11 | +const state = vi.hoisted(() => ({ |
| 12 | + attach: undefined as FakeChild | undefined, |
| 13 | + acknowledgements: [] as { child: FakeChild; args: readonly string[] }[], |
| 14 | +})); |
| 15 | +vi.mock('node:child_process', () => ({ |
| 16 | + execFile: vi.fn(), |
| 17 | + spawn: vi.fn((_command: string, args: readonly string[]) => { |
| 18 | + const child = Object.assign(new EventEmitter(), { stdout: new PassThrough(), stderr: new PassThrough(), kill: vi.fn() }); |
| 19 | + if (args[0] === 'start') state.attach = child; |
| 20 | + else if (args[0] === 'exec') state.acknowledgements.push({ child, args }); |
| 21 | + else process.nextTick(() => child.emit('close', 0, null)); |
| 22 | + return child; |
| 23 | + }), |
| 24 | +})); |
| 25 | +vi.mock('../agents/policy.ts', () => ({ assertPhasePolicy: (policy: { invocation: unknown }) => policy.invocation })); |
| 26 | +vi.mock('../agents/container/profile.ts', () => ({ |
| 27 | + assertContainerProfileAuthenticity: () => {}, |
| 28 | + isContainerProfileAuthentic: () => true, |
| 29 | + disposeContainerProfile: async () => {}, |
| 30 | + containerProfileResources: () => [], |
| 31 | +})); |
| 32 | +vi.mock('../agents/container/run.ts', () => ({ |
| 33 | + createValidatedContainer: async () => {}, |
| 34 | + validateContainer: async () => {}, |
| 35 | + disposeValidatedContainer: async () => {}, |
| 36 | + retireContainerProfile: () => {}, |
| 37 | + isContainerProfileRetired: () => false, |
| 38 | + agentContainerId: () => 'c'.repeat(64), |
| 39 | + agentContainerResources: () => [], |
| 40 | +})); |
| 41 | +const { startProfileInvocation } = await import('../agents/adapters/supervisor.ts'); |
| 42 | + |
| 43 | +const token = '11111111-2222-3333-4444-555555555555'; |
| 44 | +const fakeProfile = (attemptId: string) => ({ |
| 45 | + name: `codeboost-agent-${attemptId}`, deferredOutput: true, resources: [], |
| 46 | + policy: { invocation: { attemptId, deadline: Date.now() + 10 * 60_000, |
| 47 | + context: { snapshotId: 's', planId: 'p', planRevision: 1, assignmentId: 'a', referencedCodeHash: 'c', stateVersion: 1 } } }, |
| 48 | +}) as unknown as ContainerProfile; |
| 49 | + |
| 50 | +describe('deferred output acknowledgement', () => { |
| 51 | + beforeEach(() => { |
| 52 | + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); |
| 53 | + state.attach = undefined; |
| 54 | + state.acknowledgements = []; |
| 55 | + }); |
| 56 | + afterEach(() => { vi.useRealTimers(); }); |
| 57 | + |
| 58 | + /** Start an invocation whose agent writes newline-free stderr, then READY with `status`. */ |
| 59 | + const readyInvocation = async (attemptId: string, status = 0, timeoutMs?: number) => { |
| 60 | + const box: { result?: InvocationResult } = {}; |
| 61 | + void startProfileInvocation(fakeProfile(attemptId), { timeoutMs, decode: () => ({ text: 'captured' }) }) |
| 62 | + .settled.then(result => { box.result = result; }); |
| 63 | + await vi.advanceTimersByTimeAsync(0); |
| 64 | + const stderr = state.attach!.stderr; |
| 65 | + stderr.emit('data', Buffer.from(`\x1eCODEBOOST_START:${token}\x1e\n`)); |
| 66 | + stderr.emit('data', Buffer.from('trailing-diagnostic')); |
| 67 | + stderr.emit('data', Buffer.from(`\n\x1eCODEBOOST_READY:${token}:${status}\x1e\n`)); |
| 68 | + await vi.advanceTimersByTimeAsync(0); |
| 69 | + // The decoded output was collected, so the supervisor acknowledges it with the READY token. |
| 70 | + expect(state.acknowledgements).toHaveLength(1); |
| 71 | + expect(state.acknowledgements[0]!.args.at(-1)).toBe(token); |
| 72 | + return box; |
| 73 | + }; |
| 74 | + const acknowledgementExits = (index: number, code: number | null, signal: NodeJS.Signals | null = null) => |
| 75 | + state.acknowledgements[index]!.child.emit('close', code, signal); |
| 76 | + const containerExits = (code: number | null, signal: NodeJS.Signals | null = null) => |
| 77 | + state.attach!.emit('close', code, signal); |
| 78 | + |
| 79 | + it.each([ |
| 80 | + ['before the container exit is observed', 'acknowledgement-first'], |
| 81 | + ['after the container exit is observed', 'exit-first'], |
| 82 | + ] as const)('keeps the result when the wrapper takes the acknowledgement and its exec then fails %s', |
| 83 | + async (_label, order) => { |
| 84 | + const box = await readyInvocation(`ack-killed-${order}`); |
| 85 | + // The wrapper saw the acknowledgement and exited with the READY status; the teardown killed the exec. |
| 86 | + if (order === 'acknowledgement-first') { acknowledgementExits(0, 137); containerExits(0); } |
| 87 | + else { containerExits(0); acknowledgementExits(0, 137); } |
| 88 | + await vi.advanceTimersByTimeAsync(0); |
| 89 | + expect(box.result?.stopReason, box.result?.stderr).toBeUndefined(); |
| 90 | + expect(box.result?.exitCode).toBe(0); |
| 91 | + expect(box.result?.stdout).toBe('captured'); |
| 92 | + expect(box.result?.stderr).toBe('trailing-diagnostic\n'); |
| 93 | + // Nothing retries once the container has exited. |
| 94 | + await vi.advanceTimersByTimeAsync(5_000); |
| 95 | + expect(state.acknowledgements).toHaveLength(1); |
| 96 | + }); |
| 97 | + |
| 98 | + it('retries an acknowledgement that failed while the container keeps waiting for it', async () => { |
| 99 | + const box = await readyInvocation('ack-retried'); |
| 100 | + acknowledgementExits(0, 1); |
| 101 | + await vi.advanceTimersByTimeAsync(0); |
| 102 | + expect(box.result).toBeUndefined(); |
| 103 | + await vi.advanceTimersByTimeAsync(250); |
| 104 | + expect(state.acknowledgements).toHaveLength(2); |
| 105 | + expect(state.acknowledgements[1]!.args.at(-1)).toBe(token); |
| 106 | + acknowledgementExits(1, 0); |
| 107 | + containerExits(0); |
| 108 | + await vi.advanceTimersByTimeAsync(0); |
| 109 | + expect(box.result?.stopReason, box.result?.stderr).toBeUndefined(); |
| 110 | + expect(box.result?.stderr).toBe('trailing-diagnostic\n'); |
| 111 | + }); |
| 112 | + |
| 113 | + it('reports the READY status of an agent that failed', async () => { |
| 114 | + const box = await readyInvocation('ack-nonzero', 3); |
| 115 | + acknowledgementExits(0, 0); |
| 116 | + containerExits(3); |
| 117 | + await vi.advanceTimersByTimeAsync(0); |
| 118 | + expect(box.result?.stopReason, box.result?.stderr).toBeUndefined(); |
| 119 | + expect(box.result?.exitCode).toBe(3); |
| 120 | + }); |
| 121 | + |
| 122 | + it.each([ |
| 123 | + ['an exit status other than READY', 137, null], |
| 124 | + ['a signal', null, 'SIGKILL'], |
| 125 | + ] as const)('fails closed when the container exits with %s instead of taking the acknowledgement', |
| 126 | + async (_label, code, signal) => { |
| 127 | + const box = await readyInvocation(`ack-bypassed-${signal ?? code}`); |
| 128 | + acknowledgementExits(0, 137); |
| 129 | + containerExits(code, signal); |
| 130 | + await vi.advanceTimersByTimeAsync(0); |
| 131 | + expect(box.result?.stopReason).toBe('capture-failure'); |
| 132 | + expect(box.result?.stderr).toContain('trailing-diagnostic\n'); |
| 133 | + expect(box.result?.stderr).toContain('Container exited without taking the deferred output acknowledgement.'); |
| 134 | + }); |
| 135 | + |
| 136 | + it('times out instead of succeeding when no acknowledgement ever takes effect', async () => { |
| 137 | + const box = await readyInvocation('ack-never', 0, 5_000); |
| 138 | + for (let index = 0; index < 4; index += 1) { |
| 139 | + acknowledgementExits(index, 1); |
| 140 | + await vi.advanceTimersByTimeAsync(250); |
| 141 | + } |
| 142 | + expect(state.acknowledgements).toHaveLength(5); |
| 143 | + await vi.advanceTimersByTimeAsync(5_000); |
| 144 | + expect(box.result).toBeUndefined(); |
| 145 | + // The deadline stopped the container, which exits by signal and ends the last attempt without a retry. |
| 146 | + acknowledgementExits(4, 137); |
| 147 | + containerExits(null, 'SIGKILL'); |
| 148 | + await vi.advanceTimersByTimeAsync(0); |
| 149 | + expect(box.result?.stopReason).toBe('timeout'); |
| 150 | + expect(box.result?.stderr).toContain('trailing-diagnostic\n'); |
| 151 | + expect(box.result?.stderr).toContain('Deferred output acknowledgement failed 4 times.'); |
| 152 | + }); |
| 153 | +}); |
0 commit comments