leonida-lua: per-mod PRNG for math.random/math.randomseed #3115

Closed
imShangLi wants to merge 1 commit from upstream-pr/3115 into main
imShangLi commented 2026-12-02 11:42:24 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by imShangLi on 2026-12-02T11:42:24Z.


What

Give each mod its own math.random/math.randomseed PRNG state instead of sharing
the single lua_State PRNG through mlua's real C closures. Before this change, one
mod's math.randomseed(42) changed another mod's math.random sequence, breaking
the sandbox's mod-isolation promise ("one mod changing ... changes nothing for
another", docs/lua-modding.md:169-170).

Why

Finding D3D12-LUA-MATH-RANDOM-IS-STATE-WIDE: math table entries were copied per mod,
but math.random/math.randomseed remained the shared C closures over the shared
lua_State. Now they are per-mod Rust closures over a per-mod xorshift64 ModRng,
isolated from every other mod. Semantics match Lua 5.4:

  • math.random() -> [0,1)
  • math.random(n) -> [1,n]
  • math.random(m,n) -> [m,n]

Tests

New tests::math_random_is_per_mod_not_shared_state: mod A calls
math.randomseed(42); mod B and mod C each draw math.random(1000) twice. B's pair
must equal C's pair (A's reseed must not leak into B).

Red/green: before the fix B != C; after the fix all 41 leonida-lua unit tests pass,
including the new one.

Environment

Tested on Linux/Fedora 45 inside a VMware Workstation guest (no GPU, no game files
needed). leonida-lua is one of the 9 d3d12/ crates that compile offline on Linux,
so the suite runs natively here; no D3D12 adapter or Windows/MSVC required.

This change is AI-assisted.

