leonida-lua: per-mod PRNG for math.random/math.randomseed #3115
Closed
github-bot
wants to merge 1 commit from
github-bot/gh-3115 into main
AGit
pull from: github-bot/gh-3115
merge into: github:main
github:main
github:perf/darner-title-priority-ceiling
github:gh-readonly-queue/main/pr-3311-b5c45b663dbc5a9c3532bb3f307e5f81b32faefa
github:gh-readonly-queue/main/pr-3088-af22e7847ff5808f72d1a1881c24be2fafd20b54
github:gh-readonly-queue/main/pr-3123-7f3fa026a94c6646e89244f28e1ce22290361867
github:gh-readonly-queue/main/pr-3354-637baa0b77ba47222e7280b17c1a59c6a1781d57
github:gh-readonly-queue/main/pr-3365-d7a0e0196a43834813014b4bd3aa5502a8263b14
github:gh-readonly-queue/main/pr-3361-5dfe8bbd05ed12fb2f2e1718d9af77a7c5f46fd8
github:gh-readonly-queue/main/pr-3366-8da9148204e9d12c585efa9ac2b7cc1ab08c7682
github:fix/runtime-test-conservative-fixtures
github:ci/shard-semantic-linux
github:docs/fg-limit-fps-switch
github:fix/runtime-test-fixture-paths
github:fix/runtime-test-fixture-readers
github:fix/read-file-hard-link
github:fix/book-slot-heap-never-read
github:fix/depth-resolve-spv-path
github:fix/indirect-unused-batched
github:gh-pr/3358/base
github:fix/xmem-refusal-diagnostics
github:gh-pr/3357/base
github:ci/shorten-ci-time
github:fix/alias-later-queued-submissions
github:claude/gallant-sagan-aamatr
github:gh-pr/3342/base
github:gh-pr/3341/base
github:d3d12/agility-sdk-621
github:gh-pr/3293/base
github:gh-pr/3319/base
github:gh-pr/3318/base
github:gh-pr/3315/base
github:gh-pr/3313/base
github:gh-pr/3314/base
github:claude/fervent-curie-m19lnr
github:gh-pr/3216/base
github:gh-pr/3272/base
github:gh-pr/3276/base
github:gh-pr/3279/base
github:gh-pr/3257/base
github:gh-pr/3258/base
github:gh-pr/3271/base
github:codex/skip-no-hit-ray-passes
github:gh-pr/3230/base
github:gh-pr/3266/base
github:gh-pr/3247/base
github:gh-pr/3246/base
github:gh-pr/3244/base
github:claude/sharp-sagan-1jqnp3
github:t3/preserve-fsr-sdk-restart-path
github:t3/propagate-host-failure-hresult
github:t3/launcher-custom-parameters
github:t3/series-x-2160-startup
github:codex/d3d12-uncapped-simulation
github:ci/less-to-run
github:perf/native-compute-shader-forms
github:claude/blissful-franklin-ukp7ag
github:codex/full-precompile-default
github:gh-pr/3166/base
github:gh-pr/3148/base
github:gh-pr/3138/base
github:gh-pr/3106/base
github:gh-pr/3057/base
github:gh-pr/2756/base
github:gh-pr/2812/base
github:gh-pr/3032/base
github:gh-pr/2992/base
github:notes/card-time-and-plant-flicker
github:gh-pr/2986/base
github:gh-pr/3000/base
github:gh-pr/2966/base
github:gh-pr/2924/base
github:gh-pr/726/base
github:gh-pr/2761/base
github:gh-pr/2663/base
github:gh-pr/2861/base
github:gh-pr/2862/base
github:gh-pr/2820/base
github:gh-pr/2811/base
github:gh-pr/2803/base
github:rt-call-trace
github:gh-pr/2802/base
github:gh-pr/2766/base
github:perf/ahead-split
github:gh-pr/2589/base
github:gh-pr/2699/base
github:gh-pr/2696/base
github:docs/readme-runtime-proposal
github:gh-pr/1346/base
github:codex/coord-claim-check-20261124-7e48
No reviewers
Labels
Clear labels
accessibility
Barrier affecting people with disabilities
area: ci
.github/ workflows and settings
area: d3d12
The D3D12 runtime in d3d12/ (Rust: leonida.exe and its crates)
area: docs
Documentation
area: launcher
The launcher (launcher/)
area: runtime (legacy)
The earlier Vulkan runtime in runtime/
area: shader translator
The shader translator (leonida-shader, tools/rdna2spirv) and its tests
area: tools
tools/ and scripts/
area: viewer
The map viewer (viewer/)
bug
Something isn't working
dependencies
Pull requests that update a dependency file
documentation
Improvements or additions to documentation
duplicate
This issue or pull request already exists
enhancement
New feature or request
good first issue
Good for newcomers
help wanted
Extra attention is needed
invalid
This doesn't seem right
missing claim
Needs a claim in #14
needs in-game run
Changes the code a frame runs through: needs the 300 s in-game gate (docs/game_gate.md)
needs rebase
Conflicts with the base branch: rebase it on main
needs-triage
Needs maintainer evaluation before the next triage state
question
Further information is requested
ready-for-agent
Fully specified and ready for an AFK agent
submodules
Pull requests that update submodules code
wontfix
This will not be worked on
No labels
accessibility
area: ci
area: d3d12
area: docs
area: launcher
area: runtime (legacy)
area: shader translator
area: tools
area: viewer
bug
dependencies
documentation
duplicate
enhancement
good first issue
help wanted
invalid
missing claim
needs in-game run
needs rebase
needs-triage
question
ready-for-agent
submodules
wontfix
Milestone
Clear milestone
No items
No milestone
Assignees
Clear assignees
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.
Dependencies
No dependencies set
Reference
github/ubiquitarianism--leonida!3115
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-3115"
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?
@imShangLi on GitHub · 2026-12-02 11:42 UTC · original
imShangLi:fix/d3d12-lua-math-random-per-mod→main· +122 −1 · 2 files · 1 commits · closed without mergingWhat
Give each mod its own
math.random/math.randomseedPRNG state instead of sharingthe single
lua_StatePRNG through mlua's real C closures. Before this change, onemod's
math.randomseed(42)changed another mod'smath.randomsequence, breakingthe 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:
mathtable entries were copied per mod,but
math.random/math.randomseedremained the shared C closures over the sharedlua_State. Now they are per-mod Rust closures over a per-mod xorshift64ModRng,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 callsmath.randomseed(42); mod B and mod C each drawmath.random(1000)twice. B's pairmust 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-luaunit tests pass,including the new one.
Environment
Tested on Linux/Fedora 45 inside a VMware Workstation guest (no GPU, no game files
needed).
leonida-luais one of the 9d3d12/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 on GitHub · 2026-12-02 12:25 UTC · original
Ran this natively on Windows 11 (MSVC, Rust 1.98.1), head
ba5121192merged into currentmain.Suite:
cargo test -p leonida-lua --lib --lockedran 41 passed. Withmain'ssandbox.rsand this branch'stests.rs,math_random_is_per_mod_not_shared_statefails withb="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.randomseeddrift from Lua 5.4, which the workspace builds (mluawithlua54). Three calls panic in Rust rather than raising a Lua error.I ran each call in its own mod through
rig, insidepcall, with a throwaway test (not pushed). The same probe ran againstmain's sandbox for the reference column.main(Lua 5.4's own)math.random(10)1, integer10.0, floattostring(math.random(10))"7""10.0"math.random(0)ModRng::range)math.random(-5)1.586e19math.random(5, 3)3.0(bounds swapped silently)math.random(10.0)1, integermath.random(math.mininteger, math.maxinteger)math.randomseed()Option::unwrap()onNonemath.randomseed(1.5)math.random(1, 2, 3)pcalldoes not stop these panics: in the test they unwind out ofrig. Two of them are ordinary Lua idioms:math.random(0), andmath.randomseed()with no argument to reseed from time.Smaller points:
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 byu64::MAX, sonext() == u64::MAXgives exactly1.0, outside[0, 1). That is rare but reachable;(next() >> 11) as f64 * 2^-53is the usual way.mainwithout 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'srandomseed(42)would pin the leak itself.One way to keep Lua 5.4's behaviour:
i64, so results are integers.10.0is accepted.lo > hi.random(0)return a full random integer.projectdoes.randomseed()with no argument take a fresh seed.GPUs tested: n/a (CPU-only tests).
AI-assisted: yes (Claude Code).
github-bot referenced this pull request2026-12-02 12:47:03 +00:00
@MoonEyes on GitHub · 2026-12-02 12:41 UTC · original
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:mainSHA it was merged onto;mainalone 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 on GitHub · 2026-12-02 15:19 UTC · original
RUN (in game) -- render-path gate run for PR #3115:
ba5121192mainSHA:acc350745(git merge --no-ff, clean merge;python -I scripts/check_no_game_data.pyPASS;cargo test -p leonida-lua --lib --locked45 passed, 0 failed)diagprofile (diagnostics,dlss,mimalloc), Series S profile, DLSS on, Frame Gen off, same restored save snapshotba5121192onacc350745)mainalone (acc350745)Both runs loaded cleanly into the world, stayed up past 300 s in-world with 0 device lost / 0 crashes / 0
ERRORlines, and closed cleanly. Rendered FPS matchesmain(26.9vs26.8fps).Verdict: PASS.
AI-assisted: yes (Antigravity).
@MoonEyes on GitHub · 2026-12-02 18:14 UTC · original
Verified on Linux (the crate is portable): the new test is red then green, but the new
math.random/math.randomseedlet a mod panic the host and change Lua 5.4 semantics.Red/green:
python -I scripts/red_green.py pr/3115 --base origin/main --no-fetch --work-dir <scratch>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:pcall(math.randomseed)sandbox.rs:287:53: called Option::unwrap() on a None value;pcalldoes not contain it, the test thread diespcall(math.random, 0)sandbox.rs:109:13: attempt to calculate the remainder with a divisor of zero(debug;% 0panics 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
d3d12/crates/leonida-lua/src/sandbox.rs:287(merged-tree line):args.into_iter().next().unwrap()panics onmath.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 ofunwrap.sandbox.rs:109(range):1 + self.next() % nwithn == 0divides by zero;math.random(0)(valid in 5.4, returns a full random integer) andmath.random(minint, maxint)(hi - lo + 1overflows to 0, and is an overflow panic in debug before that) both reach it. Negativenis cast withas u64and returns a huge value instead of an error.f64, somath.random(n)is a float (5.0),math.typesaysfloat, and values above 2^53 lose precision. Returni64for the 1- and 2-argument forms.random(m, n)withm > nswaps 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.unit()divides byu64::MAX, so it can return exactly1.0(the documented range is[0, 1)).(next() >> 11) as f64 * 2^-53is the usual fix.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
randomby Lua 5.4's rules (lmathlib.cmath_random/project), with integer results and error returns, and add tests for no-argrandomseed,random(0),random(5, 1)andmath.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
@MoonEyes on GitHub · 2026-12-02 18:21 UTC · original
RUN (in game, batch of seventeen render-path pull requests), each head merged with
git merge --no-ffonto main3c106eb2f, in one build: #311115b579756, #29485284c6eae, #26981f188c4f7, #294644bf554fe, #3001d924cbb65, #28320c861595a, #291558e8535cf, #2822d359a2f85, #2896c9c6b103d, #29838278ef1b9, #3115ba5121192, #2945d2c08c14f, #297574512d658, #295126da88e8e, #2800b6ebcedd4, #28937c7e99b48, #3113fa1460b6b(and #30970d7a451ab, 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.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 on GitHub · 2026-12-02 23:26 UTC · original
VERIFY-3115 — Windows nativo: pasa, y un hallazgo sobre lo que el test no asegura
ba5121192—sandbox.rs(+102),tests.rs(+21)ba5121192(on an oldermain: 41 tests here, 47 onmain81efe4566)Ran
What the change is:
math.random/math.randomseedare overridden per mod with a small xorshift64 (ModRng), because the shared C closures all read the onelua_StatePRNG — so one mod'srandomseedmoved 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:
Rc<RefCell<ModRng>>in astaticdoes 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.unit()return a constant (0.5) — the test still passes.That second one is the finding: the test pins isolation, not randomness. With
math.randomreturning 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: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
Written with an AI assistant.
@MoonEyes on GitHub · 2026-12-03 07:01 UTC · original
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 latestmaininto 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 on GitHub · 2026-12-03 10:25 UTC · original
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
ModRngnuevo y un test nuevo), así que probé a quedarme con las dos mitades. No funciona, y el compilador lo dice: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.rshay algo más que la unión no podía saber:mainya cambiónew_lua— ahora espub 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
ModRngnuevo»: es unModRngnuevo más unnew_luaque ya no existe con esa firma. La resolución correcta es mirar qué hizomainconnew_luay portar elModRngal mundo nuevo — y eso es leer, no pegar.No la he empujado: el worktree está borrado, el rebase abortado y
mainsigue limpio. Y lo dejo escrito porque el intento costó veinte minutos y el siguiente no tiene por qué repetirlo.@fiestorra on GitHub · 2026-12-03 10:26 UTC · original
Corrección a lo que escribí arriba, porque me equivoqué en un dato y prefiero decirlo yo
Dije que
mainhabía cambiadonew_luaapub fn new_lua() -> Result<(Lua, Guard)>. Es al revés: esa firma es la de esta PR, ymainsigue con la antigua:Lo que sí cambió
maindesde la base de la PR es el contenido de los dos ficheros, y no poco: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 reescribenew_luaymainha 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 delimiteren los dos ficheros) y lo segundo tiraría las 43 líneas y los 312 demain.La resolución, dicha en una frase para quien la haga: coger el
ModRngy la firma nueva de esta PR y aplicarlos encima de la versión demaindenew_lua— o sea, mirar qué hacen las dos versiones del cuerpo y quedarse con una que tenga lo demainy 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 on GitHub · 2026-12-03 10:26 UTC · original
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.
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 quemaincambió la forma de la función (elGuardpasó de dentro a fuera) y la PR cambió su contenido (elModRng) 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:
Y por eso «quedarse con los dos lados» no solo rompía la sintaxis: habría dejado dos
new_luay 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_luaconstruye 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 on GitHub · 2026-12-03 18:02 UTC · original
Thanks for the work on this. This pull request has a merge conflict with the current
mainand 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 latestmaininto 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
Pull request closed