Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

perf(engine): run the shared script session in one persistent Deno process (#16208)

Chaker Atallah4d7a96ac11d8
diff --git a/brain/knowledge/decisions/000048-the-shared-script-session-is-one-persistent-deno-process.md b/brain/knowledge/decisions/000048-the-shared-script-session-is-one-persistent-deno-process.md
new file mode 100644
index 00000000000..5b04f6b2c99
--- /dev/null
+++ b/brain/knowledge/decisions/000048-the-shared-script-session-is-one-persistent-deno-process.md
@@ -0,0 +1,37 @@
+---
+status: accepted
+---
+
+# The shared script session is one persistent Deno process
+
+## Decision
+
+A props-resolution session (`deno.createSession` → `denoCodeSandbox.createScriptSession`) is **one long-lived Deno process**, not a spawn per evaluation. Step outputs are pushed into the child's heap once as globals, and each `{{ }}` expression that needs the sandbox is then evaluated in that same process. The engine drives it over the child's stdin/stdout with newline-delimited JSON: `{kind:"set",key,value,id}` installs a global, `{kind:"run",script,id}` evaluates an expression, and the child answers on stdout with a line prefixed by a per-session random marker (`MARKER{"id","success",...}`). Anything unmarked on stdout is the script's own console output.
+
+## Context
+
+Since 0.92, any `{{ }}` token that isn't a plain property path evaluates in Deno. The previous "session" spawned a fresh Deno process on every `run()` and `JSON.stringify`'d the **entire accumulated** script context into it. Because sibling expressions in one step resolve concurrently and the context grows as tokens reference more steps — and inputs resolve twice (resolved + censored) — a step mapping many columns over a large list made dozens of full copies of the data through the engine heap, causing `MEMORY_ISSUE` and OOMKills (Pylon #6216 / SRE-239).
+
+## Why
+
+Serialize each step output across the process boundary **once per session** instead of once per expression. Deno's own machine-mode REPL (`deno repl --json`, the engine behind `@deno/sandbox`) has this exact shape but was unusable: it returns results as display strings (`String(object)`, not values — structured output is the still-open denoland/deno#30470), its transport is a Unix socketpair on fd 3 that Node can't cleanly hand a non-Node child, and it is Unix-only and undocumented. An in-child TCP/socket RPC server was rejected because it would need `--allow-net`/`--allow-read`, breaking the zero-permission posture that keeps user expressions from reaching localhost services — stdin/stdout needs no grant and only the parent holds the pipe ends.
+
+## Consequences
+
+The sandbox interface (`run` / `setGlobal` / `dispose`) is unchanged, so callers are untouched. The process runs with the same empty permission set and 128 MB V8 cap as the old per-run spawns. State now persists within a session: a script that mutates step data, pollutes a built-in, or leaves background work affects later expressions **in the same resolve()** — but only within that one flow's own input resolution, and the default noOp sandbox already shares mutable context the same way (Deno is actually safer: it mutates only its in-child copy, never the engine's live step view). If the child dies mid-session the sandbox respawns and replays the globals before the next run, preserving the old per-spawn isolation across runs.
+
+## Gotchas
+
+(The child program's own mechanics — ESM scope isolation, the bound `console.log` reply channel, the `(0, eval)` paren trick, the hand-rolled line loop — are documented inline on `buildSessionProgram` in `deno.ts`.)
+
+**The session timeout is a no-progress watchdog, not a per-command deadline.** Sibling expressions are sent concurrently (`applyFunctionToValues` uses `Promise.all`) but the child runs them one at a time, so a command can sit queued behind slower ones. A per-command timer counted that queue-wait and could kill a healthy session; instead a single timer fires only when the child produces **no reply at all** for `idleTimeoutMs` (default 30s), reset on every reply. On trip it SIGKILLs the child and the next run respawns — so a wedged event loop or corrupted reply channel can never hold the engine, while a long queue of progressing commands is never killed.
+
+**Globals are sent once under concurrency via an in-flight promise.** `sentGlobals` holds, per key, the value sent **and the promise of that send**, so concurrent `syncGlobals` callers await the one transfer instead of each re-serializing the step output. A new value (different reference) supersedes it with a fresh send; a failed send is dropped so the next run retries rather than treating a never-arrived global as present. Record-after-await alone is wrong — it lets every concurrent caller re-send.
+
+**A long-lived child needs pipe hardening the one-shot path didn't.** `child.stdin` must have its own `'error'` listener: an unhandled `'error'` on the stdin pipe (an EPIPE when the child dies mid-write) is an uncaught exception that crashes the whole engine, not just the run — the `child.on('error')` listener does not catch pipe errors. `stdout`/`stderr` get `setEncoding('utf8')` so a multibyte character split across chunk boundaries is decoded whole instead of becoming `�` in the returned result (the per-chunk `toString()` in the one-shot path has the same latent bug, harmless there because it writes once). And `spawnDeno` removes its temp `DENO_DIR` if writing `main.mjs` fails, since no child was created to trigger the close-time cleanup.
+
+## Key files
+
+- `packages/core/utils/src/lib/deno.ts` — `deno.createSession` (the process + protocol), `buildSessionProgram` (the child program)
+- `packages/server/engine/src/lib/core/code/deno-code-sandbox.ts` — `createScriptSession` (lazy spawn, respawn-on-death, `syncGlobals` send-once)
+- `packages/server/engine/src/lib/variables/props-resolver.ts` — one session per `resolve()`, shared by the resolved + censored passes
diff --git a/packages/core/utils/src/lib/deno.ts b/packages/core/utils/src/lib/deno.ts
index 7306844d11e..7788831efe4 100644
--- a/packages/core/utils/src/lib/deno.ts
+++ b/packages/core/utils/src/lib/deno.ts
@@ -85,6 +85,155 @@ export const deno = {
})
},
+ async createSession({ bootstrapBody, permissions, cwd, memoryLimitMb = DEFAULT_MEMORY_LIMIT_MB, env = {}, idleTimeoutMs = DEFAULT_SESSION_IDLE_TIMEOUT_MS }: DenoSessionParams): Promise<DenoSession> {
+ const marker = newResultMarker()
+ const { child, denoPath, denoDir } = await spawnDeno({
+ entry: { body: buildSessionProgram({ bootstrapBody, marker }) },
+ permissions,
+ cwd,
+ memoryLimitMb,
+ allowReadPaths: [],
+ resolveNodeModules: false,
+ env,
+ })
+
+ const pending = new Map<string, PendingSessionCommand>()
+ let nextCommandId = 0
+ let alive = true
+ let stdoutBuffer = ''
+ let capturedStderr = ''
+ let idleTimer: ReturnType<typeof setTimeout> | null = null
+
+ const refreshWatchdog = (): void => {
+ if (idleTimer !== null) {
+ clearTimeout(idleTimer)
+ idleTimer = null
+ }
+ if (!alive || pending.size === 0) {
+ return
+ }
+ idleTimer = setTimeout(() => {
+ child.kill('SIGKILL')
+ failAllPending(sandboxError.build({ error: `Deno session made no progress for ${idleTimeoutMs}ms`, stdout: '', stderr: capturedStderr }))
+ }, idleTimeoutMs)
+ }
+
+ const settleResponse = (line: string): void => {
+ let message: SessionReply | null = null
+ try {
+ message = JSON.parse(line.slice(marker.length))
+ }
+ catch {
+ return
+ }
+ if (message === null) {
+ return
+ }
+ const command = pending.get(message.id)
+ if (command === undefined) {
+ return
+ }
+ pending.delete(message.id)
+ refreshWatchdog()
+ if (message.success) {
+ command.resolve(message.result)
+ }
+ else {
+ command.reject(sandboxError.build({ error: message.error, stdout: '', stderr: capturedStderr }))
+ }
+ capturedStderr = ''
+ }
+
+ child.stdout.setEncoding('utf8')
+ child.stderr.setEncoding('utf8')
+
+ child.stdout.on('data', (chunk: string) => {
+ stdoutBuffer += chunk
+ let newline = stdoutBuffer.indexOf('\n')
+ while (newline !== -1) {
+ const line = stdoutBuffer.slice(0, newline)
+ stdoutBuffer = stdoutBuffer.slice(newline + 1)
+ if (line.startsWith(marker)) {
+ settleResponse(line)
+ }
+ else if (line.trim()) {
+ console.log(line)
+ }
+ newline = stdoutBuffer.indexOf('\n')
+ }
+ })
+
+ child.stderr.on('data', (chunk: string) => {
+ capturedStderr += chunk
+ console.error(chunk.trimEnd())
+ })
+
+ const failAllPending = (error: Error): void => {
+ alive = false
+ if (idleTimer !== null) {
+ clearTimeout(idleTimer)
+ idleTimer = null
+ }
+ for (const command of pending.values()) {
+ command.reject(error)
+ }
+ pending.clear()
+ }
+
+ child.on('close', (code, signal) => {
+ void removeDenoDir(denoDir)
+ failAllPending(sandboxError.build({ error: `Deno session exited with code ${code} and signal ${signal}`, stdout: '', stderr: capturedStderr }))
+ })
+
+ child.on('error', (error) => {
+ void removeDenoDir(denoDir)
+ failAllPending(sandboxError.build({ error: `Failed to spawn deno (${denoPath}): ${error.message}`, stdout: '', stderr: capturedStderr }))
+ })
+
+ child.stdin.on('error', (error) => {
+ child.kill('SIGKILL')
+ failAllPending(sandboxError.build({ error: `Deno session stdin error: ${error.message}`, stdout: '', stderr: capturedStderr }))
+ })
+
+ const send = (command: SessionCommandBody): Promise<unknown> => {
+ if (!alive) {
+ return Promise.reject(sandboxError.build({ error: 'Deno session is not running', stdout: '', stderr: capturedStderr }))
+ }
+ const id = String(nextCommandId++)
+ let payload: string
+ try {
+ payload = `${JSON.stringify({ ...command, id })}\n`
+ }
+ catch (stringifyError) {
+ return Promise.reject(stringifyError)
+ }
+ return new Promise((resolve, reject) => {
+ pending.set(id, { resolve, reject })
+ refreshWatchdog()
+ child.stdin.write(payload, (writeError) => {
+ if (writeError && pending.delete(id)) {
+ refreshWatchdog()
+ reject(sandboxError.build({ error: `Failed to write to deno session: ${writeError.message}`, stdout: '', stderr: capturedStderr }))
+ }
+ })
+ })
+ }
+
+ return {
+ setGlobal: async ({ key, value }: SessionSetGlobalParams): Promise<void> => {
+ await send({ kind: 'set', key, value })
+ },
+ run: ({ script }: SessionRunParams): Promise<unknown> => {
+ return send({ kind: 'run', script })
+ },
+ isAlive: (): boolean => alive,
+ dispose: (): void => {
+ alive = false
+ child.kill('SIGKILL')
+ },
+ }
+ },
+
}
// Loaded lazily so this module stays importable from browser bundles — the
@@ -116,6 +265,20 @@ async function spawnDeno({ entry, permissions, cwd, memoryLimitMb, allowReadPath
const { childProcess, os, fs } = await getNodeApis()
const denoPath = resolveDenoPath()
const denoDir = await fs.mkdtemp(`${denoDirBase ?? os.tmpdir()}/ap-deno-`)
+ let entryArg: string
+ if (typeof entry === 'string') {
+ entryArg = entry
+ }
+ else {
+ entryArg = `${denoDir}/main.mjs`
+ try {
+ await fs.writeFile(entryArg, entry.body)
+ }
+ catch (error) {
+ await removeDenoDir(denoDir)
+ throw error
+ }
+ }
const child = childProcess.spawn(denoPath, [
'run',
'--quiet',
@@ -127,7 +290,7 @@ async function spawnDeno({ entry, permissions, cwd, memoryLimitMb, allowReadPath
`--v8-flags=--max-old-space-size=${memoryLimitMb}`,
...toPermissionFlags({ permissions, tmpDir: os.tmpdir() }),
...permissions.includes(DenoPermission.ALL) ? [] : allowReadPaths.map((path) => `--allow-read=${path}`),
- entry,
+ entryArg,
], {
cwd,
env: {
@@ -198,6 +361,111 @@ catch (error) {
`
}
+/**
+ * The session child's program (ESM, so its own bindings are hidden from the
+ * scripts it evaluates in global scope).
+ * stdin: {"kind":"run","script":"step_1.a + 1","id":"0"}
+ * stdout: MARKER{"id":"0","success":true,"result":42}
+ */
+function buildSessionProgram({ bootstrapBody, marker }: { bootstrapBody: string, marker: string }): string {
+ return `
+${sandboxError.payloadSource}
+${bootstrapBody}
+${SESSION_REPLY_CHANNEL(marker)}
+${SESSION_REJECTION_TRACKING}
+${SESSION_SCRIPT_RUNNER}
+${SESSION_COMMAND_LOOP}
+`
+}
+
+/**
+ * MARKER{"id":"0","success":true,"result":42} -> protocol reply
+ * hello from a script's console.log -> forwarded as user output
+ * console.log is bound up front so a script overwriting it can't break this.
+ */
+const SESSION_REPLY_CHANNEL = (marker: string): string => `
+const print = console.log.bind(console);
+const reply = (payload) => {
+ print(${JSON.stringify(marker)} + JSON.stringify(payload));
+};`
+
+/**
+ * e.g. `Promise.reject('late')` inside a run fails that run only;
+ * the process stays alive (the one-shot runner exits instead).
+ */
+const SESSION_REJECTION_TRACKING = `
+let failCurrentRun = null;
+globalThis.addEventListener('unhandledrejection', (event) => {
+ event.preventDefault();
+ if (failCurrentRun) {
+ failCurrentRun(event.reason);
+ }
+ else {
+ console.error('Unhandled rejection in deno session:', event.reason);
+ }
+});`
+
+/**
+ * (0, eval)('(' + script + ')'): global scope, and the parens make
+ * {"where": "a"} an object literal, not a block. The setTimeout(0) lets a
+ * promise the script left behind reject before success is reported.
+ */
+const SESSION_SCRIPT_RUNNER = `
+const runScript = (script) => new Promise((resolve, reject) => {
+ failCurrentRun = reject;
+ Promise.resolve()
+ .then(() => (0, eval)('(' + script + ')'))
+ .then(async (value) => {
+ await new Promise((tick) => setTimeout(tick, 0));
+ resolve(value);
+ })
+ .catch(reject);
+});`
+
+/**
+ * {"kind":"set","key":"step_1","value":{...}} -> globalThis.step_1 = {...}
+ * {"kind":"run","script":"step_1.a"} -> reply success/failure
+ * Runs are awaited one at a time, so failCurrentRun is the only run in flight.
+ * Line splitting is hand-rolled: --no-remote rules out std's TextLineStream.
+ */
+const SESSION_COMMAND_LOOP = `
+const decoder = new TextDecoder();
+let buffered = '';
+for await (const chunk of Deno.stdin.readable) {
+ buffered += decoder.decode(chunk, { stream: true });
+ let newline = buffered.indexOf('\\n');
+ while (newline !== -1) {
+ const line = buffered.slice(0, newline);
+ buffered = buffered.slice(newline + 1);
+ newline = buffered.indexOf('\\n');
+ if (line.trim() === '') {
+ continue;
+ }
+ let command;
+ try {
+ command = JSON.parse(line);
+ }
+ catch {
+ continue;
+ }
+ if (command.kind === 'set') {
+ globalThis[command.key] = command.value;
+ reply({ id: command.id, success: true, result: null });
+ continue;
+ }
+ try {
+ const result = await runScript(command.script);
+ reply({ id: command.id, success: true, result: result ?? null });
+ }
+ catch (error) {
+ reply({ id: command.id, success: false, error: toErrorPayload(error) });
+ }
+ finally {
+ failCurrentRun = null;
+ }
+ }
+}`
+
function extractResult(stdout: string, marker: string): { userOutput: string, resultJson: string | null } {
const idx = stdout.lastIndexOf(marker)
if (idx === -1) {
@@ -211,6 +479,7 @@ function extractResult(stdout: string, marker: string): { userOutput: string, re
}
const DEFAULT_MEMORY_LIMIT_MB = 128
+const DEFAULT_SESSION_IDLE_TIMEOUT_MS = 30_000
export enum DenoPermission {
ALL = 'ALL',
@@ -234,8 +503,46 @@ type DenoProgramParams = {
timeoutMs?: number
}
+export type DenoSession = {
+ setGlobal(params: SessionSetGlobalParams): Promise<void>
+ run(params: SessionRunParams): Promise<unknown>
+ isAlive(): boolean
+ dispose(): void
+}
+
+type DenoSessionParams = {
+ bootstrapBody: string
+ permissions: DenoPermission[]
+ cwd?: string
+ memoryLimitMb?: number
+ env?: Record<string, string>
+ idleTimeoutMs?: number
+}
+
+type SessionSetGlobalParams = {
+ key: string
+ value: unknown
+}
+
+type SessionRunParams = {
+ script: string
+}
+
+type SessionCommandBody =
+ | { kind: 'set', key: string, value: unknown }
+ | { kind: 'run', script: string }
+
+type SessionReply =
+ | { id: string, success: true, result: unknown }
+ | { id: string, success: false, error: SandboxErrorPayload }
+
+type PendingSessionCommand = {
+ resolve(value: unknown): void
+ reject(error: Error): void
+}
+
type SpawnDenoParams = {
- entry: string
+ entry: string | { body: string }
permissions: DenoPermission[]
cwd?: string
memoryLimitMb: number
diff --git a/packages/server/engine/src/lib/core/code/deno-code-sandbox.ts b/packages/server/engine/src/lib/core/code/deno-code-sandbox.ts
index fa7736aa917..2a6cf08a142 100644
--- a/packages/server/engine/src/lib/core/code/deno-code-sandbox.ts
+++ b/packages/server/engine/src/lib/core/code/deno-code-sandbox.ts
@@ -3,7 +3,7 @@ import { realpath } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { pathToFileURL } from 'node:url'
-import { deno, DenoPermission } from '@activepieces/core-utils'
+import { deno, DenoPermission, DenoSession } from '@activepieces/core-utils'
import { ExecutionMode } from '@activepieces/shared'
import { CodeSandbox } from './code-sandbox-common'
@@ -83,13 +83,62 @@ export function denoCodeSandbox(permissions: DenoPermission[]): CodeSandbox {
async createScriptSession({ scriptContext, functions }) {
const context: Record<string, unknown> = { ...scriptContext }
+ const bootstrapBody = Object.entries(functions).map(([key, value]) => `globalThis[${JSON.stringify(key)}] = ${value.toString()};`).join('\n')
+ let current: LiveScriptSession | null = null
+ let spawnInFlight: Promise<LiveScriptSession> | null = null
let disposed = false
+
+ // Single-flight respawn: concurrent runs that find the child dead share one new
+ // spawn instead of each starting (and leaking) their own. The liveness check and
+ // the decision to spawn are synchronous, so no caller can clobber another's child.
+ const ensureLive = (): Promise<LiveScriptSession> => {
+ if (current !== null && current.session.isAlive()) {
+ return Promise.resolve(current)
+ }
+ if (spawnInFlight === null) {
+ current = null
+ spawnInFlight = deno.createSession({
+ bootstrapBody,
+ permissions: [],
+ cwd: tmpdir(),
+ }).then((session) => {
+ const live = { session, sentGlobals: new Map<string, SentGlobal>() }
+ current = live
+ spawnInFlight = null
+ return live
+ }).catch((error) => {
+ spawnInFlight = null
+ throw error
+ })
+ }
+ return spawnInFlight
+ }
+
+ const syncGlobals = async ({ session, sentGlobals }: LiveScriptSession): Promise<void> => {
+ await Promise.all(Object.entries(context).map(([key, value]) => {
+ const alreadySent = sentGlobals.get(key)
+ if (alreadySent !== undefined && alreadySent.value === value) {
+ return alreadySent.send
+ }
+ const send = session.setGlobal({ key, value })
+ sentGlobals.set(key, { value, send })
+ send.catch(() => {
+ if (sentGlobals.get(key)?.send === send) {
+ sentGlobals.delete(key)
+ }
+ })
+ return send
+ }))
+ }
+
return {
run: async (script: string) => {
if (disposed) {
throw new Error('Script session has been disposed')
}
- return sandbox.runScript({ script, scriptContext: context, functions })
+ const live = await ensureLive()
+ await syncGlobals(live)
+ return live.session.run({ script })
},
setGlobal: async (key: string, value: unknown, noOverwrite = true) => {
if (noOverwrite && (key in context || key in functions)) {
@@ -99,6 +148,10 @@ export function denoCodeSandbox(permissions: DenoPermission[]): CodeSandbox {
},
dispose: () => {
disposed = true
+ current?.session.dispose()
+ spawnInFlight?.then(({ session }) => session.dispose()).catch(() => undefined)
+ current = null
+ spawnInFlight = null
},
}
},
@@ -125,3 +178,13 @@ function buildPropagatedEnv(permissions: DenoPermission[]): Record<string, strin
}
return env
}
+
+type SentGlobal = {
+ value: unknown
+ send: Promise<void>
+}
+
+type LiveScriptSession = {
+ session: DenoSession
+ sentGlobals: Map<string, SentGlobal>
+}
diff --git a/packages/server/engine/src/lib/core/code/shared-script-session.ts b/packages/server/engine/src/lib/core/code/shared-script-session.ts
index 2d3a499b075..ad92be25df2 100644
--- a/packages/server/engine/src/lib/core/code/shared-script-session.ts
+++ b/packages/server/engine/src/lib/core/code/shared-script-session.ts
@@ -7,7 +7,7 @@ export function createSharedScriptSession(buildParams: () => Promise<CreateScrip
return {
get: () => {
if (isNil(sessionPromise)) {
- sessionPromise = initCodeSandbox({ useDeno: false }).then(async (codeSandbox) => codeSandbox.createScriptSession(await buildParams()))
+ sessionPromise = initCodeSandbox({ useDeno: true }).then(async (codeSandbox) => codeSandbox.createScriptSession(await buildParams()))
}
return sessionPromise
},
diff --git a/packages/server/engine/src/lib/variables/script-evaluator.ts b/packages/server/engine/src/lib/variables/script-evaluator.ts
index 4b705f92b99..2e465bf2048 100644
--- a/packages/server/engine/src/lib/variables/script-evaluator.ts
+++ b/packages/server/engine/src/lib/variables/script-evaluator.ts
@@ -17,7 +17,7 @@ export const scriptEvaluator = {
const session = await scriptSession.get()
return await session.run(script) ?? ''
}
- const codeSandbox = await initCodeSandbox({ useDeno: false })
+ const codeSandbox = await initCodeSandbox({ useDeno: true })
const scriptResult = await codeSandbox.runScript({
script,
scriptContext: scriptContext ?? {},
diff --git a/packages/server/engine/test/core/code/deno-code-sandbox.test.ts b/packages/server/engine/test/core/code/deno-code-sandbox.test.ts
index 593283869c9..0db6ee24e53 100644
--- a/packages/server/engine/test/core/code/deno-code-sandbox.test.ts
+++ b/packages/server/engine/test/core/code/deno-code-sandbox.test.ts
@@ -2,7 +2,7 @@ import { existsSync } from 'node:fs'
import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
// Resolve the deno binary shipped by the `deno` npm devDependency so the test
// does not depend on a system-wide install / PATH.
@@ -330,6 +330,117 @@ describe('denoCodeSandbox permission boundary', () => {
session.dispose()
}
})
+
+ it('runs every script of a session in one Deno process', async () => {
+ const session = await denoCodeSandbox.createScriptSession({
+ scriptContext: {},
+ functions: {},
+ })
+ try {
+ expect(await session.run('globalThis.__runs = (globalThis.__runs ?? 0) + 1')).toBe(1)
+ expect(await session.run('globalThis.__runs = (globalThis.__runs ?? 0) + 1')).toBe(2)
+ expect(await session.run('__runs')).toBe(2)
+ }
+ finally {
+ session.dispose()
+ }
+ })
+
+ it('respawns after the process dies and replays the globals', async () => {
+ const session = await denoCodeSandbox.createScriptSession({
+ scriptContext: { base: 40 },
+ functions: { double: (n: number) => n * 2 },
+ })
+ try {
+ await session.setGlobal('step_1', { out: 5 })
+ expect(await session.run('step_1.out + base')).toBe(45)
+
+ await expectRejection(session.run('Deno.exit(1)'), /exited|not running/)
+
+ expect(await session.run('double(step_1.out + base)')).toBe(90)
+ }
+ finally {
+ session.dispose()
+ }
+ })
+
+ it('respawns exactly one child when concurrent runs hit a dead session', async () => {
+ const { deno } = await import('@activepieces/core-utils')
+ const session = await denoCodeSandbox.createScriptSession({
+ scriptContext: { base: 1 },
+ functions: {},
+ })
+ try {
+ await expectRejection(session.run('Deno.exit(1)'), /exited|not running|no progress/)
+ const spawnSpy = vi.spyOn(deno, 'createSession')
+ try {
+ const results = await Promise.all([
+ session.run('base + 1'),
+ session.run('base + 2'),
+ session.run('base + 3'),
+ session.run('base + 4'),
+ ])
+ expect(results).toEqual([2, 3, 4, 5])
+ expect(spawnSpy).toHaveBeenCalledTimes(1)
+ }
+ finally {
+ spawnSpy.mockRestore()
+ }
+ }
+ finally {
+ session.dispose()
+ }
+ })
+
+ it('rejects runs after dispose', async () => {
+ const session = await denoCodeSandbox.createScriptSession({
+ scriptContext: {},
+ functions: {},
+ })
+ session.dispose()
+ await expect(session.run('1 + 1')).rejects.toThrow()
+ })
+ })
+
+ describe('deno.createSession idle watchdog', () => {
+ it('kills the child when a script wedges the event loop with no reply', async () => {
+ const { deno } = await import('@activepieces/core-utils')
+ const session = await deno.createSession({ bootstrapBody: '', permissions: [], idleTimeoutMs: 500 })
+ try {
+ await expectRejection(session.run({ script: '(() => { while (true) {} })()' }), /no progress/)
+ expect(session.isAlive()).toBe(false)
+ }
+ finally {
+ session.dispose()
+ }
+ })
+
+ it('does not trip when queued commands each make progress, even past the idle timeout total', async () => {
+ const { deno } = await import('@activepieces/core-utils')
+ // Four 300ms runs fired concurrently are serialized by the child (~1.2s total),
+ // but each reply resets the 700ms idle timer, so none of them is killed.
+ const session = await deno.createSession({ bootstrapBody: '', permissions: [], idleTimeoutMs: 700 })
+ try {
+ const runs = Array.from({ length: 4 }, (_, i) =>
+ session.run({ script: `new Promise((r) => setTimeout(() => r(${i}), 300))` }))
+ expect(await Promise.all(runs)).toEqual([0, 1, 2, 3])
+ expect(session.isAlive()).toBe(true)
+ }
+ finally {
+ session.dispose()
+ }
+ })
+
+ it('returns a large multibyte result intact across stdout chunk boundaries', async () => {
+ const session = await denoCodeSandbox.createScriptSession({ scriptContext: {}, functions: {} })
+ try {
+ const expected = '😀🌍'.repeat(50_000)
+ expect(await session.run(`'😀🌍'.repeat(50000)`)).toBe(expected)
+ }
+ finally {
+ session.dispose()
+ }
+ })
})
})