Signed-off-by: imShangLi [email protected]

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5605681324 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115). Originally posted by [imShangLi](https://github.com/imShangLi) on 2026-12-02T11:42:24Z. --- ## What Give each mod its own `math.random`/`math.randomseed` PRNG state instead of sharing the single `lua_State` PRNG through mlua's real C closures. Before this change, one mod's `math.randomseed(42)` changed another mod's `math.random` sequence, breaking the sandbox's mod-isolation promise ("one mod changing ... changes nothing for another", docs/lua-modding.md:169-170). ## Why Finding D3D12-LUA-MATH-RANDOM-IS-STATE-WIDE: `math` table entries were copied per mod, but `math.random`/`math.randomseed` remained the shared C closures over the shared `lua_State`. Now they are per-mod Rust closures over a per-mod xorshift64 `ModRng`, isolated from every other mod. Semantics match Lua 5.4: - `math.random()` -> [0,1) - `math.random(n)` -> [1,n] - `math.random(m,n)` -> [m,n] ## Tests New `tests::math_random_is_per_mod_not_shared_state`: mod A calls `math.randomseed(42)`; mod B and mod C each draw `math.random(1000)` twice. B's pair must equal C's pair (A's reseed must not leak into B). Red/green: before the fix B != C; after the fix all 41 `leonida-lua` unit tests pass, including the new one. ## Environment Tested on Linux/Fedora 45 inside a VMware Workstation guest (no GPU, no game files needed). `leonida-lua` is one of the 9 `d3d12/` crates that compile offline on Linux, so the suite runs natively here; no D3D12 adapter or Windows/MSVC required. This change is AI-assisted. Signed-off-by: imShangLi <[email protected]>
Kal0s-design commented 2026-12-02 12:25:12 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Kal0s-design on 2026-12-02T12:25:12Z.


Ran this natively on Windows 11 (MSVC, Rust 1.98.1), head ba5121192 merged into current main.

Suite: cargo test -p leonida-lua --lib --locked ran 41 passed. With main's sandbox.rs and this branch's tests.rs, math_random_is_per_mod_not_shared_state fails with b="pair 742 50" c="pair 332 342", so the red and green reproduce on Windows.

Edge cases. The isolation works, but the replacement math.random/math.randomseed drift from Lua 5.4, which the workspace builds (mlua with lua54). Three calls panic in Rust rather than raising a Lua error.

I ran each call in its own mod through rig, inside pcall, with a throwaway test (not pushed). The same probe ran against main's sandbox for the reference column.

Call main (Lua 5.4's own) this PR
math.random(10) 1, integer 10.0, float
tostring(math.random(10)) an integer string, e.g. "7" "10.0"
math.random(0) random integer, all bits Rust panic: remainder with a divisor of zero (ModRng::range)
math.random(-5) error: interval is empty 1.586e19
math.random(5, 3) error: interval is empty 3.0 (bounds swapped silently)
math.random(10.0) 1, integer error: expected integer
math.random(math.mininteger, math.maxinteger) random integer Rust panic: subtract with overflow (debug build; wraps in release)
math.randomseed() reseeds randomly, returns the seed Rust panic: Option::unwrap() on None
math.randomseed(1.5) error: no integer representation error: expected integer
math.random(1, 2, 3) error: wrong number of arguments same

pcall does not stop these panics: in the test they unwind out of rig. Two of them are ordinary Lua idioms: math.random(0), and math.randomseed() with no argument to reseed from time.

Smaller points:

  • Every mod starts from the same constant (0x9e37…), so with no reseed each mod gets the same sequence on every launch. Lua 5.4 seeds each state randomly at start.
  • unit() divides by u64::MAX, so next() == u64::MAX gives exactly 1.0, outside [0, 1). That is rare but reachable; (next() >> 11) as f64 * 2^-53 is the usual way.
  • The new test would also fail on main without mod A. B and C share one generator there, so C draws after B. A test where B draws the same values with and without A's randomseed(42) would pin the leak itself.

One way to keep Lua 5.4's behaviour:

  • Return i64, so results are integers.
  • Read the arguments as Lua integers, so 10.0 is accepted.
  • Raise "interval is empty" when lo > hi.
  • Make random(0) return a full random integer.
  • Compute the span with wrapping arithmetic, as Lua's project does.
  • Let randomseed() with no argument take a fresh seed.
  • Give each new mod a random initial seed.

GPUs tested: n/a (CPU-only tests).

AI-assisted: yes (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7345310258 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7345310258). Originally posted by [Kal0s-design](https://github.com/Kal0s-design) on 2026-12-02T12:25:12Z. --- Ran this natively on Windows 11 (MSVC, Rust 1.98.1), head `ba5121192` merged into current `main`. **Suite:** `cargo test -p leonida-lua --lib --locked` ran 41 passed. With `main`'s `sandbox.rs` and this branch's `tests.rs`, `math_random_is_per_mod_not_shared_state` fails with `b="pair 742 50" c="pair 332 342"`, so the red and green reproduce on Windows. **Edge cases.** The isolation works, but the replacement `math.random`/`math.randomseed` drift from Lua 5.4, which the workspace builds (`mlua` with `lua54`). Three calls panic in Rust rather than raising a Lua error. I ran each call in its own mod through `rig`, inside `pcall`, with a throwaway test (not pushed). The same probe ran against `main`'s sandbox for the reference column. | Call | `main` (Lua 5.4's own) | this PR | |---|---|---| | `math.random(10)` | `1`, integer | `10.0`, **float** | | `tostring(math.random(10))` | an integer string, e.g. `"7"` | `"10.0"` | | `math.random(0)` | random integer, all bits | **Rust panic**: remainder with a divisor of zero (`ModRng::range`) | | `math.random(-5)` | error: interval is empty | `1.586e19` | | `math.random(5, 3)` | error: interval is empty | `3.0` (bounds swapped silently) | | `math.random(10.0)` | `1`, integer | error: expected integer | | `math.random(math.mininteger, math.maxinteger)` | random integer | **Rust panic**: subtract with overflow (debug build; wraps in release) | | `math.randomseed()` | reseeds randomly, returns the seed | **Rust panic**: `Option::unwrap()` on `None` | | `math.randomseed(1.5)` | error: no integer representation | error: expected integer | | `math.random(1, 2, 3)` | error: wrong number of arguments | same | `pcall` does not stop these panics: in the test they unwind out of `rig`. Two of them are ordinary Lua idioms: `math.random(0)`, and `math.randomseed()` with no argument to reseed from time. Smaller points: - Every mod starts from the same constant (`0x9e37…`), so with no reseed each mod gets the same sequence on every launch. Lua 5.4 seeds each state randomly at start. - `unit()` divides by `u64::MAX`, so `next() == u64::MAX` gives exactly `1.0`, outside `[0, 1)`. That is rare but reachable; `(next() >> 11) as f64 * 2^-53` is the usual way. - The new test would also fail on `main` without mod A. B and C share one generator there, so C draws after B. A test where B draws the same values with and without A's `randomseed(42)` would pin the leak itself. One way to keep Lua 5.4's behaviour: - Return `i64`, so results are integers. - Read the arguments as Lua integers, so `10.0` is accepted. - Raise "interval is empty" when `lo > hi`. - Make `random(0)` return a full random integer. - Compute the span with wrapping arithmetic, as Lua's `project` does. - Let `randomseed()` with no argument take a fresh seed. - Give each new mod a random initial seed. GPUs tested: n/a (CPU-only tests). AI-assisted: yes (Claude Code).
MoonEyes commented 2026-12-02 12:41:57 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T12:41:57Z.


This pull request touches the render path, so it needs an in-game run before it can be merged: unit tests and CI do not catch rendering regressions (a device loss after an earlier merge is why this gate exists).

Could you, or anyone with a working setup, post a run report on the current head merged onto current main:

  • the head SHA and the main SHA it was merged onto;
  • GPU, driver and OS;
  • at least 300 s in the world after loading;
  • device lost / crashes (count), and rendered fps (median) if you have them;
  • the same run on main alone for comparison, if you can.

Please do not attach logs or screenshots that show game content. If a run on this exact head is already posted, a link to it in a reply is enough.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7345737565 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7345737565). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T12:41:57Z. --- This pull request touches the render path, so it needs an in-game run before it can be merged: unit tests and CI do not catch rendering regressions (a device loss after an earlier merge is why this gate exists). Could you, or anyone with a working setup, post a run report on the **current head** merged onto current `main`: - the head SHA and the `main` SHA it was merged onto; - GPU, driver and OS; - at least 300 s in the world after loading; - device lost / crashes (count), and rendered fps (median) if you have them; - the same run on `main` alone for comparison, if you can. Please do not attach logs or screenshots that show game content. If a run on this exact head is already posted, a link to it in a reply is enough. AI-assisted (Claude Code).
lixonik commented 2026-12-02 15:19:24 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-12-02T15:19:24Z.


RUN (in game) -- render-path gate run for PR #3115:

  • PR head SHA: ba5121192
  • Merged onto main SHA: acc350745 (git merge --no-ff, clean merge; python -I scripts/check_no_game_data.py PASS; cargo test -p leonida-lua --lib --locked 45 passed, 0 failed)
  • Build: diag profile (diagnostics,dlss,mimalloc), Series S profile, DLSS on, Frame Gen off, same restored save snapshot
  • GPU / Driver / OS: NVIDIA GeForce RTX 5070 (12 GB), driver 595.79, Windows 10 x64
Run Time in world World samples Device lost / crashes / errors Median rendered FPS (ms) Slowest / fastest tenth (fps) Median draws
PR #3115 (ba5121192 on acc350745) 315 s (438.4 s total) 65 0 / 0 / 0 26.9 fps (37.1 ms) 21.8 / 27.8 4,411
main alone (acc350745) 315 s (451.7 s total) 65 0 / 0 / 0 26.8 fps (37.4 ms) 21.9 / 27.6 4,397

Both runs loaded cleanly into the world, stayed up past 300 s in-world with 0 device lost / 0 crashes / 0 ERROR lines, and closed cleanly. Rendered FPS matches main (26.9 vs 26.8 fps).

Verdict: PASS.

AI-assisted: yes (Antigravity).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7350127440 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7350127440). Originally posted by [lixonik](https://github.com/lixonik) on 2026-12-02T15:19:24Z. --- RUN (in game) -- render-path gate run for PR #3115: - **PR head SHA:** `ba5121192` - **Merged onto `main` SHA:** `acc350745` (`git merge --no-ff`, clean merge; `python -I scripts/check_no_game_data.py` PASS; `cargo test -p leonida-lua --lib --locked` **45 passed, 0 failed**) - **Build:** `diag` profile (`diagnostics,dlss,mimalloc`), Series S profile, DLSS on, Frame Gen off, same restored save snapshot - **GPU / Driver / OS:** NVIDIA GeForce RTX 5070 (12 GB), driver 595.79, Windows 10 x64 | Run | Time in world | World samples | Device lost / crashes / errors | Median rendered FPS (ms) | Slowest / fastest tenth (fps) | Median draws | | --- | ---: | ---: | --- | ---: | ---: | ---: | | **PR #3115 (`ba5121192` on `acc350745`)** | 315 s (438.4 s total) | 65 | **0 / 0 / 0** | **26.9 fps** (37.1 ms) | 21.8 / 27.8 | 4,411 | | **`main` alone (`acc350745`)** | 315 s (451.7 s total) | 65 | **0 / 0 / 0** | **26.8 fps** (37.4 ms) | 21.9 / 27.6 | 4,397 | Both runs loaded cleanly into the world, stayed up past 300 s in-world with 0 device lost / 0 crashes / 0 `ERROR` lines, and closed cleanly. Rendered FPS matches `main` (`26.9` vs `26.8` fps). Verdict: **PASS**. AI-assisted: yes (Antigravity).
MoonEyes commented 2026-12-02 18:14:03 +00:00 (Migrated from github.com)

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


Verified on Linux (the crate is portable): the new test is red then green, but the new math.random/math.randomseed let a mod panic the host and change Lua 5.4 semantics.

head      ba5121192 (pr/3115)
base      origin/main 45dc41f95, merge base 6c7f6b60c, merges cleanly
toolchain Rust 1.98.1 (d3d12/rust-toolchain.toml), x86_64-unknown-linux-gnu, no GPU, no game files

Red/green: python -I scripts/red_green.py pr/3115 --base origin/main --no-fetch --work-dir <scratch>

red: the base plus the tests of d3d12/crates/leonida-lua/src/tests.rs
ran: cargo -p leonida-lua
red then green (1): leonida_lua::tests::math_random_is_per_mod_not_shared_state
pass on both: 44
verdict: red then green

So the isolation itself works. I then added a throwaway probe test (not pushed) to the merged tree, a mod running through rig(...) as the existing tests do:

mod code result on the merge
pcall(math.randomseed) panic sandbox.rs:287:53: called Option::unwrap() on a None value; pcall does not contain it, the test thread dies
pcall(math.random, 0) panic sandbox.rs:109:13: attempt to calculate the remainder with a divisor of zero (debug; % 0 panics in release too)
math.type(math.random(10)), tostring(...) float, 5.0 (Lua 5.4, which mlua is built with, returns an integer: 5)
pcall(math.random, 5, 1) true 1.0 (Lua 5.4 raises "interval is empty")

Defects

  1. d3d12/crates/leonida-lua/src/sandbox.rs:287 (merged-tree line): args.into_iter().next().unwrap() panics on math.randomseed() with no argument, which is valid Lua 5.4. A mod can take down the runtime, defeating the sandbox's own "a mod cannot crash the host" intent. Return an error (or reseed from a fresh value) instead of unwrap.
  2. sandbox.rs:109 (range): 1 + self.next() % n with n == 0 divides by zero; math.random(0) (valid in 5.4, returns a full random integer) and math.random(minint, maxint) (hi - lo + 1 overflows to 0, and is an overflow panic in debug before that) both reach it. Negative n is cast with as u64 and returns a huge value instead of an error.
  3. Return type: every integer form returns f64, so math.random(n) is a float (5.0), math.type says float, and values above 2^53 lose precision. Return i64 for the 1- and 2-argument forms.
  4. random(m, n) with m > n swaps the bounds instead of raising "interval is empty"; float arguments with an integral value (math.random(10.0)) are rejected with "expected integer" while Lua accepts them.
  5. unit() divides by u64::MAX, so it can return exactly 1.0 (the documented range is [0, 1)). (next() >> 11) as f64 * 2^-53 is the usual fix.
  6. Every mod starts from the same constant seed 0x9e3779b97f4a7c15, so all unseeded mods draw the same sequence and it is the same on every run. Stock Lua 5.4 seeds each state randomly. If deterministic is intended, say so in the docs; otherwise seed each mod from a per-run value.

Suggested shape: keep the per-mod state, but implement random by Lua 5.4's rules (lmathlib.c math_random/project), with integer results and error returns, and add tests for no-arg randomseed, random(0), random(5, 1) and math.type.

PR template: no GPUs tested: line (fine for a CPU-only crate, but say so). AI use is disclosed.

Verdict: defects. The isolation is right and proven red/green; the replacement functions need to follow Lua 5.4 and must not panic before merge.

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


Generated by Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7354179616 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7354179616). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T18:14:03Z. --- **Verified on Linux (the crate is portable): the new test is red then green, but the new `math.random`/`math.randomseed` let a mod panic the host and change Lua 5.4 semantics.** ``` head ba5121192 (pr/3115) base origin/main 45dc41f95, merge base 6c7f6b60c, merges cleanly toolchain Rust 1.98.1 (d3d12/rust-toolchain.toml), x86_64-unknown-linux-gnu, no GPU, no game files ``` **Red/green:** `python -I scripts/red_green.py pr/3115 --base origin/main --no-fetch --work-dir <scratch>` ``` red: the base plus the tests of d3d12/crates/leonida-lua/src/tests.rs ran: cargo -p leonida-lua red then green (1): leonida_lua::tests::math_random_is_per_mod_not_shared_state pass on both: 44 verdict: red then green ``` So the isolation itself works. I then added a throwaway probe test (not pushed) to the merged tree, a mod running through `rig(...)` as the existing tests do: | mod code | result on the merge | |---|---| | `pcall(math.randomseed)` | **panic** `sandbox.rs:287:53: called Option::unwrap() on a None value`; `pcall` does not contain it, the test thread dies | | `pcall(math.random, 0)` | **panic** `sandbox.rs:109:13: attempt to calculate the remainder with a divisor of zero` (debug; `% 0` panics in release too) | | `math.type(math.random(10))`, `tostring(...)` | `float`, `5.0` (Lua 5.4, which mlua is built with, returns an integer: `5`) | | `pcall(math.random, 5, 1)` | `true 1.0` (Lua 5.4 raises "interval is empty") | **Defects** 1. `d3d12/crates/leonida-lua/src/sandbox.rs:287` (merged-tree line): `args.into_iter().next().unwrap()` panics on `math.randomseed()` with no argument, which is valid Lua 5.4. A mod can take down the runtime, defeating the sandbox's own "a mod cannot crash the host" intent. Return an error (or reseed from a fresh value) instead of `unwrap`. 2. `sandbox.rs:109` (`range`): `1 + self.next() % n` with `n == 0` divides by zero; `math.random(0)` (valid in 5.4, returns a full random integer) and `math.random(minint, maxint)` (`hi - lo + 1` overflows to 0, and is an overflow panic in debug before that) both reach it. Negative `n` is cast with `as u64` and returns a huge value instead of an error. 3. Return type: every integer form returns `f64`, so `math.random(n)` is a float (`5.0`), `math.type` says `float`, and values above 2^53 lose precision. Return `i64` for the 1- and 2-argument forms. 4. `random(m, n)` with `m > n` swaps the bounds instead of raising "interval is empty"; float arguments with an integral value (`math.random(10.0)`) are rejected with "expected integer" while Lua accepts them. 5. `unit()` divides by `u64::MAX`, so it can return exactly `1.0` (the documented range is `[0, 1)`). `(next() >> 11) as f64 * 2^-53` is the usual fix. 6. Every mod starts from the same constant seed `0x9e3779b97f4a7c15`, so all unseeded mods draw the same sequence and it is the same on every run. Stock Lua 5.4 seeds each state randomly. If deterministic is intended, say so in the docs; otherwise seed each mod from a per-run value. Suggested shape: keep the per-mod state, but implement `random` by Lua 5.4's rules (`lmathlib.c` `math_random`/`project`), with integer results and error returns, and add tests for no-arg `randomseed`, `random(0)`, `random(5, 1)` and `math.type`. PR template: no `GPUs tested:` line (fine for a CPU-only crate, but say so). AI use is disclosed. **Verdict: defects.** The isolation is right and proven red/green; the replacement functions need to follow Lua 5.4 and must not panic before merge. AI-assisted verification: Claude Opus (Claude Code), separate agent per batch. --- _Generated by [Claude Code](https://claude.ai/code)_
MoonEyes commented 2026-12-02 18:21:31 +00:00 (Migrated from github.com)

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


RUN (in game, batch of seventeen render-path pull requests), each head merged with git merge --no-ff onto main 3c106eb2f, in one build: #3111 15b579756, #2948 5284c6eae, #2698 1f188c4f7, #2946 44bf554fe, #3001 d924cbb65, #2832 0c861595a, #2915 58e8535cf, #2822 d359a2f85, #2896 c9c6b103d, #2983 8278ef1b9, #3115 ba5121192, #2945 d2c08c14f, #2975 74512d658, #2951 26da88e8e, #2800 b6ebcedd4, #2893 7c7e99b48, #3113 fa1460b6b (and #3097 0d7a451ab, merged since). RTX 4060 8 GB, driver 610.88, Windows 11. Series S, -Resolution 1080, frame generation 2x, 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 (43 samples) median 14.6, mean 12.7
Rendered fps, last 120 s median 13.7
Time under 5 fps in the world 13 % (short drops, lowest sample 0.3 fps)

The drops under 5 fps line up with shaders being translated while walking (about 500 translations in the last 330 s): this batch changes the shader translation, so the shader cache built by earlier runs did not apply and the pipeline precompile alone took about 45 minutes. The batch-5 run on the same machine and route had no sample under 5 fps (median 16.4). I read this as cold-cache stutter, not as a regression of a single pull request, but this run cannot tell them apart.

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. A first attempt of this batch is not counted: the run script gave up waiting for the game window after 40 minutes of precompile.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7354438976 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7354438976). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T18:21:31Z. --- RUN (in game, batch of seventeen render-path pull requests), each head merged with `git merge --no-ff` onto main `3c106eb2f`, in one build: #3111 `15b579756`, #2948 `5284c6eae`, #2698 `1f188c4f7`, #2946 `44bf554fe`, #3001 `d924cbb65`, #2832 `0c861595a`, #2915 `58e8535cf`, #2822 `d359a2f85`, #2896 `c9c6b103d`, #2983 `8278ef1b9`, #3115 `ba5121192`, #2945 `d2c08c14f`, #2975 `74512d658`, #2951 `26da88e8e`, #2800 `b6ebcedd4`, #2893 `7c7e99b48`, #3113 `fa1460b6b` (and #3097 `0d7a451ab`, merged since). RTX 4060 8 GB, driver 610.88, Windows 11. Series S, `-Resolution 1080`, frame generation 2x, 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 (43 samples) | median 14.6, mean 12.7 | | Rendered fps, last 120 s | median 13.7 | | Time under 5 fps in the world | 13 % (short drops, lowest sample 0.3 fps) | The drops under 5 fps line up with shaders being translated while walking (about 500 translations in the last 330 s): this batch changes the shader translation, so the shader cache built by earlier runs did not apply and the pipeline precompile alone took about 45 minutes. The batch-5 run on the same machine and route had no sample under 5 fps (median 16.4). I read this as cold-cache stutter, not as a regression of a single pull request, but this run cannot tell them apart. 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. A first attempt of this batch is not counted: the run script gave up waiting for the game window after 40 minutes of precompile. AI-assisted (Claude Code).
fiestorra commented 2026-12-02 23:26:58 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-02T23:26:58Z.


VERIFY-3115 — Windows nativo: pasa, y un hallazgo sobre lo que el test no asegura

Own commit ba5121192 — sandbox.rs (+102), tests.rs (+21)
Head ba5121192 (on an older main: 41 tests here, 47 on main 81efe4566)

Ran

cargo test -p leonida-lua     41 passed; 0 failed
  tests::math_random_is_per_mod_not_shared_state ... ok

What the change is: math.random/math.randomseed are overridden per mod with a small xorshift64 (ModRng), because the shared C closures all read the one lua_State PRNG — so one mod's randomseed moved every other mod's sequence. The comment says it, and the test does: mod A reseeds, mods B and C never do, and B's pair must equal C's pair.

Two controls, and what they taught me:

  1. Sharing one RNG across mods (what the old code effectively did) — Rc<RefCell<ModRng>> in a static does not compile (cannot be shared between threads safely). So the type system already makes the bug harder to reintroduce than the test does; I could not express the regression in the same shape.
  2. Making unit() return a constant (0.5) — the test still passes.

That second one is the finding: the test pins isolation, not randomness. With math.random returning the same number every time, B's "500 500" equals C's "500 500" and the assertion is satisfied. What it does catch is the leak of A's seed into B's sequence, which is what it was written for — but a one-line addition would also catch a dead RNG:

let b = fake.of("b")[0].clone();
let draws: Vec<&str> = b.split_whitespace().skip(1).collect();
assert_ne!(draws[0], draws[1], "two draws from one mod's RNG must differ");

I would not block on it — the property the pull request claims is isolation, and that is tested — but a test named after a shared-state bug is the one place worth also proving the state is doing something.

What I could not test

  • Two mods interacting in a real run: the rig loads three Lua mods into one runtime and reads the log; no title.

Written with an AI assistant.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7362009066 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7362009066). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-02T23:26:58Z. --- ## VERIFY-3115 — Windows nativo: pasa, **y un hallazgo sobre lo que el test no asegura** | | | |---|---| | Own commit | `ba5121192` — `sandbox.rs` (+102), `tests.rs` (+21) | | Head | `ba5121192` (on an older `main`: 41 tests here, 47 on `main` `81efe4566`) | **Ran** ``` cargo test -p leonida-lua 41 passed; 0 failed tests::math_random_is_per_mod_not_shared_state ... ok ``` **What the change is**: `math.random`/`math.randomseed` are **overridden per mod** with a small xorshift64 (`ModRng`), **because the shared C closures all read the one `lua_State` PRNG** — so one mod's `randomseed` moved every other mod's sequence. The comment says it, and the test does: mod A reseeds, **mods B and C never do**, and **B's pair must equal C's pair**. **Two controls, and what they taught me**: 1. **Sharing one RNG across mods** (what the old code effectively did) — **`Rc<RefCell<ModRng>>` in a `static` does not compile** (`cannot be shared between threads safely`). **So the type system already makes the bug harder to reintroduce than the test does**; I could not express the regression in the same shape. 2. **Making `unit()` return a constant (`0.5`)** — **the test still passes**. **That second one is the finding: the test pins *isolation*, not *randomness*.** With `math.random` returning the same number every time, **B's "500 500" equals C's "500 500"** and the assertion is satisfied. **What it does catch is the leak of A's seed into B's sequence, which is what it was written for — but a one-line addition would also catch a dead RNG**: ```rust let b = fake.of("b")[0].clone(); let draws: Vec<&str> = b.split_whitespace().skip(1).collect(); assert_ne!(draws[0], draws[1], "two draws from one mod's RNG must differ"); ``` **I would not block on it** — the property the pull request claims is isolation, and that is tested — **but a test named after a shared-state bug is the one place worth also proving the state is doing something.** ## What I could not test - **Two mods interacting in a real run**: the rig loads three Lua mods into one runtime and reads the log; no title. Written with an AI assistant.
MoonEyes commented 2026-12-03 07:01:15 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-03T07:01:15Z.


