Skip to content

Fix math.random polyfill and unseeded random seed generation - #254

Merged
levno-710 merged 4 commits into
prometheus-lua:masterfrom
ludicious-claw:fix/random-seed-and-math-random
Nov 2, 2026
Merged

levno-710 merged 4 commits into
prometheus-lua:masterfrom
ludicious-claw:fix/random-seed-and-math-random

Conversation

@ludicious-claw

Copy link
Copy Markdown
Contributor

Problem

  1. The math.random() polyfill with zero arguments returned a constant 1, so
    probabilistic checks like math.random() < 0.5 in pipeline steps never fired.
  2. On stock Lua 5.1 the OpenSSL-derived seed overflowed a signed 32-bit int in
    math.randomseed, giving srand(-2147483648) on every run. Unseeded
    obfuscations were byte-identical (10/10 runs).
  3. The io.popen handle was never closed, and empty/missing OpenSSL output produced
    seed 0, bypassing the os.time() fallback.

Changes

  • Fix the polyfill condition for zero-argument math.random().
  • Reduce the seed modulo 2147483647, close the popen handle, validate the output.
  • Make the fallback safe when io.popen, os.time or os.clock are unavailable (e.g. Luau).
  • Add regression tests in tests/harness/random-seed.lua (including the fallback path),
    annotated with -- @runtime lua51 luajit.

Testing

  • docker-test-runner.lua --suite=existing --iterations=10 (inside Docker, lua5.1 and luau, all presets): 3420 transformed passed / 0 failed, 57 baselines passed, 0 timeouts.
  • All tests/harness/*.lua pass on Lua 5.1 and LuaJIT 2.1.
  • Unseeded runs: 10/10 unique outputs on Lua 5.1, LuaJIT and Luau.
  • A fixed seed (Seed = 12345) stays deterministic.

Notes

  • Behavior change: the math.random() polyfill previously always returned 1,
    so math.random() < x branches in pipeline steps were never taken. They are now
    reachable, which changes the obfuscated output of affected steps/presets. No
    config or API changes. Happy to split this into a separate PR if you prefer.
  • The fallback seed (os.time + os.clock) is not cryptographically strong; it is
    only used when OpenSSL is unavailable.

@levno-710

levno-710 commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Thanks for the thorough fix and tests! Reproduced all three issues and confirmed the patch is correct on Lua 5.1 and LuaJIT. Merging after CI passes.

@levno-710
levno-710 merged commit de5607f into prometheus-lua:master Nov 2, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants