Skip to content

feat(vm): interrupt running Lua at a host-set deadline with Lua.set_deadline/2 - #435

Open
dbernheisel wants to merge 1 commit into
tv-labs:feat/vm-gcfrom
dbernheisel:feat/vm-deadline
Open

dbernheisel wants to merge 1 commit into
tv-labs:feat/vm-gcfrom
dbernheisel:feat/vm-deadline

Conversation

@dbernheisel

@dbernheisel dbernheisel commented Nov 5, 2026 •

Copy link
Copy Markdown

A host that calls back into Lua from an Elixir function can't stop just that callback when it runs long. :max_instructions is per evaluation, and killing the process throws away the whole state. Lua.set_deadline/2 gives running Lua a System.monotonic_time(:millisecond) deadline. Past it, Lua raises a catchable "deadline exceeded" at the next loop back-edge or call, the same places :max_instructions is checked. It's what a lua_sethook count hook gives a host in reference Lua.

  • the clock is read every 256 ticks, and only while a deadline is set
  • a pcall that traps the error is interrupted again on its next tick, so the error reaches the host
  • Lua.deadline/1 returns the current deadline, so a host can give a nested call a shorter one and restore it after
Benchmarks

feat/vm-gc (f5d18a5) vs this branch (105bb9c), lua (chunk) median, quick mode. Base and branch ran interleaved per workload, two rounds averaged (oop five rounds). Apple M4 Max, OTP 29, Elixir 1.20.0. Other work was running on the machine (load 5–11), so a few percent either way is noise.

Workload Base Branch Change
fibonacci 456.3 ms 456.6 ms +0.1%
closures 411.7 μs 411.8 μs +0.0%
oop 114.2 μs 116.5 μs +2.0%
metamethods: self-call method dispatch 511.9 μs 495.4 μs -3.2%
metamethods: 3-level __index chain 208.8 μs 216.3 μs +3.6%
metamethods: arithmetic/relational 2.26 ms 2.15 ms -4.9%
pcall success path 247.6 μs 238.9 μs -3.5%
pcall raise + catch 823.4 μs 802.5 μs -2.5%
varargs + multiple returns 3.58 ms 3.45 ms -3.6%
table.concat 35.9 μs 34.2 μs -4.6%
string.format 85.8 μs 83.4 μs -2.8%
table build 17.8 μs 17.2 μs -3.5%
table sort 23.3 μs 23.1 μs -0.7%
table iterate/sum 24.9 μs 25.2 μs +1.0%
table map + reduce 49.9 μs 50.0 μs +0.3%
table pairs (hash) 85.5 μs 83.6 μs -2.2%

Cost when a deadline is set, on this branch: 4M loop iterations in a compiled function, nine runs each.

Limit Min Median
none 245 ms 251 ms
deadline set, not reached 259 ms 266 ms
max_instructions: 1_000_000_000 338 ms 345 ms

@dbernheisel dbernheisel changed the title feat(vm): interrupt running Lua at a host. Add Lua.set_deadline feat(vm): interrupt running Lua at a host-set deadline with Lua.set_deadline/2 Nov 5, 2026
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