This pull request has a merge conflict with current main (d9b618f10), so it can't be run in game or merged as it is. Could you merge the latest main into it (or rebase onto it) and resolve the conflict? Once the head is updated, the in-game gate run can be done on the new head.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7370500372 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7370500372). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-03T07:01:15Z. --- This pull request has a merge conflict with current `main` (`d9b618f10`), so it can't be run in game or merged as it is. Could you merge the latest `main` into it (or rebase onto it) and resolve the conflict? Once the head is updated, the in-game gate run can be done on the new head. AI-assisted (Claude Code).
fiestorra commented 2026-12-03 10:25:01 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T10:25:01Z.


Intenté rebasarla y no la voy a entregar: la unión automática no sirve para estos dos conflictos, y lo cuento con el error

Las dos PRs de conflicto parecían adiciones de los dos lados (un ModRng nuevo y un test nuevo), así que probé a quedarme con las dos mitades. No funciona, y el compilador lo dice:

sandbox.rs:  HEAD 2 líneas (doc + `pub fn new_lua(guard: &Guard) -> Result<Lua> {`)
             suyo 46 líneas (`struct ModRng` + `impl ModRng`)
             unión → "error: this file contains an unclosed delimiter"

tests.rs:    HEAD 11 líneas · suyo 18 líneas
             unión → "error: unclosed delimiter" en `fn math_random_is_per_mod_not_shared_state()`

