Skip to content
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below.
after the call (`pcall`, `xpcall`, or the error path of `Lua.call_function/3`)
keeps the collector's bookkeeping, so a later minor collection does not free
a table or closure cell that is still in use.
- `Lua.set_deadline/2` and `Lua.deadline/1`: `Lua.set_deadline(lua, to_timeout(second: 5))`
gives Lua a time limit in milliseconds from now (`:infinity` removes it), and
`deadline/1` returns the milliseconds left. When the time is up, running Lua raises a
catchable `"deadline exceeded"` error, checked at loop iterations and calls like
`:max_instructions`. A `pcall` that traps it is interrupted again on any further loop or
call. It is a soft limit: Lua callbacks run by the standard library and pattern matching
are not interrupted. Without a deadline the hot path is unchanged.

### Changed
- Writes to an existing table now go through `Lua.VM.State.put_table/3`, which
Expand Down
65 changes: 65 additions & 0 deletions lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1134,6 +1134,71 @@ defmodule Lua do
Lua.API.install(lua, module, scope, opts[:data])
end

@doc """
Gives Lua code running on `lua` a time limit, in milliseconds from now.

`timeout` is a non-negative integer, or `:infinity` to remove the limit (the
default). Any other value raises `ArgumentError`.

iex> lua = Lua.new() |> Lua.set_deadline(to_timeout(minute: 1))
iex> {[45], _lua} = Lua.eval!(lua, "local s = 0 for i = 1, 9 do s = s + i end return s")

When the time is up, running Lua raises a catchable `"deadline exceeded"`
error. A `0` timeout is already up:

iex> lua = Lua.new() |> Lua.set_deadline(0)
iex> {[false, message], _lua} = Lua.eval!(lua, "return pcall(function() while true do end end)")
iex> message =~ "deadline exceeded"
true

The limit is soft. Lua checks the clock at loop iterations and function
calls, a few hundred of them apart, so it can run a little past the time.
Nothing interrupts work between two checks: Elixir functions that Lua calls,
Lua functions run by the standard library (a `string.gsub` replacement or a
`table.sort` comparator), pattern matching and `string.rep`. To stop
untrusted code for certain, run it in a process you can kill.

Once the time is up, it stays up on the state that `eval!/2` returns. Every
later evaluation on that state raises again at its first loop or call, until
you call `set_deadline/2` again. A `pcall` can catch the error, but any
loop or call after it raises again.
"""
@spec set_deadline(t(), timeout()) :: t()
def set_deadline(%__MODULE__{state: state} = lua, :infinity), do: %{lua | state: %{state | deadline: :infinity}}

# A zero timeout is up already, so it takes the same form as a deadline Lua found passed:
# every later loop or call raises, not only one that lands on a clock read.
def set_deadline(%__MODULE__{state: state} = lua, 0), do: %{lua | state: %{state | deadline: :passed}}

def set_deadline(%__MODULE__{state: state} = lua, timeout) when is_integer(timeout) and timeout > 0 do
%{lua | state: %{state | deadline: System.monotonic_time(:millisecond) + timeout}}
end

Comment on lines +1137 to +1176

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the deadline API is a bit confusing as written. I believe its expecting users to add time to System.monotonic_time(:millisecond).

Instead, I would expect that users would just pass a timeout value, and then we internally use monotonic time to set the deadline.

e.g. instead of

Lua.set_deadline(lua, System.monotonic_time(:millisecond) + 30)

Users would do

