Skip to content

fix(actions): run execute_script in a memory-bounded worker process (WI-2360) - #565

Closed
stefan-ernst wants to merge 3 commits into
mainfrom
fix/wi-2360-script-worker-isolation
Closed

stefan-ernst wants to merge 3 commits into
mainfrom
fix/wi-2360-script-worker-isolation

Conversation

@stefan-ernst

Copy link
Copy Markdown
Contributor

Problem

execute_script ran author-supplied JavaScript in Sobek inside the API
process
. CPU was bounded (vm.Interrupt, 30 s cap) and source capped at
10 KB, but nothing bounded allocation. Any holder of action.manage — every
authenticated user in their personal workspace — could save and trigger a
script that allocates without bound and drive the whole instance into the
debug.SetMemoryLimit GC death spiral. Availability impact across tenants.

This implements the item's option 1: move script execution out of the API
process.

Design

execute_script now runs in a dedicated worker process per execution,
selected by WINDSHIFT_SCRIPT_WORKER=1 on the same binary (handled at the top
of main.go). The worker owns a fresh Sobek realm and nothing else.

The parent keeps everything security-relevant, so the REST bridge is
unchanged:

  • credential minting (MintActionScriptCredential), route policy
    (ValidateScriptAPIRequest), the call budget, the write-ahead marker, and
    InProcessV2Dispatcher all stay in the parent;
  • the worker sends api_request / console messages over stdin/stdout and
    blocks for each answer; it never sees a token, the database, or any server
    state.

Budgets:

Budget Where enforced
wall clock (script_timeout_ms, node timeout) in-worker vm.Interrupt watchdog; parent force-kills after a 2 s grace
heap (script_memory_mb, default 128) debug.SetMemoryLimit + in-worker HeapAlloc monitor (interrupt)
RSS backstop (Linux) parent samples /proc/<pid>/statm and kills past baseline + budget
concurrency (concurrent_scripts) parent permit before spawn
API calls / output parent handleAPIRequest / strictScriptOutput in the worker

A killed or over-budget worker fails the node with a bounded, explainable
error (execute_script: script worker memory limit of N MiB exceeded) that the
action execution log records; the API process is unaffected.

Acceptance criteria

  1. Bounded allocation — the worker is a separate process, so the server's
    RSS is untouched; the worker is stopped by its heap monitor and the Linux
    RSS backstop. Tested.
  2. Other tenants unaffected — a runaway script does not block later
    executions in the same process. Tested.
  3. Budgets still apply — timeout, call, output, and concurrency budgets are
    unchanged and still tested.
  4. Denial coverage — this is the item's option-2 mechanism (a dedicated
    trust level). Option 1 makes it unnecessary: action.manage remains the
    authoring gate, and isolation removes the need to restrict authorship. The
    existing action.manage authorization and audit are unchanged.
  5. REST bridge semantics — identity, scopes, redirect/path rejection, and
    credential lifecycle are untouched; the existing bridge tests pass.

Scope note

Condition scripts (script_engine.go) stay in-process. They are admin-gated
(ConditionSetApplicationService.requireAdmin), capped by script_timeout_ms
and the 10 KiB source limit, and have no windshift.api.request bridge. They
can be routed through the same worker in a follow-up; the worker protocol
already separates the bridge from execution. This is called out in the
operator-controls README.

Schema / config

Adds the operator control script_memory_mb (default 128) to
operatorcontrols.Limits, documented in the operator-controls README and
regenerated into api/openapi-v2.json.

Testing

Companion tests: Windshiftapp/core-tests-internal#73.

./overlay.sh ../core-wi-2360 -- -tags=test -count=1 ./internal/services/ ./internal/aitools/ ./internal/restapi/v2/ ./internal/restapi/v1/handlers/ ./internal/operatorcontrols/
./overlay.sh ../core-wi-2360 -- -tags=test -count=1 -run TestExecuteScript ./tests/

All passed (services 172 s). golangci-lint (full repo), make openapi-v2-check, and the pre-commit guards pass.

