Skip to content

[mypyc] Fix librt.random ops treating -113 results as errors - #22420

Merged
JukkaL merged 1 commit into
python:masterfrom
Jahongir-Qurbonov:mypyc-librt-random-overlapping-error
Nov 9, 2026
Merged

JukkaL merged 1 commit into
python:masterfrom
Jahongir-Qurbonov:mypyc-librt-random-overlapping-error

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

Several librt.random primitives returning i64 were registered with ERR_MAGIC: Random.randint, Random.randrange(start, stop), and the module-level randint / randrange(start, stop). Their valid output range includes -113, which is the i64 error value, so a legitimate -113 result took the error path without checking PyErr_Occurred() and crashed.

from librt.random import Random, randint
from mypy_extensions import i64

def ri(r: Random, a: i64, b: i64) -> i64:
    return r.randint(a, b)

ri(Random(0), -113, -113)   # segfault
randint(-113, -113)         # segfault

Fix: use ERR_MAGIC_OVERLAPPING for these ops. The C implementations already set an exception on every error path. randrange(stop) only returns values in [0, stop) and random() only returns values in [0.0, 1.0), so both keep ERR_MAGIC.

I also checked the other librt primitives (strings, time, threading, vecs, base64). Each one either already uses ERR_MAGIC_OVERLAPPING or returns an object, None or bool, where a valid result can't equal the error value.

Random.randint, Random.randrange(start, stop) and the module-level
randint/randrange(start, stop) primitives used ERR_MAGIC, so a valid
result of -113 (the i64 error value) was treated as an error without
checking PyErr_Occurred(). This propagated a NULL exception and crashed.

Use ERR_MAGIC_OVERLAPPING for these ops. randrange(stop) can only return
non-negative values, so it keeps ERR_MAGIC.

@JukkaL JukkaL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix, looks good!

@JukkaL
JukkaL merged commit b83696e into python:master Nov 9, 2026
18 checks passed
@Jahongir-Qurbonov
Jahongir-Qurbonov deleted the mypyc-librt-random-overlapping-error branch November 14, 2026 22:05
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