Lua.set_deadline(lua, to_timeout(minute: 1))`

it always expects values to be >=0, and measured as a millisecond offset .

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In addition, I find the documentation here to be very confusing and hard to read

def set_deadline(%__MODULE__{}, timeout) do
raise ArgumentError,
"expected a non-negative integer number of milliseconds or :infinity, got: #{inspect(timeout)}"
end

@doc """
Returns the milliseconds left before the deadline, or `:infinity` if none is set.

It returns `0` once the time is up and never a negative number.

iex> Lua.new() |> Lua.deadline()
:infinity

iex> Lua.new() |> Lua.set_deadline(60_000) |> Lua.deadline() > 0
true

To give a nested call a shorter limit and then put the old one back, read
the time left first and set it again afterwards. The time the nested call
used is not taken off it, so subtract that yourself if it matters.
"""
@spec deadline(t()) :: non_neg_integer() | :infinity
def deadline(%__MODULE__{state: %{deadline: :infinity}}), do: :infinity
def deadline(%__MODULE__{state: %{deadline: :passed}}), do: 0
def deadline(%__MODULE__{state: %{deadline: at}}), do: max(at - System.monotonic_time(:millisecond), 0)

@doc """
Puts a private value in storage for use in Elixir functions

Expand Down
12 changes: 11 additions & 1 deletion lib/lua/vm/dispatcher.ex
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ defmodule Lua.VM.Dispatcher do
# in range, saving one function call per integer-arithmetic opcode.
@max_int 0x7FFFFFFFFFFFFFFF
@min_int -0x8000000000000000
# Ticks between clock reads while a deadline is set. A literal, not a call to
# `State`, so this module has no compile-time dependency on it; a test pins it
# equal to `State.deadline_stride/0`.
@deadline_stride 256

@op_load_constant 1
@op_load_boolean 2
Expand Down Expand Up @@ -2419,7 +2423,13 @@ defmodule Lua.VM.Dispatcher do
:maps.filter(fn reg, _cell -> reg < threshold end, open_upvalues)
end

defp tick(%{max_instructions: :infinity}, instruction_count, _call_stack, _call_depth), do: instruction_count
defp tick(%{max_instructions: :infinity, deadline: :infinity}, instruction_count, _call_stack, _call_depth),
do: instruction_count

# A deadline with no budget reads the clock only every `@deadline_stride` ticks; the ticks
# between need no struct sync.
defp tick(%{max_instructions: :infinity, deadline: deadline}, instruction_count, _call_stack, _call_depth)
when is_integer(deadline) and rem(instruction_count + 1, @deadline_stride) != 0, do: instruction_count + 1

defp tick(state, instruction_count, call_stack, call_depth) do
State.tick!(sync(state, call_stack, call_depth), instruction_count)
Expand Down
63 changes: 60 additions & 3 deletions lib/lua/vm/state.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ defmodule Lua.VM.State do
alias Lua.VM.RuntimeError
alias Lua.VM.Table

# How many ticks pass between reads of the clock while a deadline is set: a
# tick is a loop iteration or a call, so the clock is read once per stride
# rather than on every one. It counts ticks, not time: work between ticks
# is not bounded.
@deadline_stride 256

@doc false
def deadline_stride, do: @deadline_stride

# `call_stack`, `call_depth` and `open_upvalues` are control state, not
# heap state. The interpreter keeps them here; the dispatcher threads
# them as loop parameters (the same discipline as `instruction_count`
Expand Down Expand Up @@ -40,6 +49,13 @@ defmodule Lua.VM.State do
# `line`-off-State discipline so the default `:infinity` path
# carries no per-instruction struct rebuild. See `tick!/2`.
max_instructions: :infinity,
# `deadline` is a `System.monotonic_time(:millisecond)` instant after
# which execution raises a catchable `"deadline exceeded"` error;
# `:infinity` (the default) means none. Host-set per call with
# `Lua.set_deadline/2`, and checked by `tick!/2` at the same
# boundaries as the instruction budget, sampling the clock every
# `@deadline_stride` ticks. `:passed` once a tick found it passed.
deadline: :infinity,
# `instruction_count` carries the running tally ACROSS engine boundaries
# only. The interpreter and dispatcher each thread their tally as
# a loop parameter; at an `Executor`↔`Dispatcher` hand-off (where
Expand Down Expand Up @@ -81,6 +97,7 @@ defmodule Lua.VM.State do
entry_depth: non_neg_integer(),
max_string_bytes: pos_integer() | :infinity,
max_instructions: pos_integer() | :infinity,
deadline: integer() | :infinity | :passed,
instruction_count: non_neg_integer(),
metatables: map(),
upvalue_cells: map(),
Expand Down Expand Up @@ -156,13 +173,38 @@ defmodule Lua.VM.State do
threaded `instruction_count` is not otherwise in `%State{}`), so `unwind_to/2` can
carry it forward and a caught budget error stays spent — a protected call
cannot refund the work it burned.

With a `deadline` set, the tally also counts when `max_instructions` is
`:infinity`, and every `@deadline_stride` ticks the monotonic clock is read:
once it reaches the deadline, a catchable `"deadline exceeded"` runtime
error is raised the same way, and the state it carries has `deadline:
:passed`. `unwind_to/2` keeps `:passed`, and every later tick raises at
once, so a protected call that traps the error is interrupted again on its
next tick and the error reaches the host's own call — the behaviour of a
`lua_sethook` count hook in reference Lua. The host's next
`Lua.set_deadline/2` replaces it.
"""
@spec tick!(t(), non_neg_integer()) :: non_neg_integer()
def tick!(%__MODULE__{max_instructions: :infinity}, instruction_count), do: instruction_count
def tick!(%__MODULE__{max_instructions: :infinity, deadline: :infinity}, instruction_count), do: instruction_count

def tick!(%__MODULE__{max_instructions: max}, instruction_count) when instruction_count + 1 < max,
def tick!(%__MODULE__{max_instructions: max, deadline: :infinity}, instruction_count) when instruction_count + 1 < max,
do: instruction_count + 1

def tick!(%__MODULE__{deadline: :passed} = state, instruction_count),
do: deadline_exceeded!(state, instruction_count + 1)

# `:infinity` sorts above every integer, so an unbounded budget always passes this guard.
def tick!(%__MODULE__{max_instructions: max, deadline: deadline} = state, instruction_count)
when instruction_count + 1 < max do
instruction_count = instruction_count + 1

if rem(instruction_count, @deadline_stride) == 0 and System.monotonic_time(:millisecond) >= deadline do
deadline_exceeded!(state, instruction_count)
end

instruction_count
end

def tick!(%__MODULE__{call_stack: call_stack} = state, instruction_count) do
instruction_count = instruction_count + 1

Expand All @@ -172,6 +214,13 @@ defmodule Lua.VM.State do
state: %{state | instruction_count: instruction_count}
end

defp deadline_exceeded!(state, instruction_count) do
raise RuntimeError,
value: "deadline exceeded",
call_stack: state.call_stack,
state: %{state | instruction_count: instruction_count, deadline: :passed}
end

@doc """
Recovers the state a protected call should continue with after trapping
an error.
Expand Down Expand Up @@ -202,6 +251,9 @@ defmodule Lua.VM.State do
against the one per-evaluation `:max_instructions` budget, so wrapping heavy work in
`pcall` (or looping over `pcall`) cannot escape the cap.

A deadline the raise found passed (`deadline: :passed`) is kept the same way,
so a trapped `"deadline exceeded"` cannot be escaped either.

Keeping `upvalue_cells` while restoring `open_upvalues` matches reference
upvalue semantics: cells captured before the protected call keep their
mutated values, while cells opened by the unwound frames become
Expand All @@ -226,10 +278,15 @@ defmodule Lua.VM.State do
gc_remembered: raised.gc_remembered,
gc_young_from: raised.gc_young_from,
gc: raised.gc,
instruction_count: max(entry.instruction_count, raised.instruction_count)
instruction_count: max(entry.instruction_count, raised.instruction_count),
deadline: kept_deadline(entry.deadline, raised.deadline)
}
end

# A deadline the raise found passed stays passed: `pcall` cannot trap its way past it.
defp kept_deadline(_entry, :passed), do: :passed
defp kept_deadline(entry, _raised), do: entry

@doc """
Returns the `_G` table reference.
"""
Expand Down
Loading
Loading