Performance

One fork/exec of the (already-running) server binary per script node. The
item allows a per-execution worker; a pooled/recycled worker is a drop-in
replacement behind ScriptWorkerLauncher if spawn cost ever matters.

…WI-2360)

Sobek ran action scripts inside the API process with no per-script heap
bound, so any action.manage holder could save a script that allocates without
bound and drive the whole instance into the memory-limit GC death spiral.

Move execute_script into a dedicated worker process per execution, selected by
WINDSHIFT_SCRIPT_WORKER=1 on the same binary. The worker owns a fresh Sobek
realm and nothing else; the parent keeps token minting, route policy, the call
budget, the write-ahead marker, and v2 dispatch, so the REST bridge semantics
are unchanged.

Budgets:
- script_memory_mb (operator control, default 128) is the per-script heap
  budget. The worker sets debug.SetMemoryLimit and an in-worker monitor
  interrupts a runaway allocation; on Linux the parent also kills the worker
  when its resident set passes its baseline plus the budget.
- script_timeout_ms and the node timeout still cap wall clock; the worker
  outlives the run deadline by a short grace so it can report its own failure.
- concurrent_scripts still gates the parent, and the call and output budgets
  are unchanged.

A killed or over-budget worker fails the node with a bounded, explainable
error and leaves the API process unaffected. Condition scripts stay
in-process; they are admin-gated and capped by script_timeout_ms and the 10 KiB
source limit.
The parent RSS backstop now allows the worker's non-heap runtime overhead on
top of the heap budget, so the worker's own heap monitor fires first for a
script that is merely at its budget.
@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Performance review: I’d keep per-run process isolation, but change which executable gets launched. On Linux/arm64, this PR adds about 43 ms per execute_script node even with a warm filesystem cache. Ten sequential short script nodes would add roughly 0.43 s to a workflow.

Executor workload Main p50 PR p50 PR p95
Return one value 0.009 ms 42.7 ms 45.0 ms
One small GET, stubbed handler 0.022 ms 42.7 ms 44.9 ms
Twenty small GETs, stubbed handler 0.073 ms 44.4 ms 46.3 ms
50,000-iteration JS loop 5.3 ms 48.6 ms 51.6 ms

Startup dominates the small requests. A separate Go init trace counted 482 package initializers before the worker ran: go-runewidth took 19 ms and Chroma’s lexers/styles another 7.6 ms in that trace. I’d benchmark a minimal, single-use worker binary before adding a pool: it can retain a fresh process per execution without paying for UI and server initialization.

A trivial node used 53 ms of CPU across parent and child, so 20 nodes/s would consume about one core. With four concurrent callers and a four-CPU quota, the PR sustained 74 trivial nodes/s at 67 ms p95. Four live workers paused at their first GET used 75 MiB of private memory combined, excluding shared executable pages.

Three changes I’d request before merge:

  1. Bound worker frames before decoding in the parent. The parent decoder reads an entire JSON message before validation. The worker caps the request body, but method and path have no corresponding wire limit. The API process can therefore still allocate based on script-controlled input.
  2. Give subprocess workers a finite default concurrency ceiling. The pre-spawn permit is a no-op when the ceiling is zero. The per-worker heap budget doesn’t bound aggregate CPU or memory in the API container.
  3. Use one absolute deadline for JS and REST. The parent starts its timeout before launch, but the worker starts a fresh timeout after initialization and compilation. With a short timeout, the first GET can arrive already expired while a pure-JS result can still be accepted.

Method: 22a3a75d vs. dbe732a7, Go 1.27.4, native Linux/arm64 Docker on Apple M4 Pro, four-CPU quota, 1 GiB container limit. Each table entry is the median of three runs, with eight warm-ups and 240 timed executions per workload per run. Timed Execute with the full server executable and production worker launcher; token storage and REST dispatch were in-memory stubs. These are executor timings, not end-to-end HTTP or workflow latency.

Address the PR review:

