Skip to content

feat(vm): host-driven suspend/resume for deflua and Elixir callbacks - #434

Open
dompdv wants to merge 10 commits into
deviceio:mainfrom
dompdv:feat/deflua-suspend-resume
Open

dompdv wants to merge 10 commits into
deviceio:mainfrom
dompdv:feat/deflua-suspend-resume

Conversation

@dompdv

@dompdv dompdv commented Oct 23, 2026

Copy link
Copy Markdown

Summary

Host-driven suspension/resumption of a Lua evaluation (plan A51).

A deflua or Elixir callback can return {:suspend, values} (or {:suspend, values, lua} to thread state) to park the running machine. Lua.eval!/2 and Lua.call_function/3 then return {:suspended, values, lua} with a continuation on the %Lua{}; the new Lua.resume/2 / Lua.resume!/2 re-enter the parked machine — the resume values become the suspended call's results inside Lua.

defmodule Scheduler do
  use Lua.API, scope: "scheduler"

  deflua yield(value), state do
    {:suspend, [value], state}
  end
end

lua = Lua.new() |> Lua.load_api(Scheduler)

{:suspended, [42], lua} =
  Lua.eval!(lua, "local x = scheduler.yield(42); return x + 1")

{:ok, [11], _lua} = Lua.resume(lua, [10])   # the suspended call "returns" 10

Design

  • The suspend travels as a Lua.VM.Suspend exception raised by the callback wrappers (execute_function/4, wrap_callback/3); the executor and dispatcher catch it at their native-call and engine-boundary sites and attach resumable machine layers (a stack, innermost first) to the exception, which crosses the tail-recursive BEAM frame to Lua.VM.execute/3 — the same channel VM errors already use to ferry raise-time state out. Zero happy-path cost: layers are built only in rescue blocks.
  • Lua.VM.Continuation.run/3 re-enters the layers innermost-first; the heap flows through the completion states, not the layers. A :max_instructions budget spans the whole suspend/resume cycle.
  • Heap effects made before a suspend are kept, as are effects made before a post-resume error (matching pcall semantics).
  • A suspend that cannot be resumed — across pcall/xpcall, a metamethod, a table.sort comparator, a string.gsub replacement function, a generic-for iterator, a load reader, a required module, or a re-entrant native call — is reported as the catchable Lua error "attempt to suspend across a native call boundary" (the Lua 5.2-style "yield across a C-call boundary" divergence). Full coroutine support remains a separate non-goal (coroutine.lua stays a documented suite skip).

Verification

  • mix test: 2917 passed (baseline 2870 + 44 new tests + 3 new doctests), 0 failures
  • mix test test/lua53_suite_test.exs --only lua53: 20/29 unchanged
  • mix compile --warnings-as-errors and mix format: clean
  • New test file: test/lua/suspend_resume_test.exs (44 tests: result placements, chained suspends, loops, dispatcher path, heap effects, error-after-resume, pcall/xpcall boundary, re-entrant deflua, call_function direct + pending_call, ArgumentError, encoded-value validation, :max_instructions across resume, decode: false, eval-between-suspend-and-resume, chunk clause, metamethod/comparator/gsub/iterator/load boundaries)

Plan: A51

dompdv and others added 8 commits October 23, 2026 13:44
Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
A deflua or Elixir callback can now return {:suspend, values} (or
{:suspend, values, lua} to thread state) to park the running machine.
Lua.eval!/2 and Lua.call_function/3 return {:suspended, values, lua}
with a continuation on the %Lua{}; the new Lua.resume/2 and
Lua.resume!/2 re-enter the parked machine, the resume values becoming
the suspended call's results inside Lua. Heap effects made before a
suspend are kept, and a :max_instructions budget spans the whole
suspend/resume cycle.

The suspend travels as a Lua.VM.Suspend exception raised by the
callback wrappers; the executor and dispatcher catch it at their
native-call and engine-boundary sites and attach resumable machine
layers (a stack, innermost first) to the exception, which crosses the
tail-recursive BEAM frame to Lua.VM.execute/3 — the same channel VM
errors already use to ferry raise-time state out. Continuation.run/3
re-enters the layers innermost-first; the heap flows through the
completion states, not the layers.

A suspend that cannot be resumed — across pcall/xpcall, a metamethod,
a table.sort comparator, a string.gsub replacement function, a
generic-for iterator, a load reader, a required module, or a
re-entrant native call — is reported as the catchable Lua error
"attempt to suspend across a native call boundary".

Plan: A51

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
PR: deviceio#434

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
… call

Executor.call_function/3 is now guarded: a Lua.VM.Suspend escaping it is
turned into "attempt to suspend across a native call boundary". Before,
a suspend inside an operator metamethod (__add, __eq, __lt, __concat,
__len, ...) captured continuation layers in the metamethod's inner
machine, so the outer machine treated it as resumable and the resume
value became the operator's result.

The unguarded variant, call_function_resumable/3, is for the sites that
really capture continuations: the dispatcher bridges, pcall/xpcall, the
compiled generic-for path and Lua.call_function/3. The per-site
Suspend.guard/1 wrappers are now redundant and removed with guard/1.

The boundary tests now assert the raised error directly instead of
reading it back through pcall, and cover every operator metamethod and
callback both in the main chunk and in a nested function.
Lua.resume/3 and resume!/3 take opts and decode their results and any
re-suspend values the way eval!/2 does; `decode: false` keeps the raw
encoded values. resume raises ArgumentError for a continuation with no
machine layers, and its values must be a list.

The docs for resume, Lua.API and the CHANGELOG now list the full set of
suspend boundaries, operator metamethods included, and say that a
continuation is trusted data: it must not come from untrusted input or
be grafted onto another %Lua{}.
…esume

A callback that runs Lua before it suspends returns a state with a
higher instruction tally than the machine had at the call. The
innermost layer parked the lower tally, and resume seeds from it, so
the callback's work was refunded against :max_instructions. Both
engines now park the higher of the two (Suspend.tally/2).

resume/3 reraised a host-facing Lua.RuntimeException or
CompilerException raised after the resume, so a non-bang caller got an
exception instead of {:error, exception, lua} with the continuation
cleared. It now returns them in the error tuple, as call_function/3
does; resume!/3 still raises.
@dompdv

dompdv commented Nov 25, 2026

Copy link
Copy Markdown
Author

@davydog187 sorry i'm really new to the world of contributing to open source / using Github in this context. Is there a way to expose why I did this and ask a few questions?

The continuation now records the control state the evaluation was entered
with (call stack, call depth, open upvalues). A failed Lua.resume/3 restores
it, so the returned %Lua{} no longer carries the frames of the nested
function it was parked in and a later eval cannot hit a false stack
overflow under max_call_depth. Heap effects made before the error are kept.
@davydog187

Copy link
Copy Markdown
Contributor

@davydog187 sorry i'm really new to the world of contributing to open source / using Github in this context. Is there a way to expose why I did this and ask a few questions?

yes absolutely @dompdv, you can just ask away here :)

@dompdv

dompdv commented Nov 27, 2026

Copy link
Copy Markdown
Author

@davydog187
Thanks, so a little note about the context.

Context
I'm building a workflow execution engine that chains execution of small pieces of code, like "lambdas" in the serverless world. and I'm leveraging this Lua VM execution to provide a totally safe sandboxed execution. The lambdas' execution units are put in a Oban queue to provide good guarantees (retries, parallelism, ...). I'm injecting some I/O functions for the Lua code to use. Let's say "http_request" to access to the outside world. But I want those function calls to be executed asynchronously with the same execution guarantees (using Oban also).
With this PR's "suspend" capability, when a Lua code calls a http_request, the Lua code execution is suspended, the VM state is persisted, and the http_request is queued in Oban for execution. When the job is successful, the VM state is restored, and the VM execution resume with the http_request results.
It helps me a lot giving the execution guarantees I'm looking for and a fluid Lua coding experience.

Contribution
I used AI to change what I needed but I've not dived into the resulting code. I don't feel comfortable about this and got a few questions:

  • it seems that this PR has been created a little bit automatically from my fork
  • isn't it a good practice to discuss about the context with you to make sure this is heading the way you want before creating a PR
  • what is the level of diligence that I should do before officially opening a PR and asking for a review ?

Thanks again for this beautiful project

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.

2 participants