Y el motivo es el mismo en los dos: el bloque de conflicto no es una unidad completa — corta la firma de una función y deja el cuerpo fuera. Pegar las dos mitades deja una función abierta.

Y en sandbox.rs hay algo más que la unión no podía saber: main ya cambió new_lua — ahora es pub fn new_lua() -> Result<(Lua, Guard)>, sin argumento — y la rama trae la versión vieja, new_lua(guard: &Guard) -> Result<Lua>. Quedarse con las dos es dos funciones con el mismo nombre y la segunda sin cuerpo.

Lo que eso convierte en obvio: esta PR no es «un ModRng nuevo»: es un ModRng nuevo más un new_lua que ya no existe con esa firma. La resolución correcta es mirar qué hizo main con new_lua y portar el ModRng al mundo nuevo — y eso es leer, no pegar.

No la he empujado: el worktree está borrado, el rebase abortado y main sigue limpio. Y lo dejo escrito porque el intento costó veinte minutos y el siguiente no tiene por qué repetirlo.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7375200796 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7375200796). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T10:25:01Z. --- ## Intenté rebasarla y **no la voy a entregar**: la unión automática no sirve para estos dos conflictos, y lo cuento con el error **Las dos PRs de conflicto parecían adiciones de los dos lados** (**un `ModRng` nuevo y un test nuevo**), **así que probé a quedarme con las dos mitades.** **No funciona, y el compilador lo dice**: ``` sandbox.rs: HEAD 2 líneas (doc + `pub fn new_lua(guard: &Guard) -> Result<Lua> {`) suyo 46 líneas (`struct ModRng` + `impl ModRng`) unión → "error: this file contains an unclosed delimiter" tests.rs: HEAD 11 líneas · suyo 18 líneas unión → "error: unclosed delimiter" en `fn math_random_is_per_mod_not_shared_state()` ``` **Y el motivo es el mismo en los dos**: **el bloque de conflicto no es una unidad completa** — **corta la firma de una función y deja el cuerpo fuera**. **Pegar las dos mitades deja una función abierta.** **Y en `sandbox.rs` hay algo más que la unión no podía saber**: **`main` ya cambió `new_lua`** — **ahora es `pub fn new_lua() -> Result<(Lua, Guard)>`, sin argumento** — **y la rama trae la versión vieja, `new_lua(guard: &Guard) -> Result<Lua>`.** **Quedarse con las dos es dos funciones con el mismo nombre y la segunda sin cuerpo.** **Lo que eso convierte en obvio**: **esta PR no es «un `ModRng` nuevo»: es un `ModRng` nuevo más un `new_lua` que ya no existe con esa firma.** **La resolución correcta es mirar qué hizo `main` con `new_lua` y portar el `ModRng` al mundo nuevo** — **y eso es leer, no pegar.** **No la he empujado**: **el worktree está borrado, el rebase abortado y `main` sigue limpio.** **Y lo dejo escrito porque el intento costó veinte minutos y el siguiente no tiene por qué repetirlo.**
fiestorra commented 2026-12-03 10:26:12 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T10:26:12Z.


Corrección a lo que escribí arriba, porque me equivoqué en un dato y prefiero decirlo yo

Dije que main había cambiado new_lua a pub fn new_lua() -> Result<(Lua, Guard)>. Es al revés: esa firma es la de esta PR, y main sigue con la antigua:

base       L75   fn new_lua(...)
main       L85   fn new_lua(guard: &Guard) -> Result<Lua>      ← la de siempre
esta PR    L119  pub fn new_lua() -> Result<(Lua, Guard)>      ← la nueva, con el ModRng

Lo que sí cambió main desde la base de la PR es el contenido de los dos ficheros, y no poco:

d3d12/crates/leonida-lua/src/sandbox.rs   +43 / −15
d3d12/crates/leonida-lua/src/tests.rs     +312 / −9

Y eso es lo que hace esta rebasada distinta de las de switches.md: allí el conflicto era una línea derivable (el recuento se recalcula contando el fichero). Aquí hay dos cambios de verdad en el mismo sitio — la PR reescribe new_lua y main ha añadido 43 líneas alrededor de ella — y por eso ni «quedarse con los dos lados» ni «tomar el fichero de la PR» sirven: lo primero deja la función abierta (lo comprobé: unclosed delimiter en los dos ficheros) y lo segundo tiraría las 43 líneas y los 312 de main.