- The parent now rejects a worker frame larger than 1 MiB before decoding it,
  so script-controlled method and path input cannot make the API process
  allocate.
- An unset concurrent_scripts limit now resolves to a finite default of 4
  before a worker is spawned, so process count is bounded even without operator
  configuration.
- The timeout is one absolute instant computed before launch and shared with
  the worker, so startup time counts against the budget instead of granting a
  fresh timeout after initialization.
@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Thanks — all three are addressed in 310a8c90 (tests in e4afec8e).

1. Bound worker frames before decoding.
The wire is now newline-delimited frames read through readScriptWorkerFrame, which accumulates into a capped buffer and returns errScriptWorkerFrameTooLarge at 1 MiB before json.Unmarshal runs. Both directions use it. The parent maps it to execute_script: script worker frame exceeds wire budget and kills the worker. The 1 MiB budget is above the 256 KiB body and response caps, so only script-controlled method/path can trip it.
Test: TestExecuteScriptExecutorRejectsOversizedWorkerFrame (2 MiB method, dispatch never happens).

2. Finite default concurrency.
scriptConcurrencyLimit() resolves an unset concurrent_scripts to defaultScriptConcurrency = 4 before the pre-spawn Acquire. The operator ceiling still wins when set.
Tests: TestExecuteScriptExecutorDefaultConcurrencyIsFinite and TestExecuteScriptExecutorDefaultConcurrencyRejectsOverflow (four workers held at the dispatcher, the fifth gets a LimitError before spawning).

3. One absolute deadline.
Execute computes deadline = now + timeout before launch, uses it for runCtx and killCtx (deadline + 2s grace), and sends deadline_unix_nano in the run request. The worker builds context.WithDeadline from that instant and fails immediately if it has already passed, so startup counts against the budget instead of granting a fresh timeout after init/compile.
Test: TestExecuteScriptExecutorEnforcesAbsoluteDeadline — a trivial return 1; under a 1 ms ceiling times out rather than getting a fresh 1 ms window after the ~40 ms spawn.


On the 43 ms/node: I agree the full binary is the wrong host for the worker. The three fixes above don't change spawn cost, so the minimal single-use worker binary is the right follow-up. Concretely: move the worker runtime plus the pure Sobek helpers (strictScriptOutput, runScriptProgram, scriptValueString, …) into a lightweight internal/scriptruntime package that imports only sobek/stdlib, add a tiny cmd main, build it next to the server in the Dockerfile, and have the launcher prefer it (falling back to os.Executable() + the env for single-binary and test runs). That drops the UI/server initializers from the worker's init graph.

I can fold that into this PR or land it separately — tell me which you prefer. The per-run process model and the launcher interface already accommodate it, so it's additive.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Follow-up: retracting the separate minimal worker binary from my previous comment. It would break the single-binary deployment (one artifact, one entrypoint, os.Executable() re-exec), which is a worse cost than the spawn overhead. The worker stays a mode of the server binary.

That leaves the init cost as a real constraint, because a single binary always runs every linked package's init() before main(). So the options are:

  1. Keep per-execution spawn (current): strict per-run process isolation, ~43 ms/node, unchanged by the three fixes above.
  2. Recycled worker pool (single binary, item explicitly allows "pooled, recycled"): spawn a worker once, run scripts in it one at a time, hand it back to the pool. Amortizes init to once per worker instead of once per node. To keep the safety properties, each execution still gets a fresh Sobek realm, and a worker is discarded and replaced on any timeout, memory overrun, policy refusal, or runtime error, after a bounded number of executions, and when its RSS grows past a threshold; idle workers are reaped.

Option 2 is the only way I see to get the throughput back without a second artifact, and the item sanctions it. It is a meaningful change to the launcher (checkout/checkin, health check, recycling), so I'd rather not fold it in silently.

Preference? If you want the pool I'll implement it on top of this PR; otherwise I'll leave the strict per-execution model as-is.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Dropping this PR to keep the current one binary design. This can be picked up again as a micro binary spawn implementation but that would change the deployment surface

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant