D3D12-LUA-BUDGET-COUNTS-INSTRUCTIONS: a loop of library calls runs out of time too #3125

Open
uwuusowarm wants to merge 3 commits from upstream-pr/3125 into main
uwuusowarm commented 2026-12-02 12:43:56 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by uwuusowarm on 2026-12-02T12:43:56Z.


Claimed in the coordination issue as: D3D12-LUA-BUDGET-COUNTS-INSTRUCTIONS (claim, finding)

What and why

A mod's call budget (200 ms, the load 2 s) was only looked at every 4,000 VM instructions. A library function such as string.rep runs none, so a loop of them could run many times its budget: the finding measured 4.34 s against 200 ms.

  • sandbox.rs: the budget hook also runs before every function call (HookTriggers::on_calls), native ones included, so a loop of library calls stops at the first call past the deadline.
  • Guard::start(limit) becomes Guard::run(limit, || call), and the deadline is None between calls. With the hook on calls, the old lifecycle broke: run_script sets a mod up (sandbox::mod_env runs a small chunk) before its load budget starts, so after an earlier mod used up its budget the stale deadline failed the next mod's setup at its first call. a_loop_that_never_ends_runs_out_of_time_even_inside_pcall goes red with the hook change alone (e_ok: "cannot set the mod up: ... time budget"); with the deadline scoped to the call it is green again. The deadline comes back through a drop guard, so a call that unwinds leaves none behind either.
  • docs/lua-modding.md: the limits paragraph says when the time is looked at, and that what runs in between ends first: one library call, or up to 4,000 instructions without a call, which can take long on long strings.

What it costs, release build, best of 5, 5 million calls (Ryzen 7 9800X3D, Windows 11):

Loop Before After
Lua function calls 114 ms 310 ms (x2.7)
Library calls (math.abs) 88 ms 264 ms (x3.0)
Method calls (('x'):upper(), 2 million) 95 ms 174 ms (x1.8)
No calls 93 ms 93 ms

About 18 ns a call is mlua's hook dispatch and about 22 ns the clock read, so roughly 40 ns a call; a handler making 1,000 calls pays about 0.04 ms. Reading the clock only at every 16th call measured about x2 instead of x2.7-3, but lets a loop run up to 15 more library calls past the deadline (about 160 ms in the finding's loop), so this keeps the exact check. Happy to switch if the cost matters more than the overshoot.

Not covered here (both also on main):

  • One long library call still runs to its end; the hook can only stop between calls.
  • Lua 5.4 turns hooks off while a __gc finalizer runs (lgc.c, L->allowhook = 0), so a finalizer is not stopped by the budget at all: a __gc that busy-waits 1.5 s ran its whole 1.5 s against a 50 ms budget, and while true do end in one would stop the Lua thread for good. Its own finding and pull request (D3D12-LUA-GC-FINALIZER-ESCAPES-BUDGET).
  • An xpcall message handler that answers the budget's error runs with hooks off too: the error is raised from inside the hook. Its own finding and pull request (D3D12-LUA-HOOK-ERROR-LEAVES-HOOKS-OFF).

Tested

main (one Lua state per mod, #3179) is merged in at 65f7d5e7b; the review's points are 89bf1d328. Run on 89bf1d328 with the dangling-link test's .unwrap() on the now infallible Runtime::new fixed locally; main has that fix since #3244, so the merge with current main builds as it is:

  • cargo test -p leonida-lua --locked: 48 passed.
  • Red by reverting only the fix, green with it: a_loop_of_native_calls_runs_out_of_time_too (a plain loop, one inside pcall and one inside a coroutine; 200 x string.rep('x', 4 << 20) against a 20 ms budget, about 1,200 instructions, so the count hook never fires for them and on main the mods stay running) fails without .on_calls(); a_call_that_panics_leaves_no_deadline_behind fails with the deadline set back after the call in place of the drop guard. Before the merge, python -I scripts/red_green.py gave red then green for the first, the other 40 passing on both.
  • cargo clippy -p leonida-lua --all-targets --locked -- -D warnings: clean. cargo build --workspace --all-targets --locked: builds.
  • python -m unittest discover -s tests -p "test_docs_*.py": OK (59).
  • python -I scripts/check_no_game_data.py on the changed files: clean.

GPUs tested: n/a (CPU-only crate tests; Windows 11 Home 26300, AMD Ryzen 7 9800X3D)

AI-assisted: yes. Written with Claude Code (Claude Opus 5.5); reviewed by a separate read-only reviewer agent, OpenAI Codex (GPT-6.1 Sol). Its points and what came of them: the __gc escape (confirmed, pre-existing, separate finding), the pcall/coroutine cases (added to the test), the docs (updated), a post-call budget check (not taken: the budget stops code rather than accounting for it afterwards) and a panic guard for Guard::run (taken once the review here asked for it too: a drop guard, with its test). A second Codex review after the merge found no blockers; its points, a native-call test that a fast machine cannot finish inside the budget and the docs wording, are in 89bf1d328.

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a: no translator change)