La resolución, dicha en una frase para quien la haga: coger el ModRng y la firma nueva de esta PR y aplicarlos encima de la versión de main de new_lua — o sea, mirar qué hacen las dos versiones del cuerpo y quedarse con una que tenga lo de main y lo del PR. Eso es leer veinte minutos, y no lo va a hacer un script.

Lo que no he hecho: intentarlo más allá del unclosed delimiter. El worktree está borrado, el rebase abortado y no hay rama mía con esto.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7375229834 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7375229834). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T10:26:12Z. --- **Corrección a lo que escribí arriba, porque me equivoqué en un dato y prefiero decirlo yo** **Dije que `main` había cambiado `new_lua` a `pub fn new_lua() -> Result<(Lua, Guard)>`. Es al revés**: **esa firma es la de esta PR, y `main` sigue con la antigua**: ``` base L75 fn new_lua(...) main L85 fn new_lua(guard: &Guard) -> Result<Lua> ← la de siempre esta PR L119 pub fn new_lua() -> Result<(Lua, Guard)> ← la nueva, con el ModRng ``` **Lo que sí cambió `main` desde la base de la PR es el contenido de los dos ficheros, y no poco**: ``` d3d12/crates/leonida-lua/src/sandbox.rs +43 / −15 d3d12/crates/leonida-lua/src/tests.rs +312 / −9 ``` **Y eso es lo que hace esta rebasada distinta de las de `switches.md`**: **allí el conflicto era una línea derivable** (**el recuento se recalcula contando el fichero**). **Aquí hay dos cambios de verdad en el mismo sitio** — **la PR reescribe `new_lua` y `main` ha añadido 43 líneas alrededor de ella** — **y por eso ni «quedarse con los dos lados» ni «tomar el fichero de la PR» sirven**: **lo primero deja la función abierta** (**lo comprobé: `unclosed delimiter` en los dos ficheros**) **y lo segundo tiraría las 43 líneas y los 312 de `main`.** **La resolución, dicha en una frase para quien la haga**: **coger el `ModRng` y la firma nueva de esta PR y aplicarlos **encima** de la versión de `main` de `new_lua`** — **o sea, mirar qué hacen las dos versiones del cuerpo y quedarse con una que tenga lo de `main` y lo del PR.** **Eso es leer veinte minutos, y no lo va a hacer un script.** **Lo que no he hecho**: **intentarlo más allá del `unclosed delimiter`.** **El worktree está borrado, el rebase abortado y no hay rama mía con esto.**
fiestorra commented 2026-12-03 10:26:46 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T10:26:46Z.


