leonida-lua: each mod gets a Lua state of its own, so its memory limit is its own (D3D12-LUA-MEMORY-LIMIT-IS-STATE-WIDE) #3179
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3179"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from ubiquitarianism/leonida. Originally posted by eipastel on 2026-12-02T16:51:33Z.
Claimed in the coordination issue as: D3D12-LUA-MEMORY-LIMIT-IS-STATE-WIDE (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7352279491)
Depends on: none. Touches
d3d12/crates/leonida-lua/src/sandbox.rsandtests.rslike #3115 (per-mod PRNG); with a state per mod,math.random/math.randomseedare per mod already, so #3115's own PRNG would no longer be needed.What and why
One Lua state held every mod, so
MEMORY_LIMIT(128 MiB,sandbox.rs:28) was one budget for all of them: a mod holding memory made another mod's ordinary allocation fail, andcollectgarbage("count")reported the other mods' memory too (finding D3D12-LUA-MEMORY-LIMIT-IS-STATE-WIDE).Each mod now loads into a Lua state of its own (
sandbox::new_lua(&guard)), with the same 128 MiB limit. The time guard stays one, shared by the states (one call runs at a time), and its hook is installed on each state.Runtimekeeps the states alive for the handlers and callbacks that point into them (mlua 0.12 handles do not keep a state alive).Runtime::newcan no longer fail, so it returnsRuntime.docs/lua-modding.mdsays each mod has its own state and limit.Not changed: a mod that fails to load, or is switched off, keeps its state until the next reload (as before, when its objects stayed in the shared state).
Tested
tests::a_mod_that_holds_memory_does_not_starve_another: mod A holds 120 MiB, mod B allocates 40 MiB and counts its own memory.python -I scripts/red_green.py lua-memory-limit-per-mod --crate leonida-luaon base5b1fff821: red then green (1), pass on both: 44.cargo test -p leonida-lua --lib --locked: 45 passed, 0 failed.cargo clippy -p leonida-lua --all-targets --locked -- -D warnings: clean.cargo check --workspace --all-targets --locked: clean.python -m unittest discover -s tests -p "test_docs_*.py": OK.python -I scripts/check_no_game_data.pyon the changed files: clean.GPUs tested: n/a (no GPU or game files involved)
AI-assisted: yes. Code: Claude Opus 5.5. Independent read-only reviewer: Claude Opus (no blockers; its should-fix items,
Runtime::newreturningResultwith nothing left to fail and the singular "Lua state" in comments, are addressed in the second commit).Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).docs/design.md, with how it was confirmed. (n/a)Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-02T17:34:08Z.
Verified here: it applies on the current
mainand the wholeleonida-luasuite passes.What the change does, and why it is worth having: one Lua state held every mod, so
MEMORY_LIMIT(128 MiB) was one budget shared by all of them - a mod that eats it starves the rest. A state per mod makes the limit per mod, which is what a limit means when the thing it limits is a mod.The risk of a change like this is the opposite of what a test usually catches: not that one state misbehaves, but that something which used to be shared (a globals table, a registry entry, a handle) is now per-state and quietly duplicated or lost. 45 tests passing on the crate, with the memory ones included, is the evidence that the split did not lose anything the tests can see.
What it does not cover: a real mod actually reaching 128 MiB. That needs a launched title with two mods, one of them greedy - this machine can run neither, so the number that matters (does the second mod survive the first one's limit) is not measured here.
For the merge: the body says it touches
sandbox.rsandtests.rs"like #3115 (per-mod PRNG)" - if #3115 is still open, whichever lands second has a conflict in the same files, and that is cheaper to sort now than after a review.AI-assisted: yes - DeepSeek v4.1 (flash).
Written with an AI assistant.
Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T18:18:08Z.
Verification of #3179 (third party, Linux x86_64, Rust 1.98.1, no GPU, no game files)
057cc94d8a7f3050a058dde61396068a11cfa256(5 files, +65/-46).5b1fff821; merged withgit merge --no-ffontomain45dc41f95, no conflict.leonida-luabuilds and tests on Linux: its Windows-only dependencies are behindcfg(windows).Green (main + PR)
d3d12/)cargo test -p leonida-lua --lockedpython -I scripts/check_no_game_data.py <the 5 files>Red
python -I scripts/red_green.py --no-fetch --base origin/main --work-dir <scratch> pr/3179givesred does not build. The PR'stests.rsuses the newRuntime::new(..) -> Runtimesignature (no.unwrap()),so the tests alone do not compile on
main. This is not evidence either way.a_mod_that_holds_memory_does_not_starve_another, unchanged, tomain'stests.rs(it usesrigandstatus, whichmainhas). Then I rancargo test -p leonida-lua --lib --locked a_mod_that_holds_memory: Onmain, B's 40 MiBstring.repfails because A holds about 120 MiB of the shared 128 MiB. With the PR itpasses. Red then green.
Review of the diff
MEMORY_LIMITis perLuain mlua. Giving each mod its own state(
runtime.rs:267-269) makes the limit andcollectgarbage("count")per mod. The time budget stays sharedthrough one
Guard(sandbox.rs:50-65), which is right because one call runs at a time.Functionwith their owning state, and are calledonly with Rust values (
runtime.rs:291-296,:388-389). I found no Lua value passed from one mod's state intoanother's.
runtime.rs:268-269pushes the state intostatesbeforebuild_envandloadcanfail, so a mod that fails to load keeps its state until the runtime is dropped. Push it after a successful load,
or say why it stays.
mods x 128 MiB, not 128 MiB, anddocs/lua-modding.mdsays so ("128 MiB times theirnumber").
cargo clippyandcargo fmt --check, because the 1.98.1 clippy and rustfmt components are notavailable on this machine. CI covers both.
AI disclosure (models and reviewer) and the claim are in the body. The body notes the overlap with #3115.
Verdict: ready. Red then green shown by hand, and the crate suite is green on Linux.
AI-assisted verification: Claude Opus (Claude Code), separate agent per batch.
Generated by Claude Code
Imported from ubiquitarianism/leonida. Originally posted by eipastel on 2026-12-02T18:28:50Z.
Thanks to both of you for checking it.
2f2f697c0.run_scriptnow pushes the state intoRuntime::statesonly after the script's load call succeeds, so a failed mod's state and its memory are dropped at once; the handles it registered before failing go whenload_modswitches it off.cargo test -p leonida-lua --lib --locked: 45 passed; clippy-D warningsclean.red_green.pysaysred does not build: right, the second commit changedRuntime::newto returnRuntime, so the PR'stests.rsdoes not compile onmain. The red side was shown on the first commit (2d2ae41b9) withred_green.py lua-memory-limit-per-mod --crate leonida-lua: red then green (1), and MoonEyes' manual run above shows the same["false false false"].sandbox.rs/tests.rs. With a state per mod, #3115's per-mod PRNG is no longer needed, sincemath.randomalready has a state of its own per mod.AI-assisted: Claude Opus 5.5.
Imported from ubiquitarianism/leonida. Originally posted by Kal0s-design on 2026-12-02T18:53:03Z.
Ran natively on Windows 11, head
2f2f697c0merged into currentmain(f1a559851, clean merge).The thread covers Linux and the first commit's red. This is the Windows run on the current head, plus a few cases the new test doesn't cover.
Results (measured)
cargo test -p leonida-lua --lib --lockedon the mergea_mod_that_holds_memory_does_not_starve_anotheradded tomainleft: ["false false false"], same as on Linuxcargo clippy -p leonida-lua --all-targetscargo fmt --checkapi.rsdiffs already onmainIsolation probes (measured, throwaway tests, same probe on
mainand on the merge)mainThe last one was to check the new early drop. A's state goes away before
disableremoves its handlers, and passes after that are fine.What
2f2f697c0adds (measured). A mod that holds 100 MiB, registers a frame handler and a page, then callserror()at load. With the runtime still alive afterload_dir, process private memory was back at base with the PR. Onmainit stayed about 101 MiB higher. So a mod that fails at load gives its memory back right away now.math.random(measured). Mod B seeds with 7 and draws from a frame handler. Mod A callsmath.randomseed(1)in its own frame handler, before B. With the PR, B's numbers are the same as when B runs alone. Onmainthey change. That backs the author's point that #3115 isn't needed once this lands.Unload (measured). A mod that loads fine and is then switched off by an error in a handler keeps its state. With 100 MiB held at load, process private memory went from 2 to 102 MiB and stayed at 102 after the mod was disabled. It only went back down when the runtime was dropped.
maindoes the same (101 MiB), so it's not a regression. In code,statesis only ever pushed to. Now that each mod has its own state, dropping it ondisablewould be cheap to add, and it would give back that mod's memory without a reload. Up to you whether that belongs here or in a follow-up.Cost of a state per mod (measured, rough, debug build). 300 near-empty mods add 11 to 14 MiB of private memory with the PR and 4 to 5.5 MiB on
main(3 runs each), so about 25 KiB per extra state. Load time for 100 mods was 130 ms with the PR and 180 ms onmain. At that size the difference is noise.Merge
mainRuntime::new(..).unwrap(), which doesn't exist after this PR (E0599). Removing the.unwrap()gives 46 passedsandbox.rsandtests.rs(already mentioned in the thread)sandbox.rs,runtime.rsanddocs/lua-modding.md. This one isn't mentioned yet. #3125 turns the guard's deadline into anOptionand wraps the load call inguard.run(..), so whichever lands second has to move that into the newGuard::defaultand keep thestates.pushafter the callThe pre-existing flake
a_scan_without_a_size_reaches_the_end_of_the_imagefailed 6 times in 40 runs on the merge and 1 in 20 onmain, with--test-threads=4. Every failure wasleft: ["tail 1 0"], meaning the second scan found nothing. That's a wrong count, not a budget or memory error, so I don't think it comes from this change. It deserves its own issue though.Not checked: a real mod reaching the limit in the game, Linux or Wine on this head, and the per-state cost in a release build.
GPUs tested: n/a (CPU-only tests).
AI-assisted: yes (Claude Code).
Imported from ubiquitarianism/leonida. Originally posted by eipastel on 2026-12-02T19:21:58Z.
Thanks for the Windows run and the extra probes.
a_scan_without_a_size_reaches_the_end_of_the_imageflake: the cause is in the test's fake, not in the scan or this PR. The fake took the image base from the heapVec's address; the second scan starts atbase - 100, cannot read its range whole, somemory::readablereads it by absolute 4 KiB pages, and whenbase % 4096is 1..=99 the marker atbase + 3996sits in the piece that also covers bytes before the image and is skipped (["tail 1 0"]). Forcing the base to a page boundary + 50 fails every run; + 0 passes. The fix (a fixed page-aligned base, as a real image has) is ready oneipastel:lua-scan-test-page-aligned(claimed as D3D12-LUA-SCAN-TEST-PAGE-ALIGNED). I can't open it yet: accounts without write access get one open pull request at a time, so it goes up once this one lands.disable: agreed it is cheap now; I'll keep it for a follow-up so this PR stays one topic.Guard::defaultand thestates.pushafter the load call;Runtime::newwithout.unwrap()).AI-assisted: Claude Opus 5.5.
Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T19:27:59Z.
Re-verification of #3179 on the current head (third party, Linux x86_64, Rust 1.98.1, no GPU, no game files): the earlier nit is fixed, ready.
2f2f697c05b1fff821, 16 commits behindmainb41763227;git merge --no-ffis clean057cc94d82f2f697c0"leonida-lua: keep a mod's state only once it has loaded" (runtime.rs+5/-1). The other four files are unchanged.The earlier nit (state kept for a mod that fails to load): fixed.
run_scriptnow pushes theLuaintoRuntime::statesonly after the load call returnsOk(d3d12/crates/leonida-lua/src/runtime.rs:285-288). On any earlier?the state is dropped at the end of the function, andload_modthen callsShared::disable(runtime.rs:242-245), which drops the mod's handlers and pages. Dropping those handles after their state is safe: in mlua 0.12.3 aValueRefholds aWeakLua, and itsDroptouches the state only whentry_locksucceeds.Extra probe (local only, not committed): a mod that registers a
framehandler, a menu page with an action and a held key, then callserror("load boom"), next to a good mod. After three passes the bad mod isFailed, its handler never ran, its page is gone, and the good mod logged three times.cargo test -p leonida-lua --locked probe_: 1 passed.Commands (from
d3d12/onmain+ head, detached):cargo test -p leonida-lua --locked: lib 45 passed, 0 failed; doc-tests 0.python -I scripts/check_no_game_data.pyon the 5 changed files: exit 0.python -I scripts/run_standalone_tests.py -j 8): 660 files, 1 failed (tests/test_run_game_wine.py). Plainmainb41763227gives the same result, and the failure comes from the local environment, not this PR.Red (main + only the new test): I added
a_mod_that_holds_memory_does_not_starve_anotherunchanged to thetests.rsofmainb41763227.cargo test -p leonida-lua --lib --locked a_mod_that_holds_memory: FAILED,left: ["false false false"],right: ["true 41943040 true"]. With the head it passes. Red then green. (scripts/red_green.pystill reports "red does not build", because the PR'stests.rsuses the newRuntime::newsignature.)Notes, not blocking:
leonida-luafailure ina_scan_without_a_size_reaches_the_end_of_the_image(tests.rs:587,["tail 1 0"]). That test is inmainand this PR does not touch it; the author has a separate fix ready.2f2f697c0yet.Verdict: ready.
AI-assisted verification: Claude Opus (Claude Code), separate agent per batch.
Generated by Claude Code
Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-12-02T20:10:01Z.
Verified PR #3179 (
2f2f697c0) merged cleanly ontomain(f1a559851) on native Windows 10 x64 (Rust 1.98.1):python -I scripts/check_no_game_data.pyPASS.cargo test -p leonida-lua --lib --locked-- 45 passed, 0 failed (0.62 s).Verdict: PASS (CPU/unit tests; no game launch).
AI-assisted: yes (Antigravity).