🤖 Generated with Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5606634756 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3125). Originally posted by [uwuusowarm](https://github.com/uwuusowarm) on 2026-12-02T12:43:56Z. --- Claimed in the coordination issue as: D3D12-LUA-BUDGET-COUNTS-INSTRUCTIONS ([claim](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7345382997), [finding](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7335555984)) ### What and why A mod's call budget (200 ms, the load 2 s) was only looked at every 4,000 VM instructions. A library function such as `string.rep` runs none, so a loop of them could run many times its budget: the finding measured 4.34 s against 200 ms. - `sandbox.rs`: the budget hook also runs before every function call (`HookTriggers::on_calls`), native ones included, so a loop of library calls stops at the first call past the deadline. - `Guard::start(limit)` becomes `Guard::run(limit, || call)`, and the deadline is `None` between calls. With the hook on calls, the old lifecycle broke: `run_script` sets a mod up (`sandbox::mod_env` runs a small chunk) before its load budget starts, so after an earlier mod used up its budget the stale deadline failed the next mod's setup at its first call. `a_loop_that_never_ends_runs_out_of_time_even_inside_pcall` goes red with the hook change alone (`e_ok`: "cannot set the mod up: ... time budget"); with the deadline scoped to the call it is green again. The deadline comes back through a drop guard, so a call that unwinds leaves none behind either. - `docs/lua-modding.md`: the limits paragraph says when the time is looked at, and that what runs in between ends first: one library call, or up to 4,000 instructions without a call, which can take long on long strings. What it costs, release build, best of 5, 5 million calls (Ryzen 7 9800X3D, Windows 11): | Loop | Before | After | |---|---|---| | Lua function calls | 114 ms | 310 ms (x2.7) | | Library calls (`math.abs`) | 88 ms | 264 ms (x3.0) | | Method calls (`('x'):upper()`, 2 million) | 95 ms | 174 ms (x1.8) | | No calls | 93 ms | 93 ms | About 18 ns a call is mlua's hook dispatch and about 22 ns the clock read, so roughly 40 ns a call; a handler making 1,000 calls pays about 0.04 ms. Reading the clock only at every 16th call measured about x2 instead of x2.7-3, but lets a loop run up to 15 more library calls past the deadline (about 160 ms in the finding's loop), so this keeps the exact check. Happy to switch if the cost matters more than the overshoot. Not covered here (both also on `main`): - One long library call still runs to its end; the hook can only stop between calls. - Lua 5.4 turns hooks off while a `__gc` finalizer runs (`lgc.c`, `L->allowhook = 0`), so a finalizer is not stopped by the budget at all: a `__gc` that busy-waits 1.5 s ran its whole 1.5 s against a 50 ms budget, and `while true do end` in one would stop the Lua thread for good. Its own finding and pull request (D3D12-LUA-GC-FINALIZER-ESCAPES-BUDGET). - An `xpcall` message handler that answers the budget's error runs with hooks off too: the error is raised from inside the hook. Its own finding and pull request (D3D12-LUA-HOOK-ERROR-LEAVES-HOOKS-OFF). ### Tested `main` (one Lua state per mod, #3179) is merged in at `65f7d5e7b`; the review's points are `89bf1d328`. Run on `89bf1d328` with the dangling-link test's `.unwrap()` on the now infallible `Runtime::new` fixed locally; `main` has that fix since #3244, so the merge with current `main` builds as it is: - `cargo test -p leonida-lua --locked`: 48 passed. - Red by reverting only the fix, green with it: `a_loop_of_native_calls_runs_out_of_time_too` (a plain loop, one inside `pcall` and one inside a coroutine; 200 x `string.rep('x', 4 << 20)` against a 20 ms budget, about 1,200 instructions, so the count hook never fires for them and on `main` the mods stay running) fails without `.on_calls()`; `a_call_that_panics_leaves_no_deadline_behind` fails with the deadline set back after the call in place of the drop guard. Before the merge, `python -I scripts/red_green.py` gave red then green for the first, the other 40 passing on both. - `cargo clippy -p leonida-lua --all-targets --locked -- -D warnings`: clean. `cargo build --workspace --all-targets --locked`: builds. - `python -m unittest discover -s tests -p "test_docs_*.py"`: OK (59). - `python -I scripts/check_no_game_data.py` on the changed files: clean. GPUs tested: n/a (CPU-only crate tests; Windows 11 Home 26300, AMD Ryzen 7 9800X3D) AI-assisted: yes. Written with Claude Code (Claude Opus 5.5); reviewed by a separate read-only reviewer agent, OpenAI Codex (GPT-6.1 Sol). Its points and what came of them: the `__gc` escape (confirmed, pre-existing, separate finding), the `pcall`/coroutine cases (added to the test), the docs (updated), a post-call budget check (not taken: the budget stops code rather than accounting for it afterwards) and a panic guard for `Guard::run` (taken once the review here asked for it too: a drop guard, with its test). A second Codex review after the merge found no blockers; its points, a native-call test that a fast machine cannot finish inside the budget and the docs wording, are in `89bf1d328`. ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. (n/a: no translator change) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Kal0s-design commented 2026-12-02 14:13:27 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Kal0s-design on 2026-12-02T14:13:27Z.


Ran natively on Windows 11, head 7610d9fe8 merged into current main (128648cfe, clean merge, main has not touched leonida-lua since the base), Rust 1.98.1 from rust-toolchain.toml, --locked.

The pull request's own checks

Check main merge
a_loop_of_native_calls_runs_out_of_time_too FAILED (panics at tests.rs:508) ok
cargo test -p leonida-lua n/a 41 passed, 0 failed
cargo clippy -p leonida-lua --all-targets -- -D warnings n/a clean

Escape probes (throwaway test, not committed)

Release build, one mod per fresh runtime, call budget 50 ms, handler on frame, wall time of the frame pass. "Stopped" means the mod ended Failed with the budget message and never reached the log line after the code under test.

Handler body main merge
100 × string.rep('x', 4 << 20) 2,353 ms, ran to the end 53 ms, stopped
table.sort of 300k numbers with a Lua comparator 50 ms, stopped 50 ms, stopped
s:gsub('x', function(c) return c end) on 4 Mi chars 50 ms, stopped 50 ms, stopped
10M × string.format('%d %s', ...) 50 ms, stopped 50 ms, stopped
1M reads through an __index function that calls string.rep 1,618 ms, stopped 50 ms, stopped
string.rep loop 100 pcalls deep 2,064 ms, stopped 50 ms, stopped
string.rep loop in a coroutine inside a coroutine 2,616 ms, stopped 50 ms, stopped
Load budget 200 ms, top-level 1000 × string.rep('x', 4 << 20) 6,544 ms, stopped 223 ms, stopped
table.sort of 2M numbers, no comparator (one native call) 1,494 ms, ran to the end 1,091 ms, then stopped at the next call
S:gsub('a', 'c') on 16 MiB (one native call) 308 ms, ran to the end 292 ms, then stopped
string.find(('a'):rep(200), '.-.-.-b') (one native call, backtracking) 671 ms, ran to the end 535 ms, then stopped
500 × local t = S .. S .. S .. S, S 4 MiB (no calls at all) 1,949 ms, ran to the end 1,520 ms, then stopped
xpcall(function() error('x') end, h), where h runs 20,000 × string.rep('x', 1 << 20) 68,448 ms, h ran to the end 72,457 ms, h ran to the end
xpcall(function() while true do end end, h), same h 64,616 ms, h ran to the end 79,535 ms, h ran to the end
The same 20,000-call loop as h, not in a handler 2,259 ms, stopped 52 ms, stopped

Where the pull request says it helps, it does: every loop of calls, through pcall, coroutines, comparators, gsub callbacks and __index, now stops within a few ms of the deadline, and so does the load budget. The single long native calls are the overshoot the body already lists. On the merge the mod is at least switched off afterwards, where on main it carried on.

Two things it does not cover:

  1. A loop with no calls in it can still overshoot by about 30×. Each .. above copies 16 MiB in one instruction, and the whole loop is under 4,000 instructions, so the count hook barely fires and the call hook never does. It is the same class as "one long library call", but it is plain operators, so the new docs sentence ("the time is looked at before every function call and every 4,000 instructions") is accurate while the escape is easy to miss.
  2. An xpcall message handler is not bounded at all, on main or here. The handler loop ran for 64–80 s against a 50 ms budget and finished, while the same loop outside a handler stops at 52 ms. That holds whether the error came from error() or from the budget itself. My reading (not verified by a probe): Lua runs the handler for an error raised inside a hook while hooks are still switched off (luaD_hook sets allowhook = 0), so the handler that answers the budget error runs unhooked. Either way, the updated docs/lua-modding.md line says a loop that does not end stops "also inside pcall, xpcall and coroutine.resume", and for an xpcall handler that is not true. A while true do end handler would presumably hang the Lua thread, the same outcome as the __gc finding in the body. I did not run that, to keep the probe bounded. This is probably a separate finding rather than a blocker for this pull request.

Budget is per call, legit code near the limit

Handler main merge
os.clock busy-wait of 30 ms, 5 frames 29–30 ms each, stays running 29–30 ms each, stays running
400,000 × math.abs(i), 3 frames 14–17 ms, running 28–43 ms, running
800,000 × math.abs(i), 3 frames 26–30 ms, running 50 ms on frame 1, switched off

The deadline is reset for every call: 30 ms a frame for 5 frames never adds up against the 50 ms budget. The cost the body measures (×2.7–3 per call) has a concrete edge, though. A call-heavy handler that used about 55–60 % of its budget on main is now switched off. With the real 200 ms budget that means a handler doing a few million library calls a frame, so probably no real mod, but it may be worth a line in the docs or the changelog.

The budget message is the expected "the mod used up its time budget (a loop that does not end?)" in every stopped case. One cosmetic difference: on main the pcall/resume/xpcall cases carry a traceback through sandbox:N: in global 'pcall', while on the merge the status is the bare message. That is likely because the call hook now fires on the call to check before check can rethrow.

Not checked: __gc finalizers (already a separate finding in the body), the cost on a real mod set, and anything in-game.

GPUs tested: n/a (CPU-only tests).
AI-assisted: yes (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7348189900 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3125#issuecomment-7348189900). Originally posted by [Kal0s-design](https://github.com/Kal0s-design) on 2026-12-02T14:13:27Z. --- Ran natively on Windows 11, head `7610d9fe8` merged into current `main` (`128648cfe`, clean merge, `main` has not touched `leonida-lua` since the base), Rust 1.98.1 from `rust-toolchain.toml`, `--locked`. **The pull request's own checks** | Check | `main` | merge | |---|---|---| | `a_loop_of_native_calls_runs_out_of_time_too` | FAILED (panics at `tests.rs:508`) | ok | | `cargo test -p leonida-lua` | n/a | 41 passed, 0 failed | | `cargo clippy -p leonida-lua --all-targets -- -D warnings` | n/a | clean | **Escape probes (throwaway test, not committed)** Release build, one mod per fresh runtime, call budget 50 ms, handler on `frame`, wall time of the frame pass. "Stopped" means the mod ended `Failed` with the budget message and never reached the log line after the code under test. | Handler body | `main` | merge | |---|---|---| | 100 × `string.rep('x', 4 << 20)` | 2,353 ms, ran to the end | **53 ms, stopped** | | `table.sort` of 300k numbers with a Lua comparator | 50 ms, stopped | 50 ms, stopped | | `s:gsub('x', function(c) return c end)` on 4 Mi chars | 50 ms, stopped | 50 ms, stopped | | 10M × `string.format('%d %s', ...)` | 50 ms, stopped | 50 ms, stopped | | 1M reads through an `__index` function that calls `string.rep` | 1,618 ms, stopped | **50 ms, stopped** | | `string.rep` loop 100 `pcall`s deep | 2,064 ms, stopped | **50 ms, stopped** | | `string.rep` loop in a coroutine inside a coroutine | 2,616 ms, stopped | **50 ms, stopped** | | Load budget 200 ms, top-level 1000 × `string.rep('x', 4 << 20)` | 6,544 ms, stopped | **223 ms, stopped** | | `table.sort` of 2M numbers, no comparator (one native call) | 1,494 ms, ran to the end | 1,091 ms, then stopped at the next call | | `S:gsub('a', 'c')` on 16 MiB (one native call) | 308 ms, ran to the end | 292 ms, then stopped | | `string.find(('a'):rep(200), '.-.-.-b')` (one native call, backtracking) | 671 ms, ran to the end | 535 ms, then stopped | | 500 × `local t = S .. S .. S .. S`, `S` 4 MiB (no calls at all) | 1,949 ms, ran to the end | **1,520 ms, then stopped** | | `xpcall(function() error('x') end, h)`, where `h` runs 20,000 × `string.rep('x', 1 << 20)` | 68,448 ms, `h` ran to the end | **72,457 ms, `h` ran to the end** | | `xpcall(function() while true do end end, h)`, same `h` | 64,616 ms, `h` ran to the end | **79,535 ms, `h` ran to the end** | | The same 20,000-call loop as `h`, not in a handler | 2,259 ms, stopped | 52 ms, stopped | Where the pull request says it helps, it does: every loop of calls, through `pcall`, coroutines, comparators, `gsub` callbacks and `__index`, now stops within a few ms of the deadline, and so does the load budget. The single long native calls are the overshoot the body already lists. On the merge the mod is at least switched off afterwards, where on `main` it carried on. Two things it does not cover: 1. **A loop with no calls in it can still overshoot by about 30×.** Each `..` above copies 16 MiB in one instruction, and the whole loop is under 4,000 instructions, so the count hook barely fires and the call hook never does. It is the same class as "one long library call", but it is plain operators, so the new docs sentence ("the time is looked at before every function call and every 4,000 instructions") is accurate while the escape is easy to miss. 2. **An `xpcall` message handler is not bounded at all, on `main` or here.** The handler loop ran for 64–80 s against a 50 ms budget and finished, while the same loop outside a handler stops at 52 ms. That holds whether the error came from `error()` or from the budget itself. My reading (not verified by a probe): Lua runs the handler for an error raised inside a hook while hooks are still switched off (`luaD_hook` sets `allowhook = 0`), so the handler that answers the budget error runs unhooked. Either way, the updated `docs/lua-modding.md` line says a loop that does not end stops "also inside `pcall`, `xpcall` and `coroutine.resume`", and for an `xpcall` handler that is not true. A `while true do end` handler would presumably hang the Lua thread, the same outcome as the `__gc` finding in the body. I did not run that, to keep the probe bounded. This is probably a separate finding rather than a blocker for this pull request. **Budget is per call, legit code near the limit** | Handler | `main` | merge | |---|---|---| | `os.clock` busy-wait of 30 ms, 5 frames | 29–30 ms each, stays running | 29–30 ms each, stays running | | 400,000 × `math.abs(i)`, 3 frames | 14–17 ms, running | 28–43 ms, running | | 800,000 × `math.abs(i)`, 3 frames | 26–30 ms, running | **50 ms on frame 1, switched off** | The deadline is reset for every call: 30 ms a frame for 5 frames never adds up against the 50 ms budget. The cost the body measures (×2.7–3 per call) has a concrete edge, though. A call-heavy handler that used about 55–60 % of its budget on `main` is now switched off. With the real 200 ms budget that means a handler doing a few million library calls a frame, so probably no real mod, but it may be worth a line in the docs or the changelog. The budget message is the expected "the mod used up its time budget (a loop that does not end?)" in every stopped case. One cosmetic difference: on `main` the `pcall`/`resume`/`xpcall` cases carry a traceback through `sandbox:N: in global 'pcall'`, while on the merge the status is the bare message. That is likely because the call hook now fires on the call to `check` before `check` can rethrow. Not checked: `__gc` finalizers (already a separate finding in the body), the cost on a real mod set, and anything in-game. GPUs tested: n/a (CPU-only tests). AI-assisted: yes (Claude Code).
MoonEyes commented 2026-12-02 18:02:11 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T18:02:11Z.


Code review only, not built (leonida-lua is part of the Windows workspace). Ready.

  • Head: 7610d9fe8, merge base 23a51c494, 100 behind current main 45dc41f95. A trial merge is clean. main has not touched leonida-lua since the base.
  • CI: the runs on this head are waiting for maintainer approval (action_required).
  • Already verified on Windows on this exact head by Kal0s-design (14:13): a_loop_of_native_calls_runs_out_of_time_too fails on main and passes on the merge, cargo test -p leonida-lua gives 41 passed, and the escape probes went from 2,353 ms to 53 ms for a string.rep loop. No commits since.

Review of d3d12/crates/leonida-lua/src/sandbox.rs and runtime.rs:

  • The root cause is fixed. Native functions run no VM instructions, so a count-only hook could miss a loop of them. HookTriggers::on_calls() checks the deadline at every call.
  • The cost is one Instant::now() per Lua call. Mods are not on a frame-critical path in the same way as draw code, and Kal0s's probes show no visible overhead.
  • Guard::run sets and restores the deadline. deadline: Option<Instant> set to None between calls means host-side setup can no longer trip on a stale deadline from an earlier call, which the old start() allowed. Nested run restores the outer deadline.
  • Minor and non-blocking: Guard::run does not restore outer if call unwinds. mlua normally turns Rust panics into Lua errors, so this is unlikely, but a drop guard would make it hold by construction.

Verdict: ready.

AI-assisted verification: Claude Opus (Claude Code), separate agent per batch.


Generated by Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7353881249 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3125#issuecomment-7353881249). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T18:02:11Z. --- **Code review only, not built (`leonida-lua` is part of the Windows workspace). Ready.** - Head: `7610d9fe8`, merge base `23a51c494`, 100 behind current `main` `45dc41f95`. A trial merge is clean. `main` has not touched `leonida-lua` since the base. - CI: the runs on this head are waiting for maintainer approval (`action_required`). - Already verified on Windows on this exact head by Kal0s-design (14:13): `a_loop_of_native_calls_runs_out_of_time_too` fails on `main` and passes on the merge, `cargo test -p leonida-lua` gives 41 passed, and the escape probes went from 2,353 ms to 53 ms for a `string.rep` loop. No commits since. **Review of `d3d12/crates/leonida-lua/src/sandbox.rs` and `runtime.rs`:** - The root cause is fixed. Native functions run no VM instructions, so a count-only hook could miss a loop of them. `HookTriggers::on_calls()` checks the deadline at every call. - The cost is one `Instant::now()` per Lua call. Mods are not on a frame-critical path in the same way as draw code, and Kal0s's probes show no visible overhead. - `Guard::run` sets and restores the deadline. `deadline: Option<Instant>` set to `None` between calls means host-side setup can no longer trip on a stale deadline from an earlier call, which the old `start()` allowed. Nested `run` restores the outer deadline. - Minor and non-blocking: `Guard::run` does not restore `outer` if `call` unwinds. mlua normally turns Rust panics into Lua errors, so this is unlikely, but a drop guard would make it hold by construction. Verdict: **ready**. AI-assisted verification: Claude Opus (Claude Code), separate agent per batch. --- _Generated by [Claude Code](https://claude.ai/code)_
uwuusowarm commented 2026-12-02 22:45:54 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by uwuusowarm on 2026-12-02T22:45:54Z.


Thank you both for the runs and the review. Pushed two commits on top of 7610d9fe8:

  • 65f7d5e7b merges main (no rebase, so your notes on 7610d9fe8 still point somewhere). Only the conflict resolution for the per-mod states of #3179: the shared Guard derives Default, so nothing is timed before the first call either, and run_script loads under guard.run and then keeps the state as main does.
  • 89bf1d328, the review's points:
    • Guard::run gives the deadline back through a drop guard, so a call that unwinds leaves none behind. New test a_call_that_panics_leaves_no_deadline_behind: red with the deadline set back after the call, green with the drop guard.
    • a_loop_of_native_calls_runs_out_of_time_too now runs 200 calls against a 20 ms budget, about 70 times the budget unchecked in a debug build, so a fast machine cannot finish inside it; still about 6 instructions an iteration.
    • docs/lua-modding.md: what runs between two looks at the clock is one library call or up to 4,000 instructions without a call, which can take long on long strings (the S .. S probe).

Not in this pull request:

  • The xpcall message handler running unhooked is the hook-error case: the budget's error is raised from inside the hook, where Lua has hooks off, and the handler runs right there. It is claimed in #2570 as D3D12-LUA-HOOK-ERROR-LEAVES-HOOKS-OFF and opens as its own pull request after this one, like the __gc finalizer (D3D12-LUA-GC-FINALIZER-ESCAPES-BUDGET).
  • The bare message without the traceback in the pcall cases: the call hook fires at the call to check, before check rethrows. Left as it is.
  • Handlers near the limit: a handler making millions of library calls a frame now uses its budget about three times as fast. The cost is in the description; I left the docs at what the limit is.

Depends on #3237: on current main the leonida-lua tests do not build (the dangling-link test calls .unwrap() on the now infallible Runtime::new), and this pull request leaves that line to #3237. With that one line fixed locally: cargo test -p leonida-lua 48 passed, cargo clippy -p leonida-lua --all-targets -- -D warnings clean, cargo build --workspace --all-targets and the docs tests OK; each of the two tests checked red by reverting only its fix (the call hook, the drop guard).

AI-assisted: Claude Code (Claude Opus 5.5); reviewed again by OpenAI Codex (GPT-6.1 Sol), no blockers.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7361130012 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3125#issuecomment-7361130012). Originally posted by [uwuusowarm](https://github.com/uwuusowarm) on 2026-12-02T22:45:54Z. --- Thank you both for the runs and the review. Pushed two commits on top of `7610d9fe8`: - `65f7d5e7b` merges `main` (no rebase, so your notes on `7610d9fe8` still point somewhere). Only the conflict resolution for the per-mod states of #3179: the shared `Guard` derives `Default`, so nothing is timed before the first call either, and `run_script` loads under `guard.run` and then keeps the state as `main` does. - `89bf1d328`, the review's points: - `Guard::run` gives the deadline back through a drop guard, so a call that unwinds leaves none behind. New test `a_call_that_panics_leaves_no_deadline_behind`: red with the deadline set back after the call, green with the drop guard. - `a_loop_of_native_calls_runs_out_of_time_too` now runs 200 calls against a 20 ms budget, about 70 times the budget unchecked in a debug build, so a fast machine cannot finish inside it; still about 6 instructions an iteration. - `docs/lua-modding.md`: what runs between two looks at the clock is one library call or up to 4,000 instructions without a call, which can take long on long strings (the `S .. S` probe). Not in this pull request: - The `xpcall` message handler running unhooked is the hook-error case: the budget's error is raised from inside the hook, where Lua has hooks off, and the handler runs right there. It is claimed in #2570 as D3D12-LUA-HOOK-ERROR-LEAVES-HOOKS-OFF and opens as its own pull request after this one, like the `__gc` finalizer (D3D12-LUA-GC-FINALIZER-ESCAPES-BUDGET). - The bare message without the traceback in the `pcall` cases: the call hook fires at the call to `check`, before `check` rethrows. Left as it is. - Handlers near the limit: a handler making millions of library calls a frame now uses its budget about three times as fast. The cost is in the description; I left the docs at what the limit is. Depends on #3237: on current `main` the `leonida-lua` tests do not build (the dangling-link test calls `.unwrap()` on the now infallible `Runtime::new`), and this pull request leaves that line to #3237. With that one line fixed locally: `cargo test -p leonida-lua` 48 passed, `cargo clippy -p leonida-lua --all-targets -- -D warnings` clean, `cargo build --workspace --all-targets` and the docs tests OK; each of the two tests checked red by reverting only its fix (the call hook, the drop guard). AI-assisted: Claude Code (Claude Opus 5.5); reviewed again by OpenAI Codex (GPT-6.1 Sol), no blockers.
MoonEyes commented 2026-12-03 00:02:21 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-03T00:02:21Z.


RUN (in game, batch of nine pull requests), each head merged with git merge --no-ff onto main 81efe4566, in one build: #3136 74bd1bcd4, #3156 53c3100ce, #3206 d024194b3, #3248 efd21d867, #3256 e7aad1d4c, #3262 3643c2879, #2851 b83b0b375, #3125 89bf1d328, #2642 164506d01. RTX 4060 8 GB, driver 610.88, Windows 11. Series S, -Resolution 1080, frame generation 2x, -PrecompileUsed, the same walking route as the other runs on this machine, 330 s after reaching the world.

What Result
Device lost / device removed 0
Exceptions, panics, hang watchdog, GPU stall, title suspended 0
Process alive at the end yes, stopped by the time limit
Rendered fps, last 240 s (48 samples) median 15.6, mean 15.6
Rendered fps, last 120 s median 14.3
Time under 5 fps in the world 3 %

For reference, the same machine and route rendered 13.3 to 17.2 fps on other batches in the last day. These fps are a check that nothing fell over, not a measurement of a gain.

Verdict: PASS for the in-game gate (300 s or more in the world, no device loss) for this batch, on the heads listed above. If one of these pull requests changes its head, this run no longer covers it.

Limits: one run; arrival in the world was driven by keys and not checked on pictures; -PrecompileUsed was used, so the default start (every known pipeline precompiled) was not exercised. The precompile before the world took 619 s, against 157 s for the previous batch; the shader-side changes in this batch (#3156, #3262) probably left the pipeline cache cold (not checked). Switches that are off by default (for example #2851's LEONIDA_TITLE_MEMORY_SCALE, #3136's timeline attribution) were not turned on: this run covers their default path only. #2642 targets Wine and was run on Windows only.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7362723758 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3125#issuecomment-7362723758). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-03T00:02:21Z. --- RUN (in game, batch of nine pull requests), each head merged with `git merge --no-ff` onto main `81efe4566`, in one build: #3136 `74bd1bcd4`, #3156 `53c3100ce`, #3206 `d024194b3`, #3248 `efd21d867`, #3256 `e7aad1d4c`, #3262 `3643c2879`, #2851 `b83b0b375`, #3125 `89bf1d328`, #2642 `164506d01`. RTX 4060 8 GB, driver 610.88, Windows 11. Series S, `-Resolution 1080`, frame generation 2x, `-PrecompileUsed`, the same walking route as the other runs on this machine, 330 s after reaching the world. | What | Result | |---|---| | Device lost / device removed | 0 | | Exceptions, panics, hang watchdog, GPU stall, title suspended | 0 | | Process alive at the end | yes, stopped by the time limit | | Rendered fps, last 240 s (48 samples) | median 15.6, mean 15.6 | | Rendered fps, last 120 s | median 14.3 | | Time under 5 fps in the world | 3 % | For reference, the same machine and route rendered 13.3 to 17.2 fps on other batches in the last day. These fps are a check that nothing fell over, not a measurement of a gain. Verdict: PASS for the in-game gate (300 s or more in the world, no device loss) for this batch, on the heads listed above. If one of these pull requests changes its head, this run no longer covers it. Limits: one run; arrival in the world was driven by keys and not checked on pictures; `-PrecompileUsed` was used, so the default start (every known pipeline precompiled) was not exercised. The precompile before the world took 619 s, against 157 s for the previous batch; the shader-side changes in this batch (#3156, #3262) probably left the pipeline cache cold (not checked). Switches that are off by default (for example #2851's `LEONIDA_TITLE_MEMORY_SCALE`, #3136's timeline attribution) were not turned on: this run covers their default path only. #2642 targets Wine and was run on Windows only. AI-assisted (Claude Code).
fiestorra commented 2026-12-03 00:19:57 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T00:19:57Z.


VERIFY-3125 — no se puede verificar todavía: su rama no compila y rebasarla choca en tres ficheros

Own commits 985661b34-era branch — sandbox.rs (+14), tests.rs (+25), docs/lua-modding.md; head 89bf1d328

Ran at the head (now that main compiles again — it did not for a few hours, see #3244):

cargo test -p leonida-lua
error[E0599]: no method named `unwrap` found for struct `Runtime` in the current scope
error: could not compile `leonida-lua` (lib test)

That error is not this pull request's fault: the branch predates Runtime::new becoming infallible, so it still carries Runtime::new(...).unwrap() in its own copy of tests.rs. On the fixed main the file has no unwrap; on this branch it does — so the branch has to be rebased before anything can run.

And rebasing it here produces three conflicts:

CONFLICT (content): d3d12/crates/leonida-lua/src/runtime.rs
CONFLICT (content): d3d12/crates/leonida-lua/src/sandbox.rs
CONFLICT (content): docs/lua-modding.md

Because main moved under it: #3115 (per-mod math.random) rewrote the same sandbox.rs seats, and #3244 changed tests.rs. Those are not cosmetic conflicts — the sandbox override seats are exactly where a native-call budget is charged.

So the honest status is blocked on a rebase, and the author is the one who should do it, because resolving the sandbox seats is a decision about which of two changes wins, not a mechanical merge.

What the change claims, and it is worth the rebase: the instruction budget counts native calls too — a loop of library calls runs out of time like a loop of Lua bytecode does — with tests a_call_that_panics_leaves_no_deadline_behind and a_loop_of_native_calls_runs_out_of_time_too. A budget that only counts bytecode is a budget that a single for i=1,1e9 do math.random() end escapes, which is the cheapest denial of service a mod can write.

What I could not test

  • Anything: no compile without the rebase, and the rebase needs its author.

Written with an AI assistant.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7363067993 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3125#issuecomment-7363067993). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T00:19:57Z. --- ## VERIFY-3125 — **no se puede verificar todavía: su rama no compila y rebasarla choca en tres ficheros** | | | |---|---| | Own commits | `985661b34`-era branch — `sandbox.rs` (+14), `tests.rs` (+25), `docs/lua-modding.md`; head `89bf1d328` | **Ran at the head** (now that `main` compiles again — it did not for a few hours, see #3244): ``` cargo test -p leonida-lua error[E0599]: no method named `unwrap` found for struct `Runtime` in the current scope error: could not compile `leonida-lua` (lib test) ``` **That error is not this pull request's fault**: **the branch predates `Runtime::new` becoming infallible**, **so it still carries `Runtime::new(...).unwrap()` in its own copy of `tests.rs`.** **On the fixed `main` the file has no `unwrap`; on this branch it does** — **so the branch has to be rebased before anything can run.** **And rebasing it here produces three conflicts**: ``` CONFLICT (content): d3d12/crates/leonida-lua/src/runtime.rs CONFLICT (content): d3d12/crates/leonida-lua/src/sandbox.rs CONFLICT (content): docs/lua-modding.md ``` **Because `main` moved under it**: **#3115 (per-mod `math.random`) rewrote the same `sandbox.rs` seats, and #3244 changed `tests.rs`.** **Those are not cosmetic conflicts — the sandbox override seats are exactly where a native-call budget is charged.** **So the honest status is `blocked on a rebase`**, and **the author is the one who should do it**, **because resolving the sandbox seats is a decision about which of two changes wins**, not a mechanical merge. **What the change claims, and it is worth the rebase**: **the instruction budget counts native calls too** — a loop of library calls **runs out of time like a loop of Lua bytecode does** — with tests `a_call_that_panics_leaves_no_deadline_behind` and `a_loop_of_native_calls_runs_out_of_time_too`. **A budget that only counts bytecode is a budget that a single `for i=1,1e9 do math.random() end` escapes**, **which is the cheapest denial of service a mod can write.** ## What I could not test - **Anything**: no compile without the rebase, and the rebase needs its author. Written with an AI assistant.
merzleckeier commented 2026-12-03 00:24:40 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-03T00:24:40Z.

Review: COMMENTED


Current-main build check for 89bf1d32 on d5b30be1. git merge-tree --write-tree merged cleanly. The resulting tree already uses the infallible Runtime::new in the Lua tests. With Rust 1.98.1 on Linux, cargo test -p leonida-lua --locked --offline passed all 49 tests, including the native-call budget and deadline cleanup tests. This addresses the build and conflict report for this exact combination. Synthetic tests only. AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6161509380 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3125#pullrequestreview-6161509380). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-12-03T00:24:40Z. **Review:** COMMENTED --- Current-main build check for `89bf1d32` on `d5b30be1`. `git merge-tree --write-tree` merged cleanly. The resulting tree already uses the infallible `Runtime::new` in the Lua tests. With Rust 1.98.1 on Linux, `cargo test -p leonida-lua --locked --offline` passed all 49 tests, including the native-call budget and deadline cleanup tests. This addresses the build and conflict report for this exact combination. Synthetic tests only. AI-assisted.
uwuusowarm commented 2026-12-03 09:01:09 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by uwuusowarm on 2026-12-03T09:01:09Z.


@fiestorra thanks for the check. Two notes on the build and the conflicts:

  • The .unwrap() on Runtime::new is main's own: it came in with the merge of main at 65f7d5e7b, and main itself carried it until #3244 removed it (the description named #3237 for it, which is now closed). The head alone still has it, but the merge with current main does not.
  • The three conflicts come from rebasing. The branch merges main instead of rebasing onto it, so replaying its first commit onto current main meets the changes that the merge commit 65f7d5e7b already resolves. Merged, it is clean: git merge-tree --write-tree of 89bf1d328 with main d9b618f10 has no conflicts, and merzleckeier's review ran that merge with d5b30be1 on Linux, 49 tests passed.

I'd leave the head at 89bf1d328 for now, so MoonEyes' in-game run still covers it. If a maintainer would rather have main merged in again, I'll do that.

AI-assisted: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7373058635 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3125#issuecomment-7373058635). Originally posted by [uwuusowarm](https://github.com/uwuusowarm) on 2026-12-03T09:01:09Z. --- @fiestorra thanks for the check. Two notes on the build and the conflicts: - The `.unwrap()` on `Runtime::new` is `main`'s own: it came in with the merge of `main` at `65f7d5e7b`, and `main` itself carried it until #3244 removed it (the description named #3237 for it, which is now closed). The head alone still has it, but the merge with current `main` does not. - The three conflicts come from rebasing. The branch merges `main` instead of rebasing onto it, so replaying its first commit onto current `main` meets the changes that the merge commit `65f7d5e7b` already resolves. Merged, it is clean: `git merge-tree --write-tree` of `89bf1d328` with `main` `d9b618f10` has no conflicts, and merzleckeier's review ran that merge with `d5b30be1` on Linux, 49 tests passed. I'd leave the head at `89bf1d328` for now, so MoonEyes' in-game run still covers it. If a maintainer would rather have `main` merged in again, I'll do that. AI-assisted: Claude Code (Claude Opus 5.5).
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3125:upstream-pr/3125'
git switch 'upstream-pr/3125'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3125'
git switch 'upstream-pr/3125'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3125'
git switch 'upstream-pr/3125'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3125'
git switch 'main'
git merge --squash 'upstream-pr/3125'
git switch 'main'
git merge --ff-only 'upstream-pr/3125'
git switch 'main'
git merge 'upstream-pr/3125'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!3125
No description provided.