Ahora está claro del todo, y es la explicación que le falta a esta rebasada: los tres árboles tienen la misma función en tres versiones distintas, y no es un conflicto de posición.

base        pub fn new_lua() -> Result<(Lua, Guard)>          ← crea su propio Guard
            (sin ModRng, un `math.random` global para todos)

main        pub fn new_lua(guard: &Guard) -> Result<Lua>       ← el Guard se pasa de fuera
            + impl Default for Guard
            + hide_string_dump(&lua)   ← quita `dump` de la metatabla de string
            (sin ModRng)

esta PR     pub fn new_lua() -> Result<(Lua, Guard)>           ← como la base
            + ModRng (xorshift64 por mod) en `new_lua`

La PR se escribió sobre la base y no vio el cambio de main — no es que los dos hayan añadido cosas distintas al mismo sitio: es que main cambió la forma de la función (el Guard pasó de dentro a fuera) y la PR cambió su contenido (el ModRng) sobre la forma vieja.

Por eso la resolución no es ni un lado ni el otro, y ahora se puede escribir sin ambigüedad:

la version de main de new_lua (con guard como argumento y con hide_string_dump), más el bloque del ModRng de esta PR dentro de ella — o sea, B + RNG, donde la base era A, main hizo B y la PR hizo A + RNG.

