Skip to content

Commit c3b3f79

Browse files
committed
fix(execution): stop waiting for fetch decisions at the execution deadline
1 parent 17d8d05 commit c3b3f79

2 files changed

Lines changed: 90 additions & 30 deletions

File tree

‎apps/sim/lib/execution/isolated-vm.test.ts‎

Lines changed: 69 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,34 @@ function createReadyFetchProxyProc(fetchMessage: { url: string; optionsJson?: st
177177
return proc
178178
}
179179

180+
/** A worker whose code starts a POST it never awaits and returns at once. */
181+
function createUnawaitedFetchProc(): MockProc {
182+
const proc = createBaseProc()
183+
proc.send = (message: unknown) => {
184+
const msg = message as { type?: string; executionId?: number }
185+
if (msg.type === 'execute') {
186+
setImmediate(() => {
187+
proc.emit('message', {
188+
type: 'fetch',
189+
executionId: msg.executionId,
190+
fetchId: 1,
191+
requestId: 'req-unawaited',
192+
url: 'https://hook.example/write',
193+
optionsJson: JSON.stringify({ method: 'POST' }),
194+
})
195+
proc.emit('message', {
196+
type: 'result',
197+
executionId: msg.executionId,
198+
result: { result: 'returned', stdout: '' },
199+
})
200+
})
201+
}
202+
return true
203+
}
204+
setImmediate(() => proc.emit('message', { type: 'ready' }))
205+
return proc
206+
}
207+
180208
const { mockSpawn, mockExecSync } = vi.hoisted(() => ({
181209
mockSpawn: vi.fn(),
182210
mockExecSync: vi.fn(() => Buffer.from('v23.11.0')),
@@ -1101,33 +1129,9 @@ describe('isolated-vm scheduler', () => {
11011129
})
11021130

11031131
it('returns a result only once the fetch policy decided a request the code never awaited', async () => {
1104-
const unawaitedFetchProc = () => {
1105-
const proc = createBaseProc()
1106-
proc.send = (message: unknown) => {
1107-
const msg = message as { type?: string; executionId?: number }
1108-
if (msg.type === 'execute') {
1109-
setImmediate(() => {
1110-
proc.emit('message', {
1111-
type: 'fetch',
1112-
executionId: msg.executionId,
1113-
fetchId: 1,
1114-
requestId: 'req-unawaited',
1115-
url: 'https://hook.example/write',
1116-
optionsJson: JSON.stringify({ method: 'POST' }),
1117-
})
1118-
proc.emit('message', {
1119-
type: 'result',
1120-
executionId: msg.executionId,
1121-
result: { result: 'returned', stdout: '' },
1122-
})
1123-
})
1124-
}
1125-
return true
1126-
}
1127-
setImmediate(() => proc.emit('message', { type: 'ready' }))
1128-
return proc
1129-
}
1130-
const { executeInIsolatedVM } = await loadExecutionModule({ spawns: [unawaitedFetchProc] })
1132+
const { executeInIsolatedVM } = await loadExecutionModule({
1133+
spawns: [createUnawaitedFetchProc],
1134+
})
11311135
inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({
11321136
isValid: true,
11331137
resolvedIP: '93.184.216.34',
@@ -1167,6 +1171,44 @@ describe('isolated-vm scheduler', () => {
11671171
expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled()
11681172
})
11691173

1174+
it('stops waiting for an unawaited request’s decision at the execution’s deadline', async () => {
1175+
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
1176+
try {
1177+
const { executeInIsolatedVM } = await loadExecutionModule({
1178+
spawns: [createUnawaitedFetchProc],
1179+
})
1180+
inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({
1181+
isValid: true,
1182+
resolvedIP: '93.184.216.34',
1183+
originalHostname: 'hook.example',
1184+
})
1185+
const decided: string[] = []
1186+
1187+
const running = executeInIsolatedVM(
1188+
{
1189+
code: 'fetch("https://hook.example/write", { method: "POST" }); return "returned"',
1190+
params: {},
1191+
envVars: {},
1192+
contextVariables: {},
1193+
timeoutMs: 100,
1194+
requestId: 'req-unawaited-slow',
1195+
},
1196+
{
1197+
fetchPolicy: (request) => {
1198+
decided.push(request.method)
1199+
return new Promise<'stub'>(() => {})
1200+
},
1201+
}
1202+
)
1203+
await vi.waitFor(() => expect(decided).toEqual(['POST']))
1204+
await vi.advanceTimersByTimeAsync(1100)
1205+
1206+
expect((await running).result).toBe('returned')
1207+
} finally {
1208+
vi.useRealTimers()
1209+
}
1210+
})
1211+
11701212
it('does not log a resolved secret from a failed fetch URL or error', async () => {
11711213
const secret = 'fetch-path-secret-value'
11721214
const requestUrl = `https://example.com/${secret}`

‎apps/sim/lib/execution/isolated-vm.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -210,10 +210,13 @@ interface PendingExecution {
210210
runInOutboundScope: ReturnType<typeof captureOutboundScope>
211211
fetchPolicy?: IsolatedFetchPolicy
212212
/**
213-
* Fetches whose {@link fetchPolicy} decision is still pending. The result waits for them, so a
214-
* request the code never awaited is decided (and recorded) before the caller reads the run.
213+
* Fetches whose {@link fetchPolicy} decision is still pending. The result waits for them until
214+
* {@link deadline}, so a request the code never awaited is decided (and recorded) before the
215+
* caller reads the run, and a slow decision never holds the code past its time limit.
215216
*/
216217
fetchDecisions: Set<Promise<unknown>>
218+
/** When the pool gives up on the execution (epoch ms): dispatch plus {@link hostTimeoutMs}. */
219+
deadline: number
217220
resolve: (result: IsolatedVMExecutionResult) => void
218221
timeout: ReturnType<typeof setTimeout>
219222
ownerKey: string
@@ -905,6 +908,17 @@ function handleBrokerMessage(
905908
})
906909
}
907910

911+
/** Settles once every promise in `pending` has, or at `deadline` (epoch ms), whichever is first. */
912+
function settleBefore(pending: Iterable<Promise<unknown>>, deadline: number): Promise<void> {
913+
return new Promise((resolve) => {
914+
const timer = setTimeout(resolve, Math.max(0, deadline - Date.now()))
915+
void Promise.allSettled(pending).then(() => {
916+
clearTimeout(timer)
917+
resolve()
918+
})
919+
})
920+
}
921+
908922
function handleWorkerMessage(workerId: number, message: unknown) {
909923
if (typeof message !== 'object' || message === null) return
910924
const msg = message as Record<string, unknown>
@@ -942,7 +956,10 @@ function handleWorkerMessage(workerId: number, message: unknown) {
942956
const result = msg.result as IsolatedVMExecutionResult
943957
if (!pending.abort.signal.aborted) {
944958
if (pending.fetchDecisions.size === 0) pending.resolve(result)
945-
else void Promise.allSettled(pending.fetchDecisions).then(() => pending.resolve(result))
959+
else
960+
void settleBefore(pending.fetchDecisions, pending.deadline).then(() =>
961+
pending.resolve(result)
962+
)
946963
}
947964
// The isolate's own timeout gives up on the execution just as the pool's does.
948965
if (result.termination === 'timeout') pending.abort.abort()
@@ -1450,6 +1467,7 @@ function dispatchToWorker(
14501467
runInOutboundScope: state.runInOutboundScope,
14511468
fetchPolicy: state.fetchPolicy,
14521469
fetchDecisions: new Set(),
1470+
deadline: Date.now() + hostTimeoutMs,
14531471
resolve,
14541472
timeout,
14551473
ownerKey: ownerState.ownerKey,

0 commit comments

Comments
 (0)