Y por eso «quedarse con los dos lados» no solo rompía la sintaxis: habría dejado dos new_lua y ningún camino que tenga las dos ideas.

Lo que no voy a hacer, y es la última vez que lo digo en este hilo: escribir yo ese B + RNG. new_lua construye el entorno de un mod — es la frontera de seguridad del sandbox de Lua — y un merge mal hecho aquí no rompe un test, abre una puerta. El autor tiene la PR en la cabeza; yo tengo el diagnóstico escrito, que es lo que puedo aportar sin ejecutar el juego.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7375243744 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7375243744). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T10:26:46Z. --- **Ahora está claro del todo, y es la explicación que le falta a esta rebasada**: **los tres árboles tienen la misma función en tres versiones distintas, y no es un conflicto de posición.** ``` base pub fn new_lua() -> Result<(Lua, Guard)> ← crea su propio Guard (sin ModRng, un `math.random` global para todos) main pub fn new_lua(guard: &Guard) -> Result<Lua> ← el Guard se pasa de fuera + impl Default for Guard + hide_string_dump(&lua) ← quita `dump` de la metatabla de string (sin ModRng) esta PR pub fn new_lua() -> Result<(Lua, Guard)> ← como la base + ModRng (xorshift64 por mod) en `new_lua` ``` **La PR se escribió sobre la base y no vio el cambio de `main`** — **no es que los dos hayan añadido cosas distintas al mismo sitio: es que `main` cambió la **forma** de la función** (**el `Guard` pasó de dentro a fuera**) **y la PR cambió su **contenido** (el `ModRng`) sobre la forma vieja.** **Por eso la resolución no es ni un lado ni el otro, y ahora se puede escribir sin ambigüedad**: > **la version de `main` de `new_lua` (con `guard` como argumento y con `hide_string_dump`), más el bloque del `ModRng` de esta PR dentro de ella** — **o sea, `B + RNG`**, **donde la base era `A`, `main` hizo `B` y la PR hizo `A + RNG`.** **Y por eso «quedarse con los dos lados» no solo rompía la sintaxis: habría dejado dos `new_lua` y **ningún** camino que tenga las dos ideas.** **Lo que no voy a hacer, y es la última vez que lo digo en este hilo**: **escribir yo ese `B + RNG`.** **`new_lua` construye el entorno de un mod — es la frontera de seguridad del sandbox de Lua** — **y un merge mal hecho aquí no rompe un test, abre una puerta.** **El autor tiene la PR en la cabeza; yo tengo el diagnóstico escrito, que es lo que puedo aportar sin ejecutar el juego.**
MoonEyes commented 2026-12-03 18:02:42 +00:00 (Migrated from github.com)

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


Thanks for the work on this. This pull request has a merge conflict with the current main and has had no new commit, comment or review for more than 5 hours, so I am closing it to keep the list of open pull requests manageable. This is not a judgement of the change. Whenever you like, merge the latest main into your branch, resolve the conflict, and reopen it (or open a new pull request that links this one). Please re-run the relevant tests on the new head; a reviewer will look at it when time allows, with no guarantee of timing or outcome.


Generated by Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7387507095 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3115#issuecomment-7387507095). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-03T18:02:42Z. --- Thanks for the work on this. This pull request has a merge conflict with the current `main` and has had no new commit, comment or review for more than 5 hours, so I am closing it to keep the list of open pull requests manageable. This is not a judgement of the change. Whenever you like, merge the latest `main` into your branch, resolve the conflict, and reopen it (or open a new pull request that links this one). Please re-run the relevant tests on the new head; a reviewer will look at it when time allows, with no guarantee of timing or outcome. --- _Generated by [Claude Code](https://claude.ai/code)_

Pull request closed

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!3115
No description provided.