Commit Graph
439 Commits
Author SHA1 Message Date
Jeong, YunWon 7aedaf919e Merge branch 'main' into copilot/fix-isalnum-function-behavior 2026-08-18 13:49:51 +09:00
Kwak Byoung Min 62f4c9895a Add StringIO newline tracking (#8539)
* Report observed StringIO newline types

Constraint: Match CPython StringIO newline reporting without changing configured newline translation.
Rejected: Separate newline-tracking representation | reuse the existing SeenNewline bitflags.
Confidence: high
Scope-risk: narrow
Directive: Keep observed newline state separate from the configured newline mode.
Tested: prek run --all-files; test_memoryio; cargo clippy -p rustpython-vm --lib -- -D warnings; workspace tests excluding the macOS C-API baseline SIGSEGV.
Not-tested: Full macOS workspace suite is blocked by the existing rustpython-capi SIGSEGV; the Linux suite is running.
Assisted-by: Codex:gpt-5.6-sol

* Preserve StringIO state boundaries

Reset observed newline state when StringIO is reinitialized and keep the property subject to closed-stream checks.

Constraint: Match CPython StringIO reinitialization and closed-stream behavior.
Rejected: Returning stale or cached newline state | violates StringIO lifecycle semantics.
Confidence: high
Scope-risk: narrow
Directive: Keep observed newline state tied to the current open StringIO contents.
Tested: cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher; cargo run --release -- extra_tests/snippets/stdlib_io_stringio.py; cargo run --release -- -m test test_memoryio; prek run --all-files; cargo clippy -p rustpython-vm --lib -- -D warnings.
Assisted-by: Codex:gpt-5.6-sol
2026-08-18 12:38:16 +09:00
Jeong, YunWon a78d0eb577 Fix crashes found hunting the last open fuzzing record (#8524)
* specialize: check the member descriptor's type before caching its slot offset

The LOAD_ATTR/STORE_ATTR specializations cached the slot offset of any member
descriptor found on the owner's type and then guarded the specialized
instruction on the type version alone, while descr_get()/descr_set() check on
every access that the instance belongs to the type the descriptor was defined
for. A descriptor taken from a wider class and bound to a narrower one read
past the instance's slot array once the cache warmed up:

    class Big:
        __slots__ = ("a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7")
    class Narrow:
        __slots__ = ("z",)
    Narrow.x = Big.__dict__["a7"]
    o = Narrow()
    for _ in range(1000):
        try: o.x
        except TypeError: pass
    # index out of bounds: the len is 1 but the index is 7 (object/core.rs)

A class with no slots at all reached the ext_ref().unwrap() on the same line.

Assisted-by: Claude

* socket: reserve recv()'s buffer fallibly

recv() and recvfrom() handed the caller's bufsize straight to
Vec::with_capacity, so an unreachable size aborted the process through
handle_alloc_error before any syscall was made:

    socket.socket().recv(2**62)
    # memory allocation of 4611686018427387904 bytes failed -> SIGABRT

try_reserve_exact reports MemoryError instead, which is what CPython raises.

Assisted-by: Claude

* types: count the __call__ and __get__ slot dispatches as recursion

Both wrappers re-enter Python without pushing a frame, so nothing counted the
nesting when the special method named the object it was looked up on:

    class C: pass
    c = C(); C.__call__ = c
    c()                                    # native stack overflow, SIGSEGV

    class D: pass
    d = D(); D.__get__ = d; D.x = d
    d.x                                    # the same, through descr_get

with_recursion around the two dispatches raises RecursionError instead, the
way Py_EnterRecursiveCall bounds a tp_call dispatch. It costs about 5% on a
__call__ dispatch and 3% on a __get__ dispatch through these wrappers.

Assisted-by: Claude

* typevar: show a ParamSpecArgs origin by its repr

ParamSpecArgs and ParamSpecKwargs fell back to a Rust `{:?}` of __origin__ when
it had no __name__. That walks the object graph natively through Debug for
PyInner, where no recursion guard sits, so a single repr() of a deeply nested
chain overflowed the native stack:

    a = object()
    for _ in range(30000):
        a = typing.ParamSpecArgs(a)
    repr(a)                                # SIGSEGV

The origin is formatted with its repr now, which is guarded, and a ParamSpec
origin is recognized by its type rather than by carrying a __name__.

Assisted-by: Claude

* Do not hold a lock across a call back into Python

Three places kept a lock while running code that can reach the same object, so
a callback that touched it wedged the process:

    _asyncio.future_add_to_awaited_by(fut, waiter)   # waiter.__hash__ adds again
    select.select(elements, [], [], 0)               # fileno() clears `elements`
    select.poll().poll(1000)                         # SIGALRM handler registers

The future's awaited-by field is read and written under its lock but the set is
built outside it, the list extraction re-reads the list on each step the way
map_iterable_object() does, and poll() waits on a copy of its descriptors. All
three ran forever before and now finish the way they do on CPython.

Assisted-by: Claude

* Validate memoryview.cast() arguments and export negative strides correctly

cast() accepted any struct format and any shape element. A zero-size
format ('0s') and a 0 in the shape both reached a division by zero;
cast() now takes only a native single character format, optionally
'@'-prefixed, and shape elements that are ints greater than zero.

A view with a negative stride starts at its last item, so the bytes it
exported began there and its own offsets walked off the front of them.
Such a view now exports the whole underlying buffer with `start` folded
into the descriptor's offsets, and zip_eq() hands over a whole run only
when both sides are contiguous in the last dimension.

Assisted-by: Claude
Assisted-by: Codex:GPT-5

* Charge native recursion to the stack, not to the frame limit

with_recursion() checked the limit sys.setrecursionlimit() sets and
incremented the same counter that pushing a frame does, so a guard on a
native dispatch spent what Python code had left to call with, and did so
where sys._getframe() cannot see it: test.support.get_recursion_available()
reported frames that were no longer there. Py_EnterRecursiveCall bounds
the native stack instead, which is a separate budget, and the C stack
check with_recursion already performs is that bound.

The snippets pinning the guarded paths nest deep enough to reach the
stack rather than the frame limit.

Assisted-by: Claude

* Report a size that cannot be allocated instead of aborting on it

A size taken from Python went straight into an infallible allocation in
several places, so the process aborted through handle_alloc_error before
any exception could be raised:

- str/bytes/bytearray center(), ljust(), rjust() and zfill() reserved
  the padded result for the caller's width
- expandtabs() built its runs of spaces from a tabsize of any width;
  the argument is a C int, and a wider one does not fit
- Buffered{Reader,Writer,Random} allocated buffer_size, and read(),
  read1() and FileIO.read() their read size
- bytes(n) and bytearray(n) allocated n
- pbkdf2_hmac() allocated the derived key length, which is a C int

Each of these now reports MemoryError, or OverflowError where the
argument does not fit the type it is declared with.

new_zeroed_bytes() leaves the zeroing to the allocator, so a large
request costs the pages that are written to rather than all of them.

Assisted-by: Claude

* marshal: answer allow_code where a code object is written or read

allow_code was answered by walking the whole result a second time, with
no depth counter and no record of what it had already seen, so a value
that referred back to itself or nested deeply enough ran off the native
stack. w_object() and r_object() answer it where the code object is,
inside the walk that already bounds its depth and resolves references.

A container length is read the way r_long() reads one: it is signed, so
a length with the top bit set is out of range rather than four billion
items to reserve room for.

load() no longer holds a borrow of the buffer read() returned across the
seek() it makes afterwards.

Assisted-by: Claude

* Do not lock an object while running code that can reach it

Several places held a lock or a borrow of an object across a call back
into Python, so a callback that touched the same object waited on a lock
its own caller was holding:

- memoryview slice assignment read a source overlapping the destination,
  and __setitem__ converted the value while holding the write borrow
- BytesIO.readinto() read into a buffer viewing the same BytesIO
- array.__setitem__ converted the value under the array's write lock,
  and mmap.write() read a source viewing the same map
- bytearray.join() and bytearray.__mod__ drove Python with the
  bytearray borrowed
- array and bytearray answered "is this resizable" after taking the
  write lock, though an export is exactly a borrow someone else holds

A TextIOWrapper cookie now has to name a position inside what was
decoded in characters as well as in bytes; only the byte offset was
checked, and the character count is what read() and tell() index with.

Assisted-by: Claude
Assisted-by: Codex:GPT-5

* Stop asserting a pbkdf2 message that depends on the width of a C long

The snippet asserted "key length is too great.", which pbkdf2_hmac()
only reaches once the length has been converted; where a C long is
narrower than the length asked for, the conversion fails first and says
so instead. Both are OverflowError, which is what the case is about.

test_support.test_get_recursion_depth passes now that a native recursion
guard no longer spends frames get_recursion_depth() cannot see.

Assisted-by: Claude

* Publish and read the same pointer for a thread's top frame

set_current_frame() casts the `Py<FrameObject>` it publishes straight to
`*mut FrameObject`, so ThreadSlot::top_frame holds the object's base.
sys._current_frames() read it back through Py::from_payload_ptr(), which
subtracts the payload offset from what it is given. The reference it took
therefore incremented, and later decremented, a word 48 bytes ahead of
the frame -- inside the object allocated before it, whose OnceLock state
word sits exactly there for two frames adjacent in the size class. The
neighbour then read an initialized-looking cold pointer that had never
been written and locked whatever the uninitialized word addressed, so
the thread that owned it crashed rather than the one that read.

The slot now holds `*mut Py<FrameObject>`, which is what both sides mean.

A thread parked in a call has no FrameObject for its topmost frame, so
top_frame is null there and the reader takes the materialize path
instead: test_sys.test_current_frames never reaches the branch. The
snippet takes _current_frames() against threads that are running.

Assisted-by: Claude
Assisted-by: Codex:GPT-5

* Decide stop-the-world parking under the thread registry lock

do_suspend() published SUSPENDED first and only then re-read `requested`,
restoring itself to ATTACHED if the stop had ended in the meantime. That
made a thread the second writer able to leave SUSPENDED, so a stop whose
completion check had already observed the thread parked could be undone
behind the requester's back:

  worker    CAS ATTACHED -> SUSPENDED
  requester all_non_requester_suspended() -> true, world_stopped = true
  requester start_the_world(): requested = false, then walks the registry
  worker    reads requested == false, stores ATTACHED

With the store landing inside that walk the debug assertion in
start_the_world fires; with the walk already past the slot, a following
stop force-parks the thread DETACHED -> SUSPENDED, counts it as stopped,
and the store then puts it back to ATTACHED with the world declared
stopped and the thread running bytecode.

`requested` is set in init_thread_countdown() and cleared in
start_the_world() with the registry held, and start_the_world() keeps
holding it while releasing every SUSPENDED thread. Taking the registry
around the check and the transition therefore makes the two orders the
only ones possible: park before that release pass and be woken by it, or
find the request already withdrawn and stay ATTACHED. The requester is
left as the only writer that takes a thread out of SUSPENDED, and the
self-restore is gone.

suspend_if_needed() takes the VirtualMachine to reach the registry.

Assisted-by: Claude
Assisted-by: Codex:GPT-5

* Keep an atexit callback alive while it is being compared

atexit.unregister() releases the callback list around each __eq__ call and
identified the entry it had compared by the address of its Box. __eq__ can
call atexit._clear(), which drops that Box, and atexit.register(), whose
new Box lands on the freed allocation; the identity search then matched
the freshly registered callback and removed it.

  atexit.register(a); atexit.register(b); atexit.register(c)
  # __eq__ runs _clear() then register(d), returns True
  atexit.unregister(probe)

left no callbacks registered where CPython leaves d.

Entries are Arc-shared now, so unregister() holds the one it is comparing
and matches it with Arc::ptr_eq: an address cannot be reused while the
comparison that named it is still running.

Assisted-by: Claude

* Hold atexit entries in PyRc rather than Arc

PyObjectRef is Send and Sync only under the threading feature, so an Arc
over a callback entry trips clippy::arc_with_non_send_sync in builds
without it, such as the wasm package. PyRc is Arc there and Rc otherwise.

Assisted-by: Claude

* Do not hold a buffer's storage while waiting for a peer

FileIO.readinto() and socket.recv_into()/recvfrom_into() took the target
buffer's write borrow and kept it for the whole call, including the wait
for data a pipe, socket or terminal may never deliver. What CPython holds
across that wait is the export, which only forbids resizing; the borrow is
a lock every other thread touching the same object waits on, so

    threading.Thread(target=lambda: sock.recv_into(buf)).start()
    len(buf)

did not answer until the peer sent. A thread parked on that lock is
ATTACHED and never reaches a safepoint, so gc.collect() in a third thread
waited for the peer as well: one incidental read of the buffer stopped the
world from being stopped at all.

The wait now runs against storage of its own and the bytes are copied over
once they arrive, with the export held throughout so the target still
cannot be resized meanwhile. A seekable file answers from itself rather
than from a peer, so FileIO.readinto() writes into the target directly
there and the buffered read path is unchanged.

Assisted-by: Claude

* Do not hold a buffer's storage while waiting to hand it over

socket.send()/sendall()/sendto()/sendmsg() and FileIO.write() kept the
source buffer's read borrow for the whole call, including the wait for a
peer that may never make room. That borrow is a lock every other thread
writing to the same object waits on, so

    threading.Thread(target=lambda: sock.sendall(buf)).start()
    buf[0] = 1

did not return until the peer read; and a thread parked there is ATTACHED
and never reaches a safepoint, so gc.collect() in a third thread waited
for the peer too -- the same wedge readinto() had on the receiving side.

ArgBytesLike::borrow_buf_unlocked() answers with bytes that survive the
borrow being dropped. An immutable object hands out a plain reference and
locks nothing, so those are sent where they lie and bytes and memoryviews
over them cost nothing; only bytes reached through a lock are copied out
first. The export is held throughout either way, so the source still
cannot be resized while it is being sent.

The regression snippet covers both directions now and is renamed for it.

Assisted-by: Claude
Assisted-by: Codex:GPT-5

* Check select()'s descriptor limit while the sequence is walked

seq2set() collected the whole sequence and compared the result's length
against FD_SETSIZE afterwards. Selectable::try_from_object() calls
fileno(), which runs Python and can append to the list being walked, and
the walk re-reads the list on every step, so the collection had no end to
reach and the comparison was never made. seq2set in Modules/selectmodule.c
checks the count per element instead.

stdlib_select.py gains a fileno() that appends to its own list, and
releases its sockets with close() rather than by dropping the name.

Assisted-by: Claude

* Bound native recursion where the C stack cannot be measured

check_c_stack_overflow() answers no unconditionally under miri and on
musl, where the stack pointer is not read. Since 9c9905aff that check is
all with_recursion() does, so every guard placed on native recursion --
__call__ and __get__ dispatch among them -- was a no-op on those targets
and the nesting ran until the stack ran out.

with_recursion() now counts its own depth on those targets and refuses
past NATIVE_RECURSION_LIMIT_UNMEASURED. The count is separate from the
frame limit sys.setrecursionlimit() sets, and compiles away where the
stack pointer can be read.

Assisted-by: Claude

* Report the failure to allocate pbkdf2's key and Take.readinto's scratch

Both buffers are sized from an argument -- pbkdf2_hmac's dklen accepts up
to i32::MAX, and readinto's from the length of the destination -- and were
built with vec![0u8; n], which aborts the process on allocation failure.
new_zeroed_bytes() raises MemoryError instead.

Assisted-by: Claude

* Read the frozen-code tuple length as a signed length

The '(' branches in read_marshal_str_vec() and read_marshal_const_tuple()
took the length with read_u32() as usize, so a value with the top bit set
read as four billion items rather than as out of range. read_len() is what
every other length in this file goes through, and it reinterprets as i32.

Both readers serve deserialize_code(), which reads only the frozen modules
baked in at build time, so this changes no reachable behavior;
marshal.loads() already went through read_len().

Assisted-by: Claude

* Make the snippets from the fuzzer sweep assert what they check

builtin_str.py expanded a tab to 2**31-1 columns, allocating 2 GiB to
observe that the width is accepted; a string with no tab observes the same
acceptance without laying anything out.

stdlib_array.py caught the refusal of frombytes() on its own exported
buffer and passed silently when nothing was raised. stdlib_hashlib.py
used a bare `assert False` as its failure branch. Both now say so through
the same shapes the other snippets use.

stdlib_socket.py also accepts OverflowError from recv() with a size that
does not fit the platform's C int.

stdlib_threading_current_frames.py indexed the frame chain for "f123"
without first asserting it is there.

Assisted-by: Claude

* Ask for a marshal container's room instead of assuming it

A flagged tuple or list is published in the reference table before its
children are read, and the placeholder was built with vec![none; len].
The length is the input's to choose and read_len() lets it reach
i32::MAX, so marshal.loads(b"\xa8\xff\xff\xff\x7f") -- five bytes -- asks
for 17 GB of element slots and aborts the process where the allocator
cannot serve it. r_object() allocates the container up front too, but
PyTuple_New() reports what it cannot get.

The elements are now reserved with try_reserve_exact() and a refusal is
raised as MemoryError through the decoder's pending-error channel.
PyTuple::new_marshal_placeholder() held nothing but that allocation and
is gone; the caller builds the elements and uses new_ref().

Assisted-by: Claude

* Compare the blocking-buffer snippet against something

measure() asserted len(buf) == len(buf), which holds whatever the length
is; it now takes the length the caller expects. The pipe case compared
the drained total against the whole source, while an unbuffered write()
reports only what it transferred and a signal can cut that short; it now
compares against what write() returned.

Assisted-by: Claude

* Refuse array.frombytes() a source whose items are not bytes

frombytes() reads its argument as bytes, but accepted any contiguous
buffer, so array("i").frombytes(memoryview(array("d", [1.0]))) appended a
double's bytes read as ints instead of raising. array_array_frombytes_impl
requires an itemsize of 1; ArgBytesLike now reports the itemsize so the
same check can be made here.

The BufferError that a resize meets while the array is exported also names
the array rather than repeating bytearray's wording.

stdlib_array.py's frombytes-of-itself case used typecode "i", where the
new check answers before the resize guard is reached; it uses "b" so the
guard is what refuses, and asserts the wider case separately.

Assisted-by: Claude

* Tell apart the ways marshal data can be bad

A type byte no reader knows, a back reference that names nothing, and
TYPE_NULL all came out as a bare "bad marshal data" ValueError. r_object()
answers the first two with "bad marshal data (unknown type code)" and
"bad marshal data (invalid reference)", and read_object() answers the
third with a TypeError, "NULL object in marshal data for object", since
TYPE_NULL stands for no object rather than for a value.

MarshalError gains the three cases and deserialize_value() maps them.
The container-specific wording r_object() uses for a NULL read inside a
tuple or list is not reproduced; the exception type is.

Assisted-by: Claude

* Hash the collector's tables by address rather than by SipHash

A collection keys three sets and two maps by object address, and it visits
every tracked object and every edge between them, so the hashing is a
per-edge cost. Those tables used the default RandomState, whose SipHash
buys resistance against a caller choosing colliding keys -- and nothing
chooses these keys: they are addresses this process handed out into tables
that live and die inside one collection. A profile of gc.collect() over a
423k-object heap spent 45% of its samples in SipHash.

They now hash with a splitmix64 finalizer. The shifts matter: a table
picks its bucket from the low bits and an address arrives with those bits
zeroed by alignment, so a plain multiply leaves every object in a handful
of buckets and is slower than SipHash was.

The reachability walk also copied each object's referent vector out of the
map it was cached in, a second pass over every edge; it reads them in
place, and reference subtraction hands its vector to the map instead of
cloning it.

Measured over 423k live objects: 0.93s to 0.15s. Over 843k dead ones:
3.00s to 0.79s. extra_tests/snippets/stdlib_threading_gc_import.py, whose
collector thread calls gc.collect() in a loop, ran anywhere from 2.7s to
28s and now runs in 3.1-3.5s: a collection that takes longer leaves more
garbage for the next one to walk, so the cost fed back on itself.

Assisted-by: Claude
Assisted-by: Codex:GPT-5

* Keep the collection's candidates and their counts in one table

A collection built a set of candidates and, beside it, a map from the same
addresses to their reference counts. Both were probed for every edge in
the heap -- membership from the set, the count from the map -- so each
edge paid to hash the same address twice, and each candidate paid to be
inserted twice. The map alone answers both questions.

The candidates also keep a walkable order now, which the reference
subtraction pass needs since it writes the counts while reading the
candidates, and which the unreachable set is built from instead of a
set difference.

Over the 423k-object heap measured in the previous commit: 0.15s to
0.13s live, and 0.79s to 0.49s dead.

Assisted-by: Claude
Assisted-by: Codex:GPT-5

* gc: collect referents into one buffer instead of a vector per object

Step 3 allocated a `Vec` for every tracked object to hold its referents
and kept them all in a map until step 4 read them back. The referents now
go into a single growing buffer, with the map holding each object's range
into it.

Adds `PyObject::gc_extend_referent_ptrs`, which appends to a caller's
buffer; `gc_get_referent_ptrs` calls it with a fresh one.

Assisted-by: Claude

* memoryview and struct: match the checks and errors of the reference

memoryview:
- `cast()` accepted a source and destination that are both item types,
  which reinterprets the items rather than re-dividing the bytes; one side
  now has to be a byte format.
- A cast to `shape=()` returned without checking that the buffer holds
  exactly the one item that shape describes.
- `hash()` hashes the bytes, so it now raises ValueError for a view whose
  items are not bytes, rather than returning a hash that disagrees with the
  value the view compares equal to.
- `tobytes()` takes the `order` argument, with 'F' walking a
  multidimensional view down its columns; `BufferDescriptor` gained
  `for_each_segment_fortran` for that walk.

struct:
- A value the format has no room for reported "argument out of range"
  instead of naming the format and its range. The format character is now
  passed to the packing functions to report it.
- `Struct.__new__` no longer reads the format; `__init__` does, so
  `__init__` can be called again and a subclass can pass the format up.
  Methods raise RuntimeError until it has run, and `Struct` is a base type.

Removes the expectedFailure from test_Struct_reinitialization and
test_struct_subclass_instantiation.

Assisted-by: Claude
Assisted-by: Codex:GPT-5

* io: decide the readinto path by file type, not by seekability

FileIO.readinto wrote straight into the caller's buffer, holding its write
borrow, when the fd was seekable; otherwise it read aside into scratch and
copied. Seekability stood in for "this read answers without waiting on a
peer", which a pipe on Windows breaks: lseek on one succeeds, so the pipe
took the borrow-holding path and every other thread touching that bytearray
waited for the peer.

host_io::reads_without_waiting answers it directly -- seekability elsewhere,
GetFileType() == FILE_TYPE_DISK on Windows.

The regression snippet times each operation separately, so a failure names
the one that waited; it asserts the transfer is still in flight before
checking the export; and the socket case fills the connection until it
refuses rather than assuming a size that outruns it, which SO_SNDBUF on an
already-connected pair does not settle.

Assisted-by: Claude
2026-08-17 00:33:27 +09:00
Jeong, YunWon c603eb7c9a Implement PEP 688 and rework the buffer protocol around managed exports (#8523)
* Implement PEP 688 __buffer__ and __release_buffer__

A Python class could not export a buffer: the slot machinery had no
bf_getbuffer or bf_releasebuffer, and every consumer acquired buffers as
PyBUF_FULL_RO through a module of PyBUF_* constants.

Add both slots. PyBuffer::release now runs a Python __release_buffer__
before the exporter's own release, once per acquisition, which PyBuffer
tracks with an `acquired` flag that clones do not inherit. An export made
by a Python __buffer__ is held by a _buffer_wrapper payload that counts its
exports and drops the returned memoryview with the last one, and the view
handed to __release_buffer__ is a _buffer_window that owns no export, so
releasing it inside the hook is inert instead of re-entering it.

Replace the PyBUF_* constants with a BufferFlags bitflags type whose
composite requests are supersets of the simpler ones, so `contains` answers
the REQ_* questions, and pass the request to PyBuffer::from_object. Each
consumer now asks for what its counterpart asks for: y* arguments for
SIMPLE, w* for WRITABLE, BytesIO.write for CONTIG_RO, bytes(), bytearray()
and memoryview() for FULL_RO. memoryview checks the request in
memory_getbuf, and array.array and mmap.mmap expose __release_buffer__.

Test buffer support with PyObject::check_buffer (PyObject_CheckBuffer)
instead of attempting an acquisition, so an exception raised by __buffer__
is no longer reported as the object not being bytes-like, and a __buffer__
with side effects runs once. PyBytesInner becomes a y* conversion as a
result: bytes and bytearray methods no longer accept iterables of ints, and
find, index, count and __contains__ take the arguments
parse_args_finds_byte and bytes_contains describe.

A view exports its start offset in the descriptor rather than in its
window, which fixes a panic when collecting from a negative-stride view.

BytesIO.write rechecks closed after acquiring its buffer, which __buffer__
can close in between.

Assisted-by: Claude Code:claude-opus-5

* Rework the buffer protocol around managed exports and view offsets

Give `PyBuffer` the `_PyManagedBufferObject` shape: one `bf_getbuffer`
acquisition is shared by every handle taken from it, cloning takes another
share instead of re-acquiring, and the exporter's release runs once when the
last share goes away. Remove `retain`, the unsafe `drop_without_release`, the
three `impl Drop`s and the `ManuallyDrop` that stood in for this. Add
`abort_acquisition` so a failed request does not run `bf_releasebuffer`.

Move the view start into `BufferDescriptor::offset`, the `Py_buffer.buf`
analogue, and drop the separate `start` fields on `PyMemoryView` and
`PyBufferWrapper`. Slicing goes through `SaturatedSlice::adjust_indices_start`,
which reproduces `PySlice_AdjustIndices` and keeps the adjusted start.

Fix `zip_eq` to take its contiguous fast path only when both last dimensions
are contiguous, and make `for_each_segment` and `zip_eq` handle zero-length and
zero-dimensional views.

Add `BufferDescriptor::projected` so a request without `PyBUF_ND`,
`PyBUF_STRIDES` or `PyBUF_FORMAT` receives a correspondingly reduced
descriptor, and reject a request without `PyBUF_INDIRECT` against an exporter
that has suboffsets.

Copy the source first in `memoryview` slice assignment when both sides reach
the same root exporter.

Hold the export across the resize in `bytearray.extend`, take `y*` in
`marshal.loads`, stop probing the buffer protocol in `FsPath`, rewrite `ord`
over the concrete string types, fold `array`'s buffer slot into one
`slot_as_buffer`, take `w*`/`y*` in `_overlapped`, and thread the new `offset`
field through the `_ctypes` descriptors.

Assisted-by: Claude

* Re-check a memoryview after a conversion and tighten cast and release

`pack_single` and `unpack_single` addressed the buffer with a position taken
before `__index__` ran, so releasing the view from that conversion read or wrote
outside the exporter's storage, panicking when it had also shrunk. Check the
released flag again once the conversion is done, as `CHECK_RELEASED_AGAIN` does.

Reject a cast to a format that is not a single native format character with an
optional `@` in front of it. An empty format reached a division by its item size
of zero. get_native_fmtchar

Report a second `__release_buffer__` on the same view as a `ValueError` rather
than accepting it, and check that the view belongs to the object first; the
silent case is a view that exports nothing. wrap_releasebuffer

Compare against another memoryview by reading its view where it lies instead of
acquiring a buffer from it, so the restricted view handed to
`__release_buffer__` compares equal rather than unequal in one direction only.
memory_richcompare

Name the type in the unraisable an exception from `__release_buffer__` reports,
as `releasebuffer_call_python` does, instead of reporting the exporter object.

Assisted-by: Claude

* Re-check the destination of a memoryview slice assignment

Acquiring the source runs `__buffer__`, which can release the destination view,
so check the released flag again once the source is in hand and before the
structures are compared, as `copy_single` does.

Build the sliced destination as a view that counts as no export, the way a
`Py_buffer dest = *view` copy does. Holding one kept the exporter unresizable
for the length of the assignment, so a source that released the view and then
resized the exporter met a `BufferError` instead of the assignment reporting the
released view.

Assisted-by: Claude

* Answer the memoryview contiguity getsets with the layout

`f_contiguous` reported the row-major answer for one dimension and False
for any more, so a view laid out both ways, such as one of shape (1, 8),
reported False while `check_buffer_request` accepted a `F_CONTIGUOUS`
request on it. `contiguous` answered row-major order alone.

Move the Fortran-order test from `PyMemoryView` to `BufferDescriptor`,
next to the row-major one it differs from only in iteration order, and
answer all three getsets with it.

Assisted-by: Claude
2026-08-16 21:32:29 +09:00
Jeong, YunWon 9e4c5708c6 str, bytes: answer equality with equality rather than with an ordering (#8531)
PyStr's comparison, PyBytesInner's, and the specialized CompareOpStr
instruction all answered == and != by taking Ord::cmp of the two buffers
and asking whether the result was Equal. An ordering has to read the
bytes: it memcmps the common prefix even where the lengths already settle
the question. CompareOpStr bypasses the Comparable slot, so it had also
lost the identity shortcut that slot takes, and a string compared with
itself was read end to end.

Add PyComparisonOp::eval_eq, which settles Eq and Ne from an equality test
and leaves an ordering operator to the caller, and answer through it in the
three places: slice equality checks the length first, and CompareOpStr
answers an object compared with itself the way the slot it specializes does.

n=1,000,000, per comparison:

                                      before      after
    s == s (the very same object)    23.21us     0.16us
    s == a string one shorter        24.63us     0.17us
    b == bytes one shorter           25.28us     0.20us
    ba == bytearray one shorter      27.68us     0.23us
    s == an equal, distinct string   23.78us    24.50us
    s <  an equal string             29.87us    25.07us

Assisted-by: Claude
2026-08-15 18:23:05 +09:00
Jeong, YunWon a97e8f0746 str: take search bounds through the character index (#8530)
* str: count an empty needle in characters

str.count with an empty needle ran find_iter over the range's bytes, which
reports one position per encoded byte boundary rather than one per
character: '가나다'.count('') answered 10 instead of 4. Count the range's
code points instead; bytes.count keeps the byte-position answer.

Assisted-by: Claude

* str: take search bounds through the character index

find, rfind, index, rindex, count, startswith and endswith resolved their
start/stop bounds with AnyStr::get_chars, which walks the payload to both
bounds, and find reported its hit by counting the code points in front of
it -- so a sweep over a subject's own indices walked it once per call.
Resolve the bounds with StrData::char_range_to_bytes instead, which is the
converter the subscript and slice paths already use, and map the hit back
with Wtf8Index::char_index_at_byte, added here as the table's inverse: a
bracketed search over the groups, then at most an entry's worth of steps.

The payload alone does not say whether it is ASCII, so get_chars walked
there too; that path is now off it as well.

n=8000, sweeping the bound over the subject, best of 3, interleaved:

                     '가나다라'*n/4            'abcd'*n/4
    find          18.00ms ->  0.15ms      3.48ms -> 0.14ms
    startswith    16.75ms ->  0.12ms
    count         22.78ms ->  4.02ms

count stays linear in the range it is given, as it is in CPython.

Assisted-by: Claude
2026-08-15 17:23:37 +09:00
Jeong, YunWon ef51c5c164 str: count a stepped slice's characters with a ceiling division (#8525)
`do_stepped_slice` and `do_stepped_slice_reverse` took the character count of
a non-ASCII result as `(range.len() / step) + 1`, which overshoots by one
whenever the span is an exact multiple of the step: `"aéc"[::3]` is one
character and reported two, `"가나다라"[::2]` two and reported three. ASCII
subjects were unaffected, since that arm collects into an `AsciiString` whose
length comes from the data.

The count is stored as the string's character length, so the result then
claimed a character its buffer does not hold, and `reversed()` on it indexed
past the end and panicked:

    s = "".join(["a", "é", "c"])
    list(reversed(s[::3]))      # index out of bounds: the len is 1 but the index is 1

Use `div_ceil`, which is the number of elements the underlying range yields.

A differential over 44331 subscript and slice shapes -- every combination of
start, stop and step over strings straddling the ASCII split, the surrogate
range and the astral plane -- now matches CPython 3.14 exactly, where it
differed on 3100 lines before.

Assisted-by: Claude
2026-08-14 23:32:36 +09:00
Jeong, YunWon 259ce8ce66 Fix the itertools.tee leak and race, the contextvars and generator races, _asyncio's InvalidStateError lookup, and _imp's frozen data (#8518)
* _imp: read get_frozen_object's data as a whole marshal value

The data argument went through deserialize_code(), which reads a code body
without the type byte in front of it, so nothing marshal.dumps() produces was
accepted. Read it with marshal.loads() and require a code object back.

Assisted-by: Claude

* _imp: bind find_frozen's arguments with FromArgs

The arity check was done by hand on a FuncArgs. Take the arguments through a
FromArgs struct instead, which makes withdata keyword-only, and fill in the
data it asks for: the frozen encoding is not marshal, so the code is
re-serialized into what get_frozen_object() reads back.

Assisted-by: Claude

* itertools: give tee's shared buffer a Python type

The buffer was a PyRc<PyItertoolsTeeData>, which is not a Python object, so the
collector could not walk into it and any cycle running through a tee was
uncollectable. Make it the _tee_dataobject type with a traverse, held by
PyRef, and split the rest along the same lines: tee() is a function, _tee is
the iterator type it builds, and _tee takes a single iterable rather than
returning a tuple from __new__. _tee is weak-referenceable, tee() rejects a
negative n with ValueError and reserves its tuple fallibly.

test_itertools.test_tee passes now; its expectedFailure marker is removed.

Assisted-by: Claude

* contextvars: hold the shared context state under locks

The variable map was a RefCell, the enter flag, the context index, the token's
used flag and the variable hash were Cells, and each carried an unsafe impl
Sync. A Context or ContextVar shared between threads overlapped their borrows
and panicked. The map and the per-variable cache are now PyMutex, the flags and
the index are atomics, entering a context is a compare_exchange, and the three
unsafe impl Sync are gone.

The cache also stopped being read through AtomicCell::as_ptr, which raced a
concurrent store on a value holding a PyObjectRef.

Values displaced from the map or the cache are dropped after the lock is
released: __del__ can come straight back into the same context, and the locks
are not reentrant.

Assisted-by: Claude

* generator: read the frame state under the running claim

send(), send_none(), throw() and close() read `closed` and `frame.lasti()`
before `running` was compare_exchanged, so the frame they went on to resume
could be one another thread had already advanced. A resume that decided from
`lasti() == 0` that the generator had not started pushes no value onto the
value stack, and the code after the yield pops one, which underflows the stack.

The compare_exchange now hands back a guard, taken before those reads and
released after maybe_close(), so the generator is retired while it is still
claimed.

Assisted-by: Claude

* itertools: claim a tee's position and its buffer as one step

`_tee::next` read `index` and moved it on afterwards, and
`_tee_dataobject::get_item` released `running` before the value it fetched
from the source was cached.

Two callers on one `_tee` then read the same index, hand out the same value
twice and advance past a value that was never cached, which leaves `index`
past `values.len()` and indexes the buffer out of bounds. Two callers at the
same index on separate tees each fetch a value from the source, and one of the
two is dropped without reaching a caller.

Both claims now cover the read and the update.

Assisted-by: Claude

* _asyncio: require InvalidStateError to be a type

new_invalid_state_error() called whatever `asyncio.exceptions.InvalidStateError`
names and unwrapped the downcast of the result, so a future asked for a result
it does not have panicked once that attribute was rebound to something that is
not an exception:

    asyncio.InvalidStateError = lambda *args: 42
    _asyncio.Future(loop=object()).result()

The type is looked up the way get_cancelled_error_type() looks its own up, and
raised with new_exception_msg; a lookup that does not produce an exception type
falls back to RuntimeError, as the other arms already did.

Assisted-by: Claude
2026-08-14 16:05:30 +09:00
Jeong, YunWon 7108ff0f69 marshal: round-trip code constants through the runtime bag (#8516)
* Keep abnormal marshal loop test aligned with CPython

Assisted-by: OpenAI Codex:gpt-5.5

* marshal: retain runtime code constants while loading

Decode code fields through the runtime MarshalBag so co_consts values that do not fit the compiler constant enum remain available to VM code wrappers while the compiler table receives shape placeholders.

Assisted-by: OpenAI Codex:GPT-5.4

* marshal: write and read co_consts through the runtime bag

serialize_code gains a serialize_code_with variant that writes each
co_consts entry through a caller-supplied writer; serialize_code keeps
the BorrowedConstant writer as its default.  The VM writer passes its own
write_object_depth, so a code constant that Literal holds but
BorrowedConstant cannot describe reaches the stream instead of panicking
in borrow_obj_constant, and a constant shared with the enclosing object
takes an entry in the writer's reference table.

PyMarshalBag implements constant_ref_from_value, bytes_from_value,
str_from_value and tuple_elements_from_value, which
deserialize_code_value_inner requires to decode code fields through the
runtime bag.

Assisted-by: Claude
2026-08-14 03:30:51 +09:00
Jeong, YunWon d5d19e0611 Fix 33 reproduced fuzzing and static-review defects (#8514)
* mmap: guard move() against dest/src past the mapping size

An offset larger than the mapping made `size - dest` underflow, producing
an out-of-range slice index panic. Check the high side first, as write() does.

Assisted-by: Claude

* exceptions: keep ImportError name/path/name_from out of an empty instance dict

ImportError.__reduce__ unwrapped get_arg(0), which is None when the exception
was constructed with no positional argument, aborting on pickle.dumps(ImportError()).
Fall back to the full args tuple there, and expose name/path/name_from as class
attributes defaulting to None so a bare ImportError() reduces to (cls, ()).

Assisted-by: Claude

* asyncio: stop unwrapping the _current_tasks downcast in current_task()

_asyncio._current_tasks is a reassignable module attribute; the three sibling
functions already degrade gracefully when it is not a dict, current_task() did not.

Assisted-by: Claude

* asyncio: raise TypeError when FutureIter.throw()'s exception class returns a non-exception

exc_type.call() goes through a Python-controlled __new__, so its result can be
any object; the downcast was unwrapped. Report it as a TypeError instead.

Assisted-by: Claude

* sequence: use a fallible reservation for sequence repetition

The guard only rejects a repeat whose per-element size crosses MAX_MEMORY_SIZE,
so (1,) * (10**12) still reached Vec::with_capacity and aborted in the allocator.
Reserve fallibly and surface a MemoryError.

Assisted-by: Claude

* collections: reject an oversized deque repetition with MemoryError

deque * sys.maxsize reached the allocator and aborted with a capacity overflow.
Apply the MAX_MEMORY_SIZE guard the other sequences already carry.

Assisted-by: Claude

* itertools: raise OverflowError for an out-of-range r argument

combinations/combinations_with_replacement/permutations narrowed r with
to_usize().unwrap(), so r=2**64 panicked instead of raising.

Assisted-by: Claude

* math: stream the generic sumprod path instead of collecting both iterables

The big-int path collected each argument into a Vec before multiplying, so an
unbounded iterable exhausted memory. Advance both iterators in lockstep and
accumulate, reporting a length mismatch when only one is exhausted.

Assisted-by: Claude

* _imp: raise TypeError for a second positional argument to find_frozen

withdata is keyword-only and unimplemented; passing it positionally hit an
unimplemented!() and aborted.

Assisted-by: Claude

* _typing: check _idfunc arity before indexing args

_typing._idfunc() with no argument indexed args[0] out of bounds.

Assisted-by: Claude

* exceptions: require a sequence for the ExceptionGroup excs argument

The argument was collected before being validated, so an unbounded iterable
such as itertools.count() exhausted memory. Reject a non-sequence up front.

Assisted-by: Claude

* mmap: treat an inverted find/rfind range as empty

find(b"x", 5, 2) built a slice whose start exceeded its end and panicked.

Assisted-by: Claude

* collections: give deque and defaultdict a GC traverse

Neither type opted into traversal, so a reference cycle through a deque or a
defaultdict was never collected.

Assisted-by: Claude

* itertools: opt the iterator types into GC traverse

cycle and its siblings hold Python references but declared no traverse, so a
cycle built through one of them leaked.

Assisted-by: Claude

* _ctypes: mask an out-of-range int instead of panicking

c_char_p(2**64) and pointer item assignment called .expect() on the narrowing
conversion. Wrap the value to the target width, which is what the C
implementation stores.

Assisted-by: Claude

* hashlib: import _hashlib when a hash module is loaded

The hash object type is a static type owned by _hashlib; calling _md5.md5()
without _hashlib imported hit an uninitialized static type and panicked.

Assisted-by: Claude

* _csv: fall back to the built-in dialect defaults when none is registered

The dialect table is empty until csv.py registers 'excel', so _csv.reader([])
unwrapped a missing entry and panicked.

Assisted-by: Claude

* builtins: reject surrogates in compile()/eval() source instead of panicking

expect_str() panics on a str containing surrogates; convert with try_as_utf8
so eval(chr(0xd800)) raises.

Assisted-by: Claude

* _suggestions: require a list for _generate_suggestions candidates

The argument was collected before validation, so an unbounded iterable
exhausted memory.

Assisted-by: Claude

* lzma: size the filter chain before consuming it

filters= was collected into a Vec before the length check, so an unbounded
iterable exhausted memory. Take the length through the sequence protocol first.

Assisted-by: Claude

* classmethod: opt into GC traverse

staticmethod already declares traverse; classmethod did not, so a cycle through
the wrapped callable leaked.

Assisted-by: Claude

* posix: reject unbounded iterables in posix_spawn and setgroups

argv, setsigdef, setsigmask and setgroups bound an ArgIterable and collected it
before validating, so an infinite generator exhausted memory. Require a
list/tuple for argv, validate signals while streaming, and take setgroups
through the sequence protocol.

Assisted-by: Claude

* _ctypes: size Array slice assignment and _argtypes_ before collecting

Both eagerly collected their argument, so an unbounded iterable exhausted
memory before the length check ran.

Assisted-by: Claude

* sys: propagate the breakpointhook warning failure

warn() was unwrapped, so an unimportable $PYTHONBREAKPOINT under
-W error panicked instead of raising.

Assisted-by: Claude

* structseq: require the sequence argument when constructing a struct sequence

A no-argument construction produced an empty backing tuple, and reading any
named field then indexed out of bounds.

Assisted-by: Claude

* Guard the hash slot dispatch against unbounded recursion

`PyObject::hash` invoked the type's hash slot directly, so an element-wise
`__hash__` following a deeply nested object graph recursed one native frame
per level and overflowed the stack. Wrap the dispatch in `with_recursion`,
matching the repr and rich-compare dispatches in the same file, so
`hash(x)` on a nested tuple/GenericAlias/slice raises `RecursionError`.

Assisted-by: Claude

* genericalias: guard the __parameters__ walk against unbounded recursion

`make_parameters_from_slice` recursed into every list/tuple argument with
nothing counting the frames, so `list[L]` for a self-referential or deeply
nested `L` overflowed the native stack at subscript time. Wrap the descent
in `with_recursion`, which makes the walk fallible; `PyGenericAlias::new`,
`from_args` and `make_parameters` now return `PyResult` and every caller
propagates.

Assisted-by: Claude

* Fix the type confusion in PyAtomicRef's Debug impl

`PyAtomicRef<T>` stores a pointer to a `Py<T>`, as `Deref`, `load_raw`,
`swap` and `Drop` all read it, but `Debug` cast it to a bare `T` and
formatted the object header as payload bytes. For `PyFunction`, whose
`code: PyAtomicRef<PyCode>` has a pointer-chasing `Debug`, that
dereferenced header words and segfaulted.

Cast to `PyObject` instead, which is what `Drop` already does and which
also covers the `PyAtomicRef<PyObject>` and `PyAtomicRef<Option<T>>`
instantiations that have no `Py<T>`.

`_asyncio._enter_task` reached this through `{:?}` in its "Cannot enter
into task" message; format the two tasks with their Python repr, which is
what the message is meant to show.

Assisted-by: Claude

* _sre: disallow instantiating Match

`Match` inherited `object.__new__`, so `M.__new__(M)` produced an instance
whose `regs`/`string`/`pattern` were never filled in by a match run; the
mapping subscript path read them and dereferenced garbage. The type has no
public constructor, so mark it `DISALLOW_INSTANTIATION`, which makes
`M.__new__(M)` raise `TypeError: cannot create 're.Match' instances`.

Assisted-by: Claude

* utils: return the empty repr instead of asserting a non-empty collection

`collection_repr` took the first element with an `.expect()` justified by the
caller's preceding non-empty check. Another thread clearing the collection
between that check and the iteration made the iterator yield nothing and
panicked the worker. Fall back to the caller-supplied empty form, which is
the text those callers already produce for an empty collection.

Assisted-by: Claude

* itertools: advance cycle's index atomically

`cycle.__next__` did `fetch_add(1)` and then reset the index to 0 in a
separate store, so two threads replaying the saved items could both read an
index past the end of `saved` and panic on the slice access. Do the advance
and the wrap in one `fetch_update`.

Assisted-by: Claude

* _ctypes: reject a float argument to a foreign call without argtypes

`conv_param`, the conversion used when `argtypes` is not set, converted its
argument with `try_int`, which goes through `__int__` and so accepts a
float. `libc.strlen(1.5)` therefore passed 1 where the callee expects a
`char *` and the callee dereferenced it. Match `ConvParam`, which does a
`PyLong_Check` and converts nothing: take the branch only for an `int` (or
a subclass, so `True` still converts), and let a float fall through to
"Don't know how to convert parameter".

The branch below it converted a float to a C double, but `try_int` claimed
every float before it could run, so it was dead; `CArgValue::Double`
existed only for that branch and both go. Typed doubles are unaffected —
they travel as `CArgValue::Typed` with code 'd'.

Assisted-by: Claude

* Report the iterator itself from PyIter's traverse

`Traverse for PyIter<O>` delegated to the inherent `PyObject::traverse` of
the object it wraps, so it reported that iterator's referents instead of
the iterator. The iterator's own reference to those referents was then
never subtracted during the collector's reference-subtraction pass, the
referents kept a non-zero gc_refs, and every object reachable from them
was classified as a root.

Any cycle running through a type with a `PyIter` field therefore survived
collection: `map`, `filter`, `zip`, `enumerate`, `reversed` and the
`itertools` iterators all leaked, while the same cycle through a `list`,
`tuple` or `list_iterator` collected. Report the wrapped object, as the
`PyObjectRef`, `PyRef<T>` and `PyStackRef` impls do.

`itertools.tee` still leaks: its shared buffer is a `PyRc<PyItertoolsTeeData>`
rather than a Python object, so the collector cannot see through it.

Assisted-by: Claude

* Remove the obsolete expectedFailure on test_code_module.test_unicode_error

Compiling a source string containing a lone surrogate now raises
UnicodeEncodeError, so the test passes.

Assisted-by: Claude

* itertools: reserve the combination indices fallibly

`combinations` and `combinations_with_replacement` built their index vector
with an infallible allocation, so an `r` that passes the ssize_t check but
does not fit in memory aborted the process instead of raising MemoryError.

Assisted-by: Claude

* Apply the struct sequence constructor's dict argument

`structseq(sequence, dict)` discarded its second argument, so the hidden
fields past `n_sequence_fields` — `tm_zone`, `st_atime` and friends — were
always None when constructed directly or restored from a `(sequence, dict)`
pickle, and a non-dict second argument was accepted silently.

Take the dict, require it to be a dict, and fill the hidden slots the
sequence did not cover from it. A key that names a field the sequence
already supplied, or no field at all, is now a
"got duplicate or unexpected field name(s)" TypeError instead of being
dropped. Both arguments are bindable by name, as `sequence` and `dict`.

`os.stat_result` and `os.statvfs_result` did not accept a second argument
at all; they and `time.struct_time` now share the parsing.

Assisted-by: Claude

* _imp: report the argument count in find_frozen's arity error

Assisted-by: Claude

* Add regression tests for the reproduced crashers

One case per catalog entry, each asserting the behavior the fix produces:
recursion guards, the memory-unsafety sites, the overflow and unbounded
allocation guards, the eager-collection rejections, the unwrap sites, and
the cycles the collector now breaks. Every expected value was checked
against CPython 3.14.

Assisted-by: Claude

* Tolerate a changed-size RuntimeError in the set repr stress test

The mutator and reader threads race on purpose; a "changed size during
iteration" RuntimeError is a valid outcome of that race and should not fail
the test. The panic it guards against is not.

Assisted-by: Claude

* Move the crash regression tests into per-module snippets

crash_regressions.py collected every reproduced crasher in one file. Split it
into the snippet for the module each case exercises, and add stdlib_gc.py,
stdlib_asyncio.py, stdlib_lzma.py, stdlib_threading_set_repr.py and
stdlib_threading_itertools_cycle.py for the cases with no existing home.

The suite runs every snippet under the host CPython too, so the checks only
RustPython raises are guarded by sys.implementation.name: the hash and
__parameters__ recursion depth, and the deque repeat overflow. The float
ctypes argument accepts either TypeError or ctypes.ArgumentError.

Assisted-by: Claude
2026-08-14 00:57:10 +09:00
Jeongseop Lim 7b58a8980d Reject extra positional arguments to float() (#8509)
* Reject extra positional arguments to float()

PyFloat::slot_new's exact-float fast path tested args.args.first(), which
succeeds for any number of positional arguments, so float(1.5, True)
returned the first one and never reached args.bind(vm). CPython's clinic
generated float_new runs _PyArg_CheckPositional("float", nargs, 0, 1)
before it fetches the first argument.

Add args.args.len() == 1 to the condition, as PyInt::slot_new,
PyStr::slot_new and PyComplex::slot_new already do; the extra argument
then falls through to args.bind(vm) and raises TypeError.

Assisted-by: Claude Code:claude-opus-5

* Bind float() arguments before the fast path

The exact-float fast path repeated float()'s argument count inline, which
duplicates what FromArgs::arity already knows. Bind first and match on the
resulting OptionalArg instead, so the positional and keyword rules stay in
one place and the bound value is reused by py_new.

Assisted-by: Claude Code:claude-opus-5
2026-08-13 23:32:19 +09:00
Jeongseop Lim 6cfa079950 Reject a fifth argument to property() (#8510)
PropertyArgs declared a fifth positional-or-keyword field, name, so the
derived arity was 0..=5 and property(None, None, None, None, None) built
a property object with the fifth argument stored in the __name__ slot.
CPython's property.__init__ is Argument Clinic generated with maxpos = 4
and the keyword list {fget, fset, fdel, doc}, so it rejects both that call
and property(name='x').

Drop the field. Nothing passed it: clone_property_with always supplied
None and copies the name separately, and the name slot is still filled by
__set_name__ and the __name__ setter.

Assisted-by: Claude Code:claude-opus-5
2026-08-13 21:51:56 +09:00
Jeongseop Lim 2e05364117 Normalize round() result to an exact int (#8511)
int.__round__ returned the receiver unchanged on the no-rounding path, so
round() on an int subclass handed back an instance of that subclass:
round(True) was True, not 1. CPython routes both no-op paths (ndigits is
None, and ndigits >= 0) through long_long(), which reuses the reference
only when the value is an exact int and otherwise copies it into a fresh
one.

Return zelf.__int__(vm).into_pyref(), which goes through into_exact_or()
and is the same normalization the neighbouring __trunc__, __floor__ and
__ceil__ already perform.

Assisted-by: Claude Code:claude-opus-5
2026-08-13 20:27:24 +09:00
Jeong, YunWon 2a793fcdd1 codegen: preserve symbol tables across copied finally bodies (#8507)
Assisted-by: OpenAI Codex:gpt-5
2026-08-13 13:16:13 +09:00
Sumi Jeong 7545bb1993 Fix locals()/vars() corrupting/leaking __conditional_annotations__ outside function scope (#8467)
CPython's _PyFrame_GetLocals only syncs fastlocals/cells into locals()
for function scope; module/class scope just returns the namespace dict
as-is. sync_visible_locals_to_mapping did this for every scope, so the
implicit __conditional_annotations__ cell (used for PEP 649/749
deferred annotations) broke two ways: at module scope its cell is
always empty, so syncing overwrote the dict's real value with None,
causing NameError on the next annotated statement; at class scope its
cell is the only real value, so syncing leaked it into locals()/dir(),
unlike CPython.

Skip cell/free slots outside function scope to match CPython, and add
a regression snippet.

Closes #8379

Assisted-by: Claude Code:claude-sonnet-5
2026-08-08 22:32:13 +09:00
강동안 85398d2f70 Specialize list.sort() comparisons for homogeneous lists (#8464)
* Use type-specialized comparators for homogeneous list sorts

Scan the sort keys once before sorting; when every element is exactly str, int, or float, compare wtf8 bytes / BigInt / f64 directly instead of going through rich_compare_bool dispatch, mirroring CPython's pre-sort check in listsort.c (unsafe_latin_compare and friends). Subclasses and mixed-type lists keep the generic __lt__ path.

* Add edge-case tests for specialized list sorts

* Cache the richcompare slot for homogeneous list sorts

* Specialize tuple sorts on their first elements

* Apply ruff formatting to the new list sort tests

* Deduplicate the reverse swap across sort dispatch arms
2026-08-08 22:30:05 +09:00
Hanif AriffinandJeong YunWon 8e920098b2 Fix bytes.isspace (#5655)
* Fix implementation of bytes.isspace to match the implementation in CPython.

* Fix implementation of bytes.istitle so that test_bigmem now passes.
Also added some extra_test to capture this.

* Fix some clippy issues

Signed-off-by: Hanif Ariffin <hanif.ariffin.4326@gmail.com>

* bytes.istitle returns false when the bytes is empty.

* Fix some edges of istitle with non-alphanumeric characters

* Disable a line because python 3.12 errors on bad escape sequence

* Match CPython's istitle a little closer

* Fix clippy warning

* Rewrite bytes.istitle along _Py_bytes_istitle

The lookahead-based check accepted b"Not--a Titlecase String", which
test_bytes covers. Track whether the previous byte was cased instead.

isspace compares bytes directly rather than converting to char.

Restore the b"omkmok\Xaa" assert: 3.14 reports an invalid escape
sequence as a SyntaxWarning, not an error.

Assisted-by: Claude

---------

Signed-off-by: Hanif Ariffin <hanif.ariffin.4326@gmail.com>
Co-authored-by: Jeong YunWon <jeong@youknowone.org>
2026-08-03 17:52:42 +09:00
0df8c8428b __length_hint__ (#6636)
* Initial plan

* fix: prevent iterator length_hint deadlock

Co-authored-by: youknowone <69878+youknowone@users.noreply.github.com>

* fix

* Auto-format: cargo fmt --all

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-08-02 21:21:11 +09:00
copilot-swe-agent[bot] 9bc27415e4 Merge remote-tracking branch 'origin/main' into copilot/fix-isalnum-function-behavior
# Conflicts:
#	crates/sre_engine/src/string.rs
#	extra_tests/snippets/builtin_str_unicode.py
2026-08-02 07:23:30 +00:00
이광효 beff2b02ac csv: port CPython reader state machine (#8381)
* csv: port CPython reader state machine

Replace the csv-core reader and per-item quote scanner with one Rust
implementation of CPython's nine-state reader parser. Keep parser state
across iterator items and distinguish virtual item boundaries from true
iterator exhaustion.

Centralize field completion so quote provenance, empty-field None conversion,
float conversion, strict parsing, field limits, blank rows, and escaped or
quoted newlines share one path. Apply the existing reentrant-iterator
generation check to every iterator item consumed by a record.

Also accept empty ASCII line terminators like CPython, report a missing
csv-core writer sentinel as _csv.Error instead of panicking, and name the
FSM entry point process_parser_input.

Remove the expected-failure markers from the eleven reader tests that now
pass.

Assisted-by: Codex:gpt-5.6-sol

* csv: test CRLF boundaries with custom lineterminator
2026-08-01 11:35:37 +09:00
조진명 071d54d442 csv: support multi-character lineterminator in writer (#8328)
* csv: support multi-character lineterminator in writer

Store the dialect line terminator as an owned String instead of the
single-byte csv_core::Terminator, dropping PyDialect's Copy derive. The
manual writer paths emit the full terminator; the csv-core-backed
QUOTE_ALL/QUOTE_NONNUMERIC paths emit a sentinel byte (preserving
csv-core's quote/empty-record bookkeeping) and append the real
terminator. field_needs_quotes/escape now quote a field containing any
terminator byte. The reader ignores lineterminator and always uses CRLF,
matching CPython and avoiding mid-UTF-8 record splits.

* csv: unmark now-passing test_write_lineterminator

* csv: address review feedback

- Remove the redundant per-branch sentinel terminator setup in to_writer;
  the unconditional terminator call after the match is the single source.
- Reword the empty-lineterminator errors to "must not be empty" (the
  constraint is non-empty, not single-character) on both entry points.
- Promote the sentinel invariant check in writerow from debug_assert_eq!
  to assert_eq! so it also guards release builds.
- Add a snippet case for a field containing a line-break byte to ensure
  the csv-core path drops only the trailing terminator.

* csv: reject non-ASCII lineterminator

The writer decides what to quote and escape by comparing raw bytes, so a
non-ASCII terminator quoted a field that merely shared a UTF-8 lead byte,
and QUOTE_NONE escaped individual bytes of the terminator and then failed to
decode the record back to a string.

Reject non-ASCII terminators, including lone surrogates, as csv.Error when
the dialect is parsed, and leave code-point-wise handling to a follow-up
(#8310). The non-string error message now matches CPython as well.
2026-07-30 00:15:33 +09:00
Jiwoo Ahn 71a406898c wasi: support monotonic / perf time (#8385)
Assisted-by: Codex:GPT-5.6 Sol

Signed-off-by: Jiwoo Ahn <ikwydls1314@gmail.com>
2026-07-29 20:33:32 +09:00
Kwak Byoung Min a49e8f9b5f Add seekable() to mmap.mmap (#8405)
* Allow mmap-backed readers to identify seek support

mmap already supports seek() and tell(); expose seekable() to match CPython.

Confidence: high
Scope-risk: narrow
Tested: test_mmap, stdlib_mmap snippet, clippy, prek, extra_tests
Not-tested: full workspace test blocked by local rustpython-capi SIGSEGV
Assisted-by: Codex:gpt-5.6-sol

* Keep mmap regression test lint-clean

CI ruff check removes the redundant blank line and treats the auto-fix as a failure.

Constraint: CI runs prek with ruff check
Confidence: high
Scope-risk: narrow
Tested: prek run --all-files; cargo run -- extra_tests/snippets/stdlib_mmap.py
Assisted-by: Codex:gpt-5.6-sol

* Keep mmap seekability method conventional

The method is invoked at runtime through the Python wrapper, so const qualification provides no benefit.

Constraint: Python methods execute at runtime
Confidence: high
Scope-risk: narrow
Tested: prek run --all-files; cargo run -- extra_tests/snippets/stdlib_mmap.py
Assisted-by: Codex:gpt-5.6-sol
2026-07-29 20:28:32 +09:00
Seonghun An 7c6e7dc29e Fix zero padding for string format specs (#8407)
* Fix zero padding for string format specs

Assisted-by: Codex:gpt-5

* Add string alignment format regression test

Assisted-by: Codex:gpt-5
2026-07-29 20:27:59 +09:00
sijun-yang 8ba361d438 Propagate method wrapper repr errors (#8371)
Assisted-by: Codex:gpt-5.6-sol
2026-07-26 13:49:19 +09:00
이광효 4ea3fd4617 ast: fix identifier interning (#8361)
* Fix AST identifier interning

Ensure parsed name and function identifier fields use interned strings,
matching CPython behavior.

Assisted-by: Codex:gpt-5.6-sol

* Apply PEP 8 import ordering
2026-07-25 19:58:05 +09:00
Jeong, YunWon 16917e0f2a Use dict keys-version stamps and entry-index hints in LOAD_ATTR/STORE_ATTR specializations (#8350)
* Use dict keys-version stamps and entry-index hints in attr specializations

Add a keys-version stamp to Dict: a globally unique u32 assigned lazily
and reset on any key-set change (new key, deletion, clear). Value-only
updates keep the stamp.

- LoadAttrMethodWithValues / LoadAttrNondescriptorWithValues: cache the
  instance dict's stamp in the pointer cache and skip the shadow probe
  while the stamp matches.
- LoadAttrWithHint: cache the entry index at specialization time; a hit
  is an identity check on the entry key instead of a hash probe, with
  self-refresh on miss.
- StoreAttrWithHint / StoreAttrInstanceValue: replace values through the
  cached entry index via set_item_with_hint.

Fixes youknowone#42

Assisted-by: Claude

* Share keys-version stamps between dicts with identical layouts

Derive the keys-version stamp from a shape — the ordered interned-key
sequence of a hole-free dict — instead of always allocating a unique
stamp. Dicts with identical layouts (instances of the same class built
by the same __init__) now carry equal stamps, so a LOAD_ATTR cache
entry populated by one instance skips the shadow probe for every
instance sharing the layout.

Shapes are held in a fixed-size lock-free table keyed by interned key
addresses; dicts with holes, non-interned keys, or more than 32 keys
fall back to dict-unique stamps.

Assisted-by: Claude

* Address clippy and review feedback for keys-version stamps

- Use BuildHasher::hash_one for shape hashing (clippy manual_hash_one)
- Fix set_item_with_hint doc: a refreshed hint is returned on any hint
  miss, not only when the hinted slot was vacant
- Route both holey-dict instances through a single LOAD_ATTR cache site
  in the snippet test

Assisted-by: Claude

* Restore try_read_cached_descriptor doc comment to its function

The doc block and #[inline] were left attached to store_attr_dict_hinted
when it was inserted above try_read_cached_descriptor.

Assisted-by: Claude

* Specialize LoadAttrWithHint even when the entry index exceeds u16

hint_for_key returns None both for an absent key and for a present key
whose entry index does not fit in u16, so very large instance dicts
stopped specializing entirely. Use get_item_opt_refresh_hint to decide
presence, degrading an unrepresentable hint to 0: the handler then
keeps taking its full-probe fallback path.

Assisted-by: Claude
2026-07-23 16:18:09 +09:00
이광효 f4ef94c464 csv: handle empty fields with skipinitialspace (#8304)
* csv: handle empty fields with skipinitialspace

skipinitialspace preprocessed records by trimming both ends of every split
field. Fields containing only spaces could therefore produce an invalid
slice, while trailing spaces were removed even though CPython preserves them.

Trim only field prefixes in the csv-core path and make the remaining
all-space trimming helper return an empty slice safely.

QUOTE_NOTNULL and QUOTE_STRINGS add another distinction: an unquoted empty
field becomes None, but a quoted empty field remains an empty string. Both
forms have identical decoded bytes, so extend the existing QUOTE_NONE custom
reader into one shared path that records whether each field started quoted.
Use that metadata only for the null conversion while retaining QUOTE_NONE
escape behavior.

Unmark Test_Csv.test_read_skipinitialspace now that its standard,
QUOTE_NOTNULL, and QUOTE_STRINGS cases pass.

This keeps the existing one-item reader lifecycle and does not add the larger
strict or multiline parser state machine.

Assisted-by: Codex:gpt-5-sol

* csv: make skipinitialspace quote-aware

The csv-core preprocessing path split each raw iterator item on every
delimiter before trimming field prefixes. Delimiters inside quoted fields were
therefore treated as separators, so spaces after them could be removed before
csv-core parsed the record.

Extract the quote, escape, delimiter, and field-start transitions from
read_quote_record() into a small per-item scanner. Reuse its events in the
skipinitialspace preprocessor and discard only InitialSpace events while
copying all other source bytes unchanged.

This keeps the custom quote-mode reader and preprocessing logic aligned
without introducing persistent multiline or strict parser state. Remove the
delimiter cache that was only needed by the old split-and-join path and add a
regression for spaces following a delimiter inside a quoted field.

Assisted-by: Codex:gpt-5-sol
2026-07-20 10:57:38 +00:00
Jeong, YunWon c7d265e8dd ctypes: fix Windows pip truststore (#8314)
* ctypes: preserve result when errcheck returns args

* ctypes: cover Windows pip truststore

* capi: implement PyEval_SaveThread

* capi: merge saved thread state into PyThreadState
2026-07-20 15:21:42 +09:00
조진명 270587e670 csv: quote embedded CR/LF under QUOTE_MINIMAL (#8315)
* csv: quote embedded CR/LF under QUOTE_MINIMAL with custom lineterminator

QUOTE_MINIMAL rows were serialized by csv-core, which only quotes bytes
registered for the configured terminator, so fields containing '\r' or
'\n' were left unquoted when the lineterminator was not CR/LF (e.g. '!'
or '\0'). Route QUOTE_MINIMAL through a hand-written path that uses
field_needs_quotes, which always treats '\r'/'\n' as needing quotes.
A single empty field is quoted and an empty row emits only the
terminator, matching CPython. QUOTE_ALL / QUOTE_NONNUMERIC still use
csv-core.

Assisted-by: Claude Code:claude-opus-4-8

* csv: unmark now-passing writer tests

test_write_iterable and test_write_empty_fields pass with the
QUOTE_MINIMAL writer fix (empty rows no longer emit an empty field).

Assisted-by: Claude Code:claude-opus-4-8
2026-07-19 13:58:32 +09:00
Seonghun An 20cb866c67 Validate TextIOWrapper chunk size (#8265)
* Validate TextIOWrapper chunk size

Match CPython for non-positive, oversized, and index-compatible values.

Assisted-by: Codex:GPT-5

* Use explicit AssertionError in io snippet

Assisted-by: Codex:GPT-5

* Report original type in chunk size overflow

Assisted-by: Codex:GPT-5

* Chain io snippet assertion error

Assisted-by: Codex:GPT-5

* Match CPython chunk size setter behavior

Assisted-by: Codex:GPT-5

* Format io snippet assertion

Assisted-by: Codex:GPT-5.6

* Match CPython type name truncation

Assisted-by: Codex:GPT-5

* Format non-ASCII chunk size test

Assisted-by: Codex:GPT-5
2026-07-18 16:39:23 +09:00
Sumi JeongandJeong, YunWon 9d9fc27082 _queue: check for pending signals during blocking get() (#8252)
* _queue: check for pending signals during blocking get()

Semaphore::acquire() waited on the condvar in a single uninterrupted call,
so a Python-level signal handler never ran until the wait itself returned.
check_signals() is only invoked from the bytecode dispatch loop, and this
native wait never passed through it -- CPython chunks its equivalent
blocking wait for the same reason.

Cap each wait at a short interval and call check_signals() between chunks,
only giving up once the caller's real deadline has actually elapsed. The
mutex guard must be dropped before check_signals() runs: a signal handler
that calls back into the same queue on the same thread would otherwise try
to relock a mutex it's still holding and deadlock against itself.

Add a regression snippet that arms a SIGALRM well before a helper thread
unblocks the queue, and asserts the handler ran near the alarm instead of
only once get() returned.

Refs #8250
Assisted-by: Claude

* _queue: correct SIGNAL_CHECK_INTERVAL doc comment

The old comment claimed this mirrors CPython's PyThread_acquire_lock_timed,
but CPython doesn't chunk its wait either -- it makes one sem_timedwait call
and relies on the OS reporting EINTR. parking_lot's Condvar has no equivalent
signal to surface, so polling is a workaround for that gap, not a mirror of
CPython's approach.

Assisted-by: Claude

* Apply suggestions from code review

Co-authored-by: Jeong, YunWon <69878+youknowone@users.noreply.github.com>

* _queue: fix comment indentation (cargo fmt)

Assisted-by: Claude

---------

Co-authored-by: Jeong, YunWon <69878+youknowone@users.noreply.github.com>
2026-07-16 17:39:48 +09:00
Kwak Byoung Min fe7993572c Forward pyexpat lexical events (#8264)
* Restore pyexpat lexical callback compatibility

Forward processing instructions, comments, and CDATA boundaries already emitted by xml-rs so registered Python handlers observe CPython-compatible events.

Constraint: Reuse existing xml-rs events without changing the dependency
Confidence: high
Scope-risk: narrow
Tested: prek; test_pyexpat; test_sax; 402 extra tests; workspace tests; clippy
Assisted-by: Codex:gpt-5.6-sol

* Recognize XML compatibility restored by lexical events

Remove stale expected-failure markers for CPython XML tests now satisfied by pyexpat lexical-event forwarding, and simplify parser event error propagation.

Constraint: CPython test edits are limited to removing stale expectedFailure markers
Confidence: high
Scope-risk: narrow
Directive: Keep parser event dispatch aligned with pyexpat handler behavior
Tested: user-verified full suite; prek run --all-files; cargo run --release -- -m test test_pyexpat test_xml_etree test_xml_etree_c test_minidom test_sax
Assisted-by: Codex:gpt-5.6-sol
2026-07-13 18:40:18 +09:00
이광효 9297e158f3 csv: fix csv escape fieldsep (#8260)
* csv: apply dialect escapechar when reading

ReaderBuilder only received escapechar when it was passed directly as a
keyword argument. A dialect object's or registered dialect's escapechar was
visible through reader.dialect but not used by csv_core.

Pass escapechar through for named, object, and default dialect paths. This
makes escaped delimiters inside quoted fields follow the configured dialect,
for example '"abc\,def"' reads as 'abc,def'.

Unmark TestQuotedEscapedExcel.test_read_escape_fieldsep.

Assisted-by: Codex

* csv: handle escaped delimiters with QUOTE_NONE

csv_core applies escapechar while reading quoted fields, but its unquoted
field state treats an escaped delimiter as a delimiter. Consequently,
QUOTE_NONE with escapechar split 'abc\,def' into 'abc\' and 'def'.

Add a small QUOTE_NONE record parser for dialects with escapechar. It keeps
the byte following an escape character as field data, so escaped delimiters
do not end a field while ordinary delimiters and record terminators retain
their usual meaning.

Unmark TestEscapedExcel.test_read_escape_fieldsep.

Assisted-by: Codex

* csv: respect skipinitialspace with QUOTE_NONE

The QUOTE_NONE parser returned before the normal reader's whitespace
preprocessing, so it ignored skipinitialspace when escapechar was set.

Track whether parsing has just followed a delimiter and skip only ordinary
spaces in that position. Escaped spaces remain field data.

Add a stdlib_csv snippet regression test for QUOTE_NONE with escapechar and
skipinitialspace.

Assisted-by: Codex:gpt-5.6-terra

* csv: deduplicate reader dialect configuration

to_reader configured ReaderBuilder separately for named, object, and default
dialects even though the configuration was identical.

Resolve the PyDialect once, then apply delimiter, double_quote, escapechar,
and quotechar in one place. Preserve the existing unregistered-name fallback
and required excel dialect lookup behavior.

Assisted-by: Codex:gpt-5.6-terra
2026-07-13 14:11:41 +09:00
Jeong, YunWon 8e30b94eef literal: round-half-even tie for normal-range float/complex repr (#8243)
to_string's normal-magnitude branch and complex::component_to_string
returned Rust's shortest formatting directly, which can pick the odd-digit
neighbour of a rounding tie where repr() picks the even one (e.g. bits
0x42e26687db6b9b04 formats as 161852602146008.13 vs repr's ...08.12).
Route both through prefer_cpython_tie_repr, generalized to fixed-notation
strings. Add unit tests and float/complex repr snippet tests.

Assisted-by: Claude
2026-07-09 21:42:08 +09:00
Jeong, YunWon c93d63a759 literal: reject internal whitespace in complex::parse_str (#8242)
parse_str split the token then parsed each part with float::parse_str,
which tolerates surrounding whitespace, so "1 +2j" parsed as (1+2j).
Reject whitespace inside the token after stripping optional parentheses.
Add unit tests and complex() snippet tests.

Assisted-by: Claude
2026-07-09 20:24:49 +09:00
Kwak Byoung Min 123dc4b9a0 Support xml.sax pyexpat setup APIs (#8238)
* Let xml.sax initialize pyexpat-backed parsers

RustPython already exposes an Expat-like XML parser, but xml.sax expects a few setup APIs before parsing. Add compatible parser setup methods and constants without pretending to implement full Expat external entity behavior.

Constraint: Lib/test changes only remove expectedFailure markers for tests that now pass; test bodies and assertions are unchanged.
Rejected: Implementing full Expat parameter entity parsing | xml-rs does not expose that configuration and the immediate failure is the missing setup API.
Confidence: high
Scope-risk: narrow
Directive: Keep SetParamEntityParsing as a compatibility shim unless the backend grows real Expat-style entity parsing support.
Tested: PATH=/tmp/pyshim:$PATH prek run --all-files
Tested: cargo run --quiet -- extra_tests/snippets/stdlib_xml.py
Tested: cargo run --release -- -m test test_sax
Tested: cargo run --release -- -m test test_pyexpat
Tested: cargo test --workspace --exclude rustpython-capi --exclude rustpython_wasm --exclude rustpython-compiler-source --exclude rustpython-venvlauncher --features threading --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env && (cd crates/capi && cargo test)
Tested: PYO3_CONFIG_FILE=$PWD/crates/capi/pyo3-rustpython.config cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher
Tested: cargo build --release --features sqlite && cd extra_tests && /tmp/rustpython-extra-tests-venv/bin/python -m pytest -v
Tested: cargo clippy --workspace --exclude rustpython-capi --exclude rustpython_wasm --exclude rustpython-compiler-source --exclude rustpython-venvlauncher --features threading --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env
Assisted-by: Codex:gpt-5.5

* Keep XML follow-up tests aligned with passing behavior

The pyexpat setup API compatibility fix also makes pulldom's basic parse smoke test pass, so keep RustPython expected-failure markers aligned with current behavior and apply the ruff import-spacing fix.

Constraint: Test body and assertions remain unchanged.

Confidence: high

Scope-risk: narrow

Tested: cargo run --release -- -m test test_pulldom -v

Tested: cargo run --release -- -m test test_sax

Tested: cargo run --release -- -m test test_pyexpat

Tested: cargo run --quiet -- extra_tests/snippets/stdlib_xml.py

Tested: PATH=/tmp/pyshim:/Users/kbm/.codex/tmp/arg0/codex-arg0ejsdGi:/Users/kbm/.omx-runs/run-20260703105454-4fab/.omx/runtime/bin:/Users/kbm/.nvm/versions/node/v24.15.0/bin:/Users/kbm/Library/Java/JavaVirtualMachines/temurin-21.0.9/Contents/Home/bin:/Users/kbm/.antigravity/antigravity/bin:/opt/homebrew/opt/mysql-client/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/Library/Apple/usr/bin:/var/folders/vq/1mhmtsbs2kj_03tsx74kd1mm0000gn/T//cmux-cli-shims/93BA47BD-630C-4ED3-8573-0FE6ABFAE824:/Applications/cmux.app/Contents/Resources/bin:/Users/kbm/.nvm/versions/node/v24.15.0/bin:/Users/kbm/Library/Java/JavaVirtualMachines/temurin-21.0.9/Contents/Home/bin:/Users/kbm/.antigravity/antigravity/bin:/opt/homebrew/opt/mysql-client/bin:/var/folders/vq/1mhmtsbs2kj_03tsx74kd1mm0000gn/T/cmux-cli-shims/93BA47BD-630C-4ED3-8573-0FE6ABFAE824:/Applications/Visual Studio Code.app/Contents/Resources/app/bin:/Applications/Visual Studio Code.app/Contents/Resources/app/bin:/Applications/Visual Studio Code.app/Contents/Resources/app/bin prek run --all-files

Tested: cargo build --release --features sqlite && cd extra_tests && /tmp/rustpython-extra-tests-venv/bin/python -m pytest -v

Tested: PYO3_CONFIG_FILE=/Users/kbm/IdeaProjects/RustPython/crates/capi/pyo3-rustpython.config cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher

Tested: cargo clippy --workspace --exclude rustpython-capi --exclude rustpython_wasm --exclude rustpython-compiler-source --exclude rustpython-venvlauncher --features threading --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env

Assisted-by: Codex:gpt-5.5
2026-07-09 20:24:16 +09:00
Jeong, YunWon 210ccc889c Thread-safe type operations: type lock, QSBR type-cache reclamation, GC stop-the-world, and interpreter optimizations (#7416)
* type lock

* Drop old PyObjectRef outside type lock to prevent deadlock

Dropping values inside with_type_lock can trigger weakref callbacks,
which may access attributes (LOAD_ATTR specialization) and re-acquire
the non-reentrant type mutex, causing deadlock.

Return old values from lock closures so they drop after lock release.

* Align type lock behavior with CPython

* Add PUBLISHED flag bit to RefCount state word

Assisted-by: Claude

* Add QSBR module for deferred memory reclamation

Assisted-by: Claude

* Defer memory free of cache-published objects via QSBR

Assisted-by: Claude

* Wire QSBR checkpoints into thread lifecycle and eval breaker

Assisted-by: Claude

* Publish type-cache values to QSBR and bypass cache without a VM

Mark cached type-method values as QSBR-published before storing their
pointer in TYPE_CACHE, so racing readers never try-incref freed memory.
Debug-assert that the current thread is ATTACHED whenever a lock-free
cache read happens.

Delete find_name_in_mro_without_vm and its unsound direct SeqLock read
outside any VM/thread registration; find_name_in_mro now falls back to
the locked, uncached MRO walk when no VM is current. This also removes
assign_version_tag()'s last caller, so its unlocked fallback is deleted
along with it (version_for_specialization keeps the locked path).

VirtualMachine::initialize() runs Python bytecode (e.g. importing
codecs/encodings) before any enter_vm scope exists, which left the
bootstrap thread not ATTACHED for cache reads during startup. Add
thread::VmBootstrapGuard, an RAII counterpart to enter_vm usable across
statements that need &mut VirtualMachine, and wrap initialize() with it.

Assisted-by: Claude

* Use try-incref reads and QSBR-backed swaps in specialization cache

Assisted-by: Claude

* Reset QSBR thread registry after fork in the child

Add Qsbr::reset_after_fork, which clears the registered thread slots
before draining the retire queue. Call it in py_os_after_fork_child,
right after type_cache_after_fork() and before
_thread::after_fork_child() re-registers the surviving thread.

Dead parent threads' Arc<QsbrSlot> handles live on in the child's
copied memory with no destructor ever running, so without this the
registry keeps them 'online' forever and future grace periods never
complete.

Assisted-by: Claude

* Add threaded stress test for type cache mutation races

Assisted-by: Claude

* Restrict qsbr internals to pub(crate) and fix clippy lints

Downgrade pub items in the private qsbr::threading module (QsbrSlot,
Qsbr, QSBR, and its methods) to pub(crate), since they were never
reachable outside the crate. Downgrade ThreadSlot::qsbr accordingly to
avoid a private-interfaces warning. Import Arc/Weak from alloc instead
of std to match clippy::std_instead_of_alloc. Rewrite the process()
comment: goals are not strictly ordered by push order since advance()
and the queue push aren't atomic together, so concurrent free_delayed
calls can interleave; the drained prefix stays sound because each item
individually passed poll, with reordering only affecting reclamation
latency.

Assisted-by: Claude

* Gate per-instruction QSBR check behind a global pending flag

eval_breaker_tripped() and check_signals() called
thread::qsbr_break_requested() on every bytecode instruction, which
does a thread-local lookup, RefCell borrow, and atomic load even when
no QSBR retirement is pending. This caused a measured 10-18% slowdown
on tight interpreter loops.

Add Qsbr::pending, a global AtomicBool set under the queue lock while
free_delayed() holds a retired allocation, and cleared under the same
lock by process()/drain_all() once the queue empties. The hot path now
checks Qsbr::break_pending() (a single relaxed static load) before
touching thread-local state, and only pays the TLS cost while a
retirement is actually in flight.

Assisted-by: Claude

* Merge signal and QSBR eval-breaker flags into one atomic word

Replace the separate ANY_TRIGGERED AtomicBool and QSBR pending
AtomicBool checks in the per-instruction eval-breaker path with a
single AtomicU8 (EVAL_BREAKER) holding a bit per source. The global
QSBR instance mirrors its pending state into the QSBR bit under the
same queue-lock critical sections that already toggle pending, while
local QSBR instances used by unit tests are left untouched.

eval_breaker_tripped() and check_signals() now read/act on the merged
word (eval_breaker_pending(), qsbr_bit_set()) instead of issuing two
separate atomic loads per instruction. set_triggered() switches from
store to fetch_or so a signal handler never clobbers the QSBR bit.

Removed the now-unreferenced is_triggered() helper; break_pending()
is kept for unit tests only and marked allow(dead_code) outside test
builds.

Assisted-by: Claude

* Skip freelist reuse for published objects in default_dealloc

Freelist-eligible payloads (tuple, int, list, dict, float, ...) were
routed to T::freelist_push before ever reaching PyInner::dealloc, so a
published object (e.g. a tuple cached as a type attribute) bypassed the
is_published -> free_delayed QSBR hook entirely. That let PyRef::new_ref
reuse the slot and rewrite the refcount word with a non-atomic
core::ptr::write racing a reader's atomic try-incref, and let
FreeList::drop call alloc::dealloc directly while a reader could still
be mid-read.

Gate the freelist branch in default_dealloc on
RefCount::is_published(), checked before any teardown. A published
object now always falls through to PyInner::dealloc, whose existing
hook defers the memory free via QSBR.

Document the non-unix (e.g. Windows) reclamation-latency limitation in
the QSBR design doc's Lifecycle integration section (previously only
noted in a code comment in vm/thread.rs).

Extend the type-cache stress test so the mutator also churns a
freelist-eligible published tuple class attribute (C.shape), read by
readers each inner loop and deleted on the same cadence as C.m, to
exercise the fixed bypass.

Assisted-by: Claude

* Use itoa for PyInt::to_str_radix_10 i64 fast path

Format small integers with itoa::Buffer instead of i64::to_string()
in PyInt::to_str_radix_10(), which backs both str(int)/repr(int) for
exact int and PyObject::str()'s exact-int fast path. Adds the itoa
crate as a workspace dependency.

Assisted-by: Claude

* Make object attribute dunders wrapper descriptors

Remove the __getattribute__, __setattr__ and __delattr__ #[pymethod]s
from PyBaseObject so add_operators installs PyWrapper slot wrappers for
them from the #[pyslot] functions instead of method descriptors.

lookup_slot_in_mro now classifies these entries as NativeSlot, so heap
types without Python-level overrides keep the native getattro/setattro
slot functions, which lets LOAD_ATTR/STORE_ATTR specialization apply to
instances of Python-defined classes.

Since __setattr__ and __delattr__ share the setattro slot, resolve both
names together in update_one_slot: overriding only one of them no longer
lets the other name's native resolution overwrite the dispatching
wrapper.

Assisted-by: Claude

* Resolve TpSetattro pair on attribute deletion, not just addition

update_one_slot's TpSetattro branch only ran the combined
__setattr__/__delattr__ resolution (added in the previous commit) when
ADD was true. On deletion (e.g. del C.__setattr__), it fell back to
inherit_from_mro, which copies the base class's slot and discards the
class's own remaining Python-level override of the other name.

lookup_slot_in_mro reads the current attribute dicts, so the same
resolution is correct for both addition and deletion; the ADD-only
guard is removed and the logic now always runs.

Assisted-by: Claude

* Generate Opcode::cache_entries/deopt as table lookups

generate_rs_opcode_metadata.py now emits a 256-entry const array for
each function instead of a chained match over opcode names.
Opcode::deopt() indexes an [Option<Opcode>; 256] table built from the
existing specialization-to-base mapping, and Opcode::cache_entries()
indexes a [u8; 256] table that bakes in the same deopt/to_base
composition deoptimize() previously performed before its own match.
Regenerated opcode_metadata.rs from the updated script; PseudoOpcode's
bodies are unchanged since it has no cache/deopt entries to table.

Added an exhaustive test in instruction.rs that checks every valid u8
opcode against a frozen copy of the old chained-match bodies.

Assisted-by: Claude

* Make Opcode/Instruction numeric conversions O(1)

Opcode::as_numeric, Opcode::as_instruction and Instruction::as_opcode
were each a per-variant match over ~230 arms in the define_opcodes!
macro. Opcode now carries the same explicit $op_id discriminants and
#[repr($typ)] as Instruction, which makes the conversions sound as:

- Opcode::as_numeric: a plain `self as $typ` identity cast.
- Opcode::as_instruction / Instruction::as_opcode: a mem::transmute,
  relying on both enums sharing one-$typ-wide layout (Instruction's
  payload fields are all the zero-sized Arg<T> marker, checked by a
  new per-instantiation size_of assertion).

try_from_numeric is left as a match: $op_id values have gaps
(specialized/instrumented opcode ranges), so a range check can't
replace it.

Adds #[inline] to the rewritten conversions plus deoptimize, and to
the small generated wrapper/table-lookup functions from the previous
opcode-metadata change (as_u8/as_u16, cache_entries, deopt, to_base)
via generate_rs_opcode_metadata.py, then regenerates
opcode_metadata.rs.

Extends the instruction.rs equivalence-test pattern with two
exhaustive tests (u8 and u16 instantiations) checking the new
identity-cast/transmute conversions against the untouched
try_from_numeric/TryFrom paths.

Assisted-by: Claude

* Pop CallIsinstance arguments directly instead of collecting into Vecs

The specialized handler built two heap-allocated Vecs per call
(pop_multiple().collect() plus a with_capacity(2) buffer) before
invoking is_instance. Pop the class and instance straight off the
stack for the effective two-argument case, removing the per-call
allocations.

Assisted-by: Claude

* Inherit tp_new instead of always installing new_wrapper

update_one_slot's TpNew branch stored new_wrapper for every ADD, so all
heap types had slots.new == new_wrapper and the CallAllocAndEnterInit
specialization never fired. Now __new__ is resolved through the MRO
dicts: an own or Python-level definition installs new_wrapper, while a
builtin __new__ entry (or none) inherits slots.new from the solid base.

The now-reachable CallAllocAndEnterInit path gains the missing guards:
the specializer requires co_argcount == oparg + 1 (via
can_specialize_call) and rejects generator-like __init__, and the
handler re-checks the argcount against the class-level init cache.
Without the argcount check, __init__ defaults broke re._parser
(UnboundLocalError in SubPattern.__init__). Remove the now-unused
is_simple_for_call_specialization.

Assisted-by: Claude

* Skip locals dict allocation for the init-cleanup shim frame

Mark the shim code object NEWLOCALS and create the shim frame with no
locals mapping so FrameLocals::lazy() is used. The shim only executes
ExitInitCheck/ReturnValue and never touches locals, so this removes one
dict allocation per specialized instantiation.

Assisted-by: Claude

* Guard CALL_ALLOC_AND_ENTER_INIT with cached function version

The init specialization cache stored only the type version, so swapping
__init__.__code__ (which zeroes func_version) did not deopt the warmed
call site and stale code assumptions (argcount shape, no varargs/kwonly,
not a generator) were applied to the new code object.

Store get_version_for_current_state() in the specialization cache when
caching __init__ and re-check func_version() in the handler before using
the cached function, deopting to the generic call path on mismatch, the
same way the getitem specialization cache does.

Assisted-by: Claude

* Apply rustfmt and ruff-format fixes to files from earlier commits

Assisted-by: Claude

* Add frame object freelist

Frame.iframe becomes FrameUnsafeCell<Option<InterpreterFrame>> so a dead
frame can be left as an empty husk. Traverse::clear extracts all owned
child references (including localsplus values via LocalsPlus::clear_into)
and empties the cell. Dead frame allocations are cached in a thread-local
FreeList<Frame> (up to 200 entries) and reused by PyRef::new_ref.

clear_generator returns early when the frame was already cleared by cycle
collection; generator drops can run after tp_clear of their frame.

gc: skip tp_clear for objects saved to gc.garbage by DEBUG_SAVEALL, since
they remain reachable from Python.

Assisted-by: Claude

* Drop frame children directly in tp_clear instead of extracting

Pushing the frame's ~10 child references into the clear buffer grew a
Vec on every frame deallocation. Take the interpreter frame out of the
cell and drop it in place; LocalsPlus::clear_into is removed.

Assisted-by: Claude

* Untrack objects before tp_clear and guard cross-thread f_locals

The cycle collector called tp_clear on unreachable objects while they
were still linked into the GC generation lists, so another thread could
obtain a strong reference to an already-cleared object (e.g. a frame
husk with iframe == None) via gc.get_objects() and access the cleared
payload. Untrack the dead set before the clear phase, mirroring the
untrack-then-clear ordering of the refcount dealloc path.

Objects that gained an external reference before untracking are found
by comparing each object's strong count against the references coming
from within the dead set; such late-resurrected objects and everything
reachable from them are re-tracked and skipped, letting a later
collection retry once the external references are released.

Also reject f_locals access for a frame currently executing on another
thread. Reading fastlocals of such a frame races with the executing
thread overwriting the slots (torn reads of dropped values). Access
from the executing thread itself (locals(), trace callbacks) is still
allowed via the current-frame chain check.

Assisted-by: Claude

* Skip localsplus heap copy for uniquely referenced dying frames

release_datastack_frame now checks the frame's strong count after
untracking it from the GC generation lists. When the caller holds the
only reference, localsplus values are dropped in place and the data
stack storage is released without the heap copy; escaped frames
(traceback, sys._getframe, trace callbacks) keep the copy path.
The three inline materialize+pop call sites in function.rs are routed
through release_datastack_frame.

Assisted-by: Claude

* Stage exact-args call arguments in stack slot buffers

CallPyExactArgs, CallBoundMethodExactArgs and CallAllocAndEnterInit no
longer collect popped arguments into a per-call Vec (plus a second Vec
for self-prepending). Arguments are popped into a fixed-size
Option<PyObjectRef> slot buffer (CallArgBuffer, 8 inline slots, heap
fallback for larger arities) and moved into fastlocals via the new
invoke_exact_args_slots / a take() iterator.

- prepare_exact_args_frame now accepts an ExactSizeIterator of args
- specialization_run_init_cleanup_shim takes the slot buffer and fills
  slot 0 with new_obj, dropping one redundant clone
- LoadAttrGetattributeOverridden, LoadAttrProperty and
  BinaryOpSubscrGetitem pass inline slot arrays instead of vec![]

Assisted-by: Claude

* Reduce allocations in generic call paths

- FuncArgs::prepend_arg: use reserve instead of reserve_exact so
  exact-capacity vectors do not realloc on every prepend.
- IntoFuncArgs::into_method_args: build the final args vec once with
  capacity len + 1 instead of prepending into a full vector.
- PyType::call: skip cloning FuncArgs when no init slot can run after
  slot_new (no init slot, not `type`, and slot_new is not new_wrapper).

Assisted-by: Claude

* Skip redundant exc_info restore on frame exit

with_frame_impl saves the current exc_info slot value and restores it
when the frame exits. When the slot still holds the same value, the
restore rewrites the slot and recomputes the thread-exception mirror
for no effect. Add restore_exception, which compares the slot against
the saved value by pointer identity and skips the store when they
match. The saved value is a strong reference held for the whole frame
scope, so the pointed-to object cannot be freed and its address reused
while the frame runs, making the pointer comparison free of ABA.

Assisted-by: Claude

* Apply rustfmt to gc_state.rs

Assisted-by: Claude

* Avoid empty FuncArgs clone in PyType::call

Cloning args for the init call clones the kwargs map even when args is
empty, which shows up in no-argument instantiation profiles. Prepare
the init-call args before slot_new: a default FuncArgs when args is
empty (indistinguishable from a clone of empty args), the existing
clone otherwise. The empty check also keeps the init-slot load of the
clone-elision path off the no-argument call path.

Assisted-by: Claude

* Push freelist husks only after tp_clear and child drops

default_dealloc pushed the object onto the thread-local freelist before
running clear_fn. Payloads that drop children inside clear (Frame) can
run __del__ there, and a reentrant allocation could pop the husk and
overwrite its payload while clear_fn still held a &mut borrow of it.
Tuples had the same window through the extracted-edges drop, which ran
after the push.

Reorder default_dealloc to clear, drop the extracted children, and only
then attempt the freelist push, so the husk becomes reusable only when
no borrows into the payload remain.

The tuple freelist bucketed husks by element count, which required
reading the payload during push; after this reordering the elements are
already cleared. PyInner<PyTuple> is a fixed-size allocation (the
elements box is dropped and replaced on reuse), so replace the per-size
buckets with the shared single-list FreeList. Remove the now-unused
pyinner_layout helper.

Assisted-by: Claude

* Resolve __set__ and __delete__ together for the descr_set slot

The descr_set slot serves both __set__ and __delete__, but the
TpDescrSet accessor resolved only the single modified name and fell
back to MRO inheritance on delete. Deleting one of the pair could
disable the surviving operation: after `del D.__set__`, an instance
delete stopped calling the remaining __delete__.

Resolve both names together like the TpSetattro accessor does: any
Python-level definition selects the dispatching wrapper, matching
native functions are stored directly, a single native function with
the other name absent is stored directly, and the slot is inherited
from the MRO only when neither name resolves.

Assisted-by: Claude

* Update type base on __bases__ assignment

set_bases replaced bases and mro but never updated the stored base, so
__base__ kept reporting the old value after reassignment and slot
resolution (tp_new inheritance, set_new/set_alloc during init_slots)
read the stale solid base.

Change the base field to PyAtomicRef<Option<PyType>> so it can be
swapped under the type lock while remaining lock-free for readers, and
recompute it in set_bases with the same best_base validation type
creation uses (BASETYPE flag, instance layout conflict among bases).
The swapped-out base is parked in the frame's temporary refs; other
references released inside the critical section are dropped after the
lock is released.

Also in set_bases:
- remove this class from the old bases' subclass lists (pruning dead
  entries), so repeated assignment no longer accumulates duplicates
- roll back bases, base, and all updated mros when the recursive mro
  update fails, instead of leaving the type half-reparented
- fix the misformatted empty-tuple error message

Remove the expectedFailure marker from test_unsubclassable_types,
which now passes.

Assisted-by: Claude

* Fix rollback order, dead weakrefs, and lock-held drops in set_bases

- Restore recorded mros in reverse on rollback so a class visited
  multiple times through diamond inheritance ends with its original
  mro instead of an intermediate one.
- Skip dead weakrefs in the subclass list during the recursive mro
  update instead of panicking on upgrade.
- Retire the replaced mros on the success path instead of dropping
  them while the type lock is held.

Assisted-by: Claude

* Reify number sub-slot wrapper once in update_one_slot

The update_sub_slot! macro expanded the Python-method wrapper closure at
both the own and inherited store sites. Each expansion is a distinct fn
item, so a base and a non-overriding subclass stored wrappers with
distinct addresses in unmerged debug builds. binary_op1 compares slot fn
addresses to detect whether a subclass overrides the operator, so the
inherited slot was misread as an override and C() // E() dispatched to
__rfloordiv__ instead of __floordiv__.

Bind the wrapper store in a single closure and call it from both branches
so the fn item is reified once and the slot value stays identical across
a base and its subclasses. Document the conservative-on-mismatch nature
of the new_wrapper address guard in call_wrapped.

Assisted-by: Claude

* Restrict type_cache_after_fork visibility and guard type-cache reads

type_cache_after_fork is only called from within the crate, so mark it
pub(crate) to resolve the unreachable-pub warning.

Add debug_assert_current_thread_attached at the has_name_in_mro lock-free
type-cache read site, matching lookup_ref_and_version_interned, and gate
the function on debug_assertions so it is not compiled unused in release
builds where the call sites are elided.

Assisted-by: Claude

* Guard BinaryOpSubscrGetitem with the cached type version

The specialized BINARY_OP_SUBSCR_GETITEM handler used the cached
__getitem__ after checking only the function version, unlike the sibling
specialized handlers which revalidate the type version tag first.

Store the type version in the inline cache at specialization time and
revalidate owner.class().tp_version_tag against it before using the cached
function, deopting to the generic subscript path on mismatch.

Assisted-by: Claude

* Call __abstractmethods__ __len__ once in object.__new__

The abstract-method check invoked the user-visible __len__ twice: once via
length_opt for the count and again while materializing the method names.
Derive the count from the materialized list instead, so __len__ runs once.

Assisted-by: Claude

* Use i64 fast paths for specialized int add/sub/mul

Rewrite execute_binary_op_int to box results through new_int via i64
checked arithmetic instead of raw BigInt ops with new_bigint. Add an
int_mul helper and a shared int_fast_op that computes the i64 result and
falls back to the BigInt operation on to_i64 or checked-op failure.

Wire int_mul into both the specialized BinaryOpMultiplyInt handler and
the generic execute_bin_op Multiply/InplaceMultiply path, gated on exact
int operands so subclasses keep dispatching through _mul/_imul.

Assisted-by: Claude

* Use i64 fast paths for exact int floordiv and remainder

Add floordiv_i64/mod_i64 computing i64 floor-division and divisor-signed
remainder, guarding zero divisor and i64::MIN overflow by returning None.
Wire them through int_floordiv/int_mod (shared int_div_fast_op boxes via
new_int) into the generic execute_bin_op FloorDivide/Remainder and their
Inplace variants, gated on exact int operands so subclasses and zero
divisors fall through to the existing _floordiv/_mod/_ifloordiv/_imod
slow path.

Assisted-by: Claude

* Skip trashcan and untrack for non-GC-tracked objects in dealloc

default_dealloc read is_gc_tracked() only to decide untracking, and
entered the trashcan recursion guard unconditionally. Non-GC objects
(int, float, str, ...) own no child references that recurse during
deallocation, so they need neither the trashcan nor untracking. Read
is_gc_tracked() once and gate both trashcan begin/end and untrack on it,
removing three thread-local accesses per non-GC object deallocation.

Assisted-by: Claude

* Merge trashcan depth and defer queue into one thread-local struct

trashcan::end accessed two separate thread-locals (DEALLOC_DEPTH and
DEALLOC_QUEUE) at the outermost deallocation. Combine both into a single
`Trashcan` thread-local holding Cell-based depth and queue fields, so
begin and end each reach their state through one thread-local access.
The queue is set back before each deferred dealloc call so reentrant
begin/end during draining never holds an outstanding borrow.

Assisted-by: Claude

* Check object layout compatibility on __bases__ and __class__ assignment

Add a shared compatible_for_assignment helper that walks each type to the
base that fixes its instance layout and rejects the assignment when the old
and new layouts differ (basicsize, itemsize, member count, __dict__,
__weakref__, and __slots__ names). Wire it into set_bases, which previously
performed no layout check, and replace the inline check in __class__
assignment, which compared the two types directly and over-rejected a
subclass that adds no layout.

Enable test_descr.test_builtin_bases, which the new set_bases check passes.

Assisted-by: Claude

* Stop the world around GC pointer-reading phases

The cycle collector reads each tracked object's interpreter state during
reference subtraction, the reachability walk and the strong-reference
snapshot, including the localsplus of frames other threads are executing.
Those slots are written without synchronization, so the reads are a data
race under threading.

collect_inner now stops the world before taking the generation read locks
and restarts it after the strong-reference snapshot, before the
finalizer/weakref/tp_clear phases. A debug assertion checks that no frame
on any thread's call stack was classified unreachable.

Automatic collections from maybe_collect are deferred to the next bytecode
safepoint via a new eval-breaker GC bit instead of running synchronously:
a synchronous collection can hold an internal lock (e.g. the lazy frame
locals cell) that another thread is blocked on with no way to reach a
safepoint, deadlocking the stop.

Hardens the stop-the-world machinery for these frequent, concurrent GC
stops: attach_thread now honors a pending stop after re-attaching so a
thread doing rapid allow_threads calls cannot run past the requester;
stop_the_world completion is level-triggered on all-threads-suspended
rather than an edge-triggered countdown; and the thread-start started/ready
handshakes detach while waiting so the waiter is parkable.

Updates the Frame and PyRwLock/PyMutex traversal SAFETY comments to state
the actual invariant.

Assisted-by: Claude

* Add threaded GC vs executing-frame stress snippet

Workers churn frame state (recursion, generators, frame cycles) while a
collector loops gc.collect() and an introspector walks live frame objects.
Exercises the stop-the-world barrier around GC traversal.

Assisted-by: Claude

* Serialize fork and GC stop-the-world requesters

fork() (posix before/after-fork) and the cycle collector both drive the
single StopTheWorldState. With no mutual exclusion their requester word and
suspension countdown could interleave and be clobbered, so the completion
check never converged and a requester waited on itself forever (reproducible
parent-side hang when forking with GC enabled).

Add one exclusion held for the whole stop->start span of either requester:
stop_the_world acquires it before any stop bookkeeping and
start_the_world/reset_after_fork release it. The acquire is park-friendly
(poll try-lock and honor a pending suspend between tries) so a requester
blocked behind an active stop can still be force-parked instead of deadlocking
the active requester. The acquirer holds no other lock while spinning.

Also correct the PyRwLock traverse SAFETY note: a failed try_read may mean a
force-parked thread holds the write lock; skipping is safe because
under-traversal only over-approximates liveness. Document the residual
gc.collect()-under-a-non-generation-lock exposure at the collect_inner barrier.

Assisted-by: Claude

* Add fork under concurrent GC stop-the-world snippet

Worker threads allocate cyclic garbage with GC enabled while the main thread
forks repeatedly and each child collects. Exercises the fork/GC
stop-the-world exclusion; the allocation rate is throttled so a collection
stays cheap in unoptimized builds.

Assisted-by: Claude

* Detach while acquiring the import lock

The global import lock is held across bytecode by the importlib bootstrap,
so its holder can be parked at a safepoint mid-hold. Acquiring it while
attached let another thread block attached on the lock, so a stop-the-world
requester could wait forever for that attached thread to suspend while the
holder stayed parked.

Wrap IMP_LOCK acquisition in allow_threads in both _imp.acquire_lock and the
pre-fork acquire_imp_lock_for_fork so the wait honors stop-the-world requests.
Correct the acquire_exclusion comment: a spinning requester may hold IMP_LOCK
(fork) or the collecting mutex (GC); safety relies on those never being
acquired attached-blocking by another thread.

Assisted-by: Claude

* Add concurrent-import vs GC deadlock snippet

Two threads re-import modules (contending the import lock) while a third
storms the cycle collector and a fourth allocates cyclic garbage. Regressed
as a hang before the import lock acquisition was made park-friendly.

Assisted-by: Claude

* Create call frames untracked and track generators explicitly

Add PyPayload::NEW_REF_UNTRACKED (default false, true for Frame) so
PyRef::new_ref skips auto-tracking ordinary call frames in the GC.
Generator/coroutine/async-generator frames are tracked explicitly in
invoke_with_locals before their generator back-reference is installed.
run_frame debug-asserts that a datastack frame is untracked on entry.

Assisted-by: Claude

* Track escaped call frames lazily at datastack release

Rewrite release_datastack_frame around the invariant that a datastack
frame is never GC-tracked while it runs: strong_count() == 1 means the
frame never escaped, so drop localsplus in place without touching the
GC; strong_count() > 1 means it escaped, so materialize localsplus onto
the heap and then track the frame. This removes the untrack and the
untrack-recheck dance from the common non-escaping path.

Assisted-by: Claude

* Guard the tracked-frame localsplus invariant

Document at Frame::traverse that references to a frame are always
recorded as graph edges, so the collector reads a frame's localsplus
only when the frame is itself a tracked candidate. Add debug assertions
at both frame track sites (escaped datastack frames and generator
frames) that a frame is heap-backed before it is tracked, so a collector
never reads data-stack-resident, still-mutating storage.

Assisted-by: Claude

* Reword frame/dealloc invariant comments and drop needless borrow

- frame.rs: replace the task codename in the tracked-frame localsplus
  invariant comment with a description of the collector-vs-executing-frame
  behavior.
- object.rs: remove needless borrow on current_cls in the __class__
  assignment compatibility check.
- core.rs: rewrite the default_dealloc trashcan/untrack-skip comment to
  state the actual invariant, which now covers untracked non-escaped
  frames releasing at interpreter depth with bounded recursion.

Assisted-by: Claude

* Move type SetAttr slot rewrite inside the type lock and tighten cache reads

Run update_slot inside the same with_type_lock transaction as
modified_inner and the attributes dict mutation, so the version
invalidation, dict change, and slot-table rewrite are published together.

Load init_version and getitem_version with Acquire in the specialization
cache readers to pair with the Release stores in the writers.

Assisted-by: Claude

* Capture the type version before reading mutable slots in specializers

specialize_load_attr, specialize_store_attr, specialize_to_bool, and the
CallAllocAndEnterInit path of specialize_call read the version tag with
version_for_specialization before inspecting getattro, setattro, the
bool/len slots, and tp_new/tp_alloc, so a concurrent install of the
corresponding dunder invalidates the version the specialization is cached
against.

In the BinaryOpSubscr __getitem__ path, check the HEAPTYPE and
eval-frame gates before lookup_ref_and_version_interned, which takes the
global type lock and may allocate a version tag.

Assisted-by: Claude

* Use _get_method_dict for the test_type check in the test runner

Replace the direct __func__.__dict__ access with the _get_method_dict
helper so plain functions without __func__ do not raise AttributeError.

Assisted-by: Claude

* Fix lint hooks: cspell dictionary entries, spelling fix, formatting

Add qsbr to the rustpython dictionary and reborrows/reparenting to
the top-level word list. Rename oldto/newto locals to old_to/new_to.
Fix Stabilise -> Stabilize typo in a frame.rs comment.
Apply cargo fmt to object.rs, type.rs, and frame.rs, and ruff
format/check fixes to two extra_tests snippet files.

Assisted-by: Claude

* Rebuild all slots for type and descendants on __bases__ reassignment

Add PyType::update_all_slots, which invalidates version tags and iterates
the full SLOT_DEFS name table calling update_slot::<true> for each distinct
name. Unlike init_slots, which is additive and driven only by dunder names
present in the current MRO, this resets a slot whose method left the MRO
instead of leaving a stale dispatcher pointer.

Call it from set_bases in place of the previous modified_inner + init_slots
pair, so reassigning __bases__ rebuilds slots for the type and every
descendant.

Add extra_tests/snippets/type_bases_slot_rebuild.py covering removed-method
resets on zelf and deep descendants, the wrong-target switch, __getattr__,
the added-method mirror, and a swap-away-and-back round trip.

Assisted-by: Claude

* Derive the thread-local frame stack from the frame chain

Remove the per-VM `frames` Vec. current_frame, sys._getframe,
sys._getframemodulename, frame.f_back, sys.monitoring re-instrumentation,
gc.get_referrers, faulthandler stack dumps and the post-fork slot rebuild
now walk the signal-safe CURRENT_FRAME/`previous` chain instead. Add
`Py::from_payload_ptr` to recover a frame object from a chain pointer.

The cross-thread `ThreadSlot::frames` registry (sys._current_frames,
cross-thread f_back, GC stop-the-world assertion) is unchanged.

Assisted-by: Claude

* Inherit sub-slot fallback into the field being resolved

update_one_slot's number/sequence/mapping fallback inherited via the
accessor's default field. Left and right binary ops (add/right_add)
share one accessor but occupy distinct fields, so resolving an absent
right op or deleting it reset the left op's field, dropping a
still-defined __add__ dispatcher. Inherit the exact field under
resolution instead.

Assisted-by: Claude

* Gate type_cache_after_fork to its fork caller and use Self in downcast

type_cache_after_fork is only called from the unix fork path, so gate it
with all(feature = "host_env", unix) to match the caller and avoid a
dead-code error on non-unix targets. Replace the explicit PyType with Self
in the modified_inner downcast.

Assisted-by: Claude

* Unmark test_attr and test_method_call_error in test_monitoring

Both TestLoadSuperAttr tests now pass; remove their expectedFailure markers.

Assisted-by: Claude

* Run tp_new specialization __init__ without a trampoline frame

CallAllocAndEnterInit ran __init__ inside a synthetic init-cleanup shim
frame whose code carried the __init__ name. Since the thread frame stack
is derived from the frame chain, that shim frame was visible to
sys._getframe, f_back walks, traceback construction and inspect.stack /
inspect.trace. Its code object has empty co_positions, so a stack walk
that reached it raised StopIteration inside inspect._get_code_position,
cascading into unrelated failures (test_inspect trace/stack/frame,
asyncio source traceback).

Call __init__ directly via run_frame, enforce the __init__() should
return None contract inline, and drop the shim: the init-cleanup code
object, its builder, with_frame_untraced, monitoring_disabled_for_code,
and the extra-frame datastack/recursion budget. Removing the second
frame per construction also cuts the specialization's per-call cost.

Assisted-by: Claude

* Replace per-call thread-frame mutex with an atomic top-of-stack (unix)

On unix threading builds, publish each thread's top Python frame in a
single relaxed AtomicPtr store from set_current_frame instead of pushing
onto a parking_lot::Mutex<Vec<FramePtr>> per call. Cross-thread readers
(sys._current_frames, cross-thread f_back, faulthandler.dump_traceback,
the GC unreachable debug-assert) run under stop-the-world and walk the
published top frame down the Frame::previous chain; the owning thread is
then parked at a safepoint, so the pointer and the frames it reaches are
quiescent and alive. The faulthandler watchdog is a plain OS thread that
cannot stop-the-world, so it walks the chain lock-free and best-effort.

Non-unix threading builds have no stop-the-world and keep the existing
mutex-guarded frame stack unchanged.

Assisted-by: Claude

* Skip exc_info save/restore for callees that never touch the slot

with_frame saves and restores the shared exc_info slot around every
Python call to contain frames that leave it unbalanced. Cache a
has_exc_handling bit on PyCode at creation, set when the bytecode
contains any opcode that calls vm.set_exception (PushExcInfo, PopExcept,
CheckEgMatch, EndAsyncFor, InstrumentedEndAsyncFor). A callee whose code
has none of these cannot mutate the slot, so the save and restore are
skipped for it. Generators go through resume_gen_frame and are
unaffected.

Assisted-by: Claude

* Return a write-through FrameLocalsProxy from frame.f_locals

Optimized (function) frames now expose `f_locals` as a `FrameLocalsProxy`
implementing PEP 667 semantics instead of a cached snapshot dict:

- reads go live through the fast-local slots; each access mints a fresh
  proxy; keys that do not name a fast local are stored in a per-frame
  `f_extra_locals` side dict and folded into `locals()`.
- writes to a fast-local key store into the slot (or its cell) in place;
  deleting a fast local raises ValueError; extra keys delete normally.
- full mapping protocol: keys/values/items (lists), get/pop/setdefault,
  update (dict or FrameLocalsProxy only), __or__/__ior__/__ror__ (dict
  result), copy (plain dict), __reduce__ blocks pickling/copy, repr with
  recursion guard, mapping-pattern and Mapping ABC support.

Class/module/exec frames keep returning their namespace mapping directly.
Cross-thread access to a frame running on another thread still raises
RuntimeError.

A closed generator now keeps its frame locals when a durable frame
reference escaped (f_locals proxy, sys._getframe, f_back), matching
take_ownership; the escape is tracked with a per-frame flag. The
snapshot-then-fold locals_to_fast/locals_dirty write-back is retired
since proxy writes reach the slots directly.

Assisted-by: Claude

* Retain the caller frame so f_back resolves after it returns

When a frame escapes its execution (referenced through a traceback,
`sys._getframe`, `f_locals`, ...), capture a strong reference to its
caller at release time. `f_back` consults it once the caller has left
the live frame chain, so the Python-visible frame chain survives return.
The retained reference is a GC-traversed edge and is cleared by
`frame.clear()`, so ancestor chains stay collectable.

Assisted-by: Claude

* Fix debug-build native stack overflow on deep recursion

Make check_c_stack_overflow one-sided (trip whenever the stack pointer
is below the soft limit) so a single native frame larger than the margin
cannot step past the danger band undetected.

Raise the debug STACK_MARGIN_BYTES from 4096 to 16384 words so the margin
exceeds a single debug interpreter frame, leaving headroom to raise
RecursionError. Release margin unchanged.

Clamp the soft-limit margin to half the stack so small explicit thread
stacks do not get a soft limit above their stack top.

Assisted-by: Claude

* Allocate exception instance __dict__ lazily

Exception construction went through into_ref_with_type, which eagerly
allocated an empty instance dict for every HAS_DICT type. Add
into_ref_with_type_lazy_dict, which builds the instance with an
unallocated dict slot, and route the four exception construction sites
(PyBaseException, PyOSError, OSErrorBuilder, PyBaseExceptionGroup)
through it. The dict now materializes on first attribute write or
__dict__ access via the existing get_or_insert path.

add_note and PyImportError::slot_init now obtain the dict through
object_get_dict so they materialize it instead of assuming it exists.

A freshly constructed exception no longer reports an empty dict in
gc.get_referents, matching the reference interpreter.

Assisted-by: Claude

* Allocate exception __dict__ lazily in vm.new_exception

Route vm.new_exception() through into_ref_with_type_lazy_dict so
internally raised exceptions (new_type_error, new_value_error, etc.)
start without an instance dict, matching the slot_new path. The dict
is materialized on the first attribute write or __dict__ access.

Assisted-by: Claude

* Validate FrameLocalsProxy.update() arguments

Reject keyword arguments and require exactly one positional argument,
raising TypeError with the "takes no keyword arguments" and "takes
exactly one argument (N given)" messages.

Assisted-by: Claude

* Address review nits in frame and faulthandler

- Drop stale vm.frames reference from the release_datastack_frame
  uniqueness argument.
- Assert has_exc_handling when unwinding an Except-typed stack slot,
  documenting the invariant that guards the shared exc_info write.
- Truncate the specialized __init__ return-type name to 200 chars,
  matching the unspecialized wrapper.
- Reword two comments to describe behavior without prose references
  to CPython.

Assisted-by: Claude

* Use scopeguard for start_the_world in faulthandler dump_all_threads

Wrap the unix stop-the-world registry walk in a scope with
scopeguard::defer! so start_the_world runs on panic, matching the
f_back and get_all_current_frames sites. Add scopeguard to the stdlib
dependencies. Also correct the restore_exception doc comment to name
with_frame after the rename.

Assisted-by: Claude

* Gitignore docs/superpowers

Assisted-by: Claude

* Rename type_bases_slot_rebuild.py to builtin_type_bases.py

Match the builtin_* naming convention of extra_tests/snippets.

Assisted-by: Claude

* Apply rustfmt, ruff, and cspell lint fixes

Reformat with rustfmt, fix import spacing in builtin_type_bases.py with
ruff, and add "pointee" to the cspell word list.

Assisted-by: Claude

* Gate unix-only QSBR methods to their call sites

`online`, `drain_all`, and `reset_after_fork` are called only from unix
code (thread attach/detach, post-fork reset), and `offline` from unix
code plus a unit test. Gate them with matching cfg so `-D dead_code`
does not fire on non-unix targets.

Assisted-by: Claude

* Visit the function closure tuple as a GC edge

PyFunction::traverse visited the cells inside the closure tuple instead
of the tuple object itself, so the tuple's reference from the function
was never subtracted during cycle collection. A closure tuple that
reached back to its function (or, through a frame retained by f_back,
to a Thread) was stranded as a false GC root and never collected,
leaking the whole cycle. Visit the tuple itself, matching clear().

Assisted-by: Claude

* Apply formatting hook fix to builtin_type_bases.py

Assisted-by: Claude

* Unmark asyncgen finalization-by-gc tests in test_base_events

test_asyncgen_finalization_by_gc and
test_asyncgen_finalization_by_gc_in_other_thread now pass; GC finalizes
the async generators.

Assisted-by: Claude

* Unmark test_sni_callback_refcycle in test_ssl

The servername-callback reference cycle is now collected by GC.

Assisted-by: Claude

* Widen GC stop-the-world gates from unix-only to all threading builds

Change `cfg(all(unix, feature = "threading"))` to `cfg(feature = "threading")`
on the stop-the-world machinery so it also compiles and runs on non-unix
threading builds:

- StopTheWorldState, its stats, stw_trace, and the stop_the_world field
- ThreadSlot state/stop_requested/thread fields and their initializers
- wait_while_suspended/attach_thread/detach_thread/suspend_if_needed/do_suspend,
  allow_threads, stop_requested_for_current_thread, and the enter_vm /
  VmBootstrapGuard / attach_current_thread / release_current_thread / cleanup
  attach-state wiring
- eval_breaker_tripped, check_signals, run_scheduled_gc, signal GC_BIT /
  schedule_gc / take_gc_scheduled, and the frame.rs safepoint call
- CollectStopTheWorld and its use in collect_inner
- QSBR::online/offline, now called from attach/detach on all threading builds
- debug_assert_current_thread_attached and its type-cache call sites

maybe_collect defers auto-collection to the bytecode safepoint on every
threading build instead of only unix; non-threading builds keep the inline
collect. stw_trace writes to std stderr on non-unix.

top_frame publishing (CURRENT_TOP_FRAME_SLOT, set_current_frame), the
frame-walk debug assert in collect_inner, and the fork reinit helpers remain
unix-only; non-unix keeps ThreadSlot::frames for introspection.

Assisted-by: Claude

* Detach current thread around blocking _winapi/_overlapped waits

Wrap the blocking Windows wait calls in `vm.allow_threads` so the calling
thread transitions ATTACHED -> DETACHED for the duration of the wait:

- _winapi: WaitForSingleObject, WaitForMultipleObjects,
  BatchedWaitForMultipleObjects, ConnectNamedPipe, ReadFile,
  Overlapped.GetOverlappedResult
- _overlapped: Overlapped.getresult

These previously blocked while ATTACHED, so a stop-the-world requester
could never suspend the thread and spun in its wait loop indefinitely.

* Format WaitForMultipleObjects allow_threads closure

* Treat concurrent sni_callback removal as no-op in invoke_sni_callback

* Assert capi refcount on a fresh mortal list instead of the int type object

The refcount test asserted exact incref/decref deltas on PyInt's shared
type object. That object's reference count is perturbed by the other capi
tests running in parallel, and is immortal under some interpreter
configurations, so the deltas were not reliably +1/-1. Assert them on a
freshly created, uniquely owned list whose reference count is private to
the test and mortal.

Assisted-by: Claude

* Traverse and GC-track PyOSError instances

The `#[pyexception]` struct macro now forwards a `traverse` option to the
generated `#[pyclass]`, and `ExceptionItemMeta` accepts the `traverse`
key. `PyOSError` is marked `traverse = "manual"`, so `HAS_TRAVERSE` is
true and OSError-family instances are tracked at creation and traversed
by the collector.

`PyOSError::traverse` now visits the underlying `PyBaseException`
(traceback, cause, context, args) instead of `PyException::try_traverse`,
which was a no-op because `PyException` has `HAS_TRAVERSE = false`.

* Unmark test_blockingioerror in test_io

The BlockingIOError reference cycle is now collected by GC.

Assisted-by: Claude
2026-07-08 15:21:41 +09:00
Jeong, YunWon f26d013032 ctypes: unify the foreign-call path on a single host_env call() API (#8235)
* host_env: add unified high-level `call` foreign-call API

Add a libffi-hiding foreign-call entry point that takes ctypes type codes
and recursive layouts plus raw buffers instead of libffi `Type`/`Arg`, to
become the single call path for the VM `_ctypes` (a later change) and other
consumers. Also bring in the `callproc_simple` helper so this host_env copy
stays byte-identical to the pyre-dev copy during the migration.

- `CTypeLayout` (Simple/Pointer/Struct/Union/Array/Opaque) with `size()` and
  an internal libffi-type lowering built on `ffi_type_for_layout`.
- `CallArg` (Typed/Int/Double/Pointer/Aggregate), `CallRet`
  (Void/Code/Pointer/Aggregate), `CallOptions` (use_errno/use_last_error),
  `CallValue` (Void/Scalar/Pointer/Aggregate), and `CallError`.
- `call(addr, &[CallArg], CallRet, CallOptions) -> Result<CallValue,
  CallError>`, built on the existing `Cif`/`ffi_*` primitives: the errno /
  last-error swap wraps only the raw call, and by-value aggregate arguments
  and returns go through `Cif::call_return_into`.
- 16 ABI unit tests over local `extern "C"` functions: scalar parity,
  by-value struct / nested / array-in-struct / {f32,f32} / large-struct
  arguments, small / odd / large struct returns, union size, the errno
  window, and the null-pointer / unknown-code / short-buffer errors.

`callproc` and `callproc_simple` are left in place; both are removed once the
migration onto `call` completes.

Assisted-by: Claude

* _ctypes: route the VM call path through host_env call()

Replace the VM's direct libffi `Type`/`Arg` marshalling with the unified
host_env `call` entry point. Behavior is preserved on the tested paths:
structs and unions still pass by pointer and struct returns still use the
register-size approximation (passing/returning aggregates by value is a
later change).

- base.rs: `FfiArgValue` → `CArgValue` (Typed{code,bytes}/Int/Double/Pointer)
  with `as_call_arg()`; the paramfunc producers emit `CArgValue`, snapshotting
  buffer bytes at conversion time so no lock is held across the call.
- _ctypes.rs: `CArgObject` carries `value: CArgValue` plus a `keep` slot for
  the from_param z/Z/P null-terminated-copy keepalive that no longer rides in
  the value; `PyCArg` repr reconstructs the scalar for identical output; byref
  updated.
- simple.rs: `to_ffi_value` → `to_carg_value`; from_param emits `CArgValue`
  and its keepalive.
- function.rs: `Argument{value, keep}`; `ArgumentType` yields a `CArgValue`
  (with the "unsupported argument type" check moved up front); `CallInfo`'s
  return fields collapse to `RetSpec` (Void/Pointer/Code) reproducing the exact
  return type and result dispatch; `ctypes_callproc` builds `CallArg`/`CallRet`/
  `CallOptions` and invokes `host_env::ctypes::call`; the errno/last-error swap
  moves into `CallOptions` (the `with_swapped_*` wrappers are removed);
  `convert_raw_result` consumes `CallValue`.
- extra_tests/snippets/stdlib_ctypes_calls.py: libc calls over the live FFI
  path (abs/strlen/sqrt, c_char_p/c_void_p returns, a use_errno round-trip);
  output matches CPython.

Two intentional deltas: a NULL function pointer now raises ValueError instead
of a debug assertion, and a c_char passed positionally without argtypes now
zero-extends via its type code rather than sign-extends via the old tag path,
which also makes it agree with the with-argtypes path.

The old host_env `callproc`/`ffi_*` and `StgInfo`'s libffi field types remain
for now; they are removed when by-value aggregates land.

Assisted-by: Claude

* _ctypes: pass and return structs and unions by value

Flip aggregate arguments and returns from the pointer / register-size
approximation to true by-value passing through the host_env `call` entry
point, and carry the driving layouts as host_env `CTypeLayout`.

- base.rs: `StgInfo.ffi_field_types: Vec<FfiType>` becomes
  `field_layouts: Vec<CTypeLayout>`, still built incrementally from the base
  class so struct inheritance is reflected. `StgInfo::to_ffi_type()` is
  replaced by a `type_layout(ty, &stg, vm)` helper that reads a type's own
  layout (aggregates from `field_layouts`, arrays recurse into the element
  type, simple types from their `_type_` code); it takes the already-borrowed
  `StgInfo` so it never re-locks the type. `CArgValue` gains an
  `Aggregate { layout, bytes }` variant lowering to `CallArg::Aggregate`, and
  `struct_union_paramfunc` snapshots the instance bytes into it (tag 'V').
- structure.rs / union.rs: collect each field's `type_layout` into
  `field_layouts` and store it on the finalized `StgInfo`.
- function.rs: `convert_object` passes a struct/union argument by value
  (snapshot bytes + argtype layout); a `byref()` result is still a pointer.
  `RetSpec` gains `Aggregate(CTypeLayout)`; `compute_ret_spec` returns it for
  a struct/union restype; `ctypes_callproc` lowers it to `CallRet::Aggregate`.
  `convert_raw_result` now drops the restype `StgInfo` read guard before
  constructing the result instance: instance construction write-locks the
  type's `StgInfo` to finalize it, which otherwise self-deadlocks against the
  held read guard (latent since the register-size return path, unreachable
  until a struct was actually returned by value).
- _ctypes.rs: a 'V' cparam now reprs as `<cparam 'V' at 0x..>` (the
  object-address default), matching PyCArg_repr; the aggregate `CArgValue`
  routes through that arm.
- extra_tests/snippets/stdlib_ctypes_byvalue.py: div/imaxdiv struct returns
  (8- and 16-byte), inet_ntoa struct and union arguments, with and without
  argtypes; output matches CPython. Also sorts the imports in the sibling
  stdlib_ctypes_calls.py snippet (ruff isort).

`_pack_` / `_swappedbytes_` layouts stay approximate — `CTypeLayout` carries
no explicit field offsets, as the previous libffi field-type path did not
either. host_env is untouched, so both `ctypes.rs` copies stay byte-identical.

test_ctypes is unchanged at run=322 skipped=58.

Assisted-by: Claude

* host_env: remove the pre-`call` foreign-call scaffolding

With the VM `_ctypes` and pyre both routed through `call`, delete the
foreign-call paths and libffi-type builders that no longer have a consumer:

- `callproc` (the low-level libffi `Vec<Type>` / `&[Arg]` entry) and its
  `CallResult` return type plus `call_result_bytes`.
- `callproc_simple` and its `SimpleArg` / `SimpleRestype` / `SimpleCallError`
  types (the pointer-only slice added for pyre's first cut), and the
  `lookup_function_symbol_addr_str` helper, along with their tests.
- `ffi_type_for_layout` + `CTypeParamKind`, `ffi_type_from_format`,
  `ffi_type_from_tag`, and `ffi_type_for_return_size` — the aggregate/simple
  libffi-type builders the old marshalling used. `call` and `CTypeLayout`
  build their own libffi types from `ffi_type_from_code` and the small
  `ffi_{pointer,byte_struct,repeat,void,i32,f64}_type` helpers, which stay.

`simple_type_chars` stays (still used by pyre's simple-type validation). The
`call` doc no longer references `callproc_simple`. A stale comment in the VM's
result decoder that named `call_result_bytes` is reworded.

host_env drops from 4051 to 3535 lines; the `call` ABI unit tests remain
(24 tests). test_ctypes is unchanged at run=322 skipped=58.

Assisted-by: Claude

* host_env: read `call` scalar returns as a full register, use `add_i32`

`call` read `Code` returns through `low::ffi_arg`. The `libffi_sys`
binding types `ffi_arg` as `c_ulong`, which is 4 bytes under LLP64
(Windows x64), so `low::call` truncated 8-byte returns (`q`/`Q`/`d`) to
the low 4 bytes. `calls_f64_scalar` and `passes_large_struct_by_value`
failed on windows-2025. Read a full register (`u64`) instead;
`decode_type_code` still slices the leading bytes each type code needs.
No change on LP64, where `ffi_arg` is already 8 bytes.

Add `typed_two_scalar_args`, which calls the previously-unused `add_i32`
ABI helper (two-argument scalar path); the helper tripped `-D warnings`
dead-code on clippy.

Assisted-by: Claude

* _ctypes: skip the by-value snippet on Windows

`stdlib_ctypes_byvalue.py` reaches libc through `CDLL(None)` and calls
`div`/`imaxdiv`/`inet_ntoa`, none of which resolve that way on Windows,
so the snippet aborted on windows-2025. Guard it like
`stdlib_ctypes_calls.py`: print "OK" and exit before touching `CDLL`.
The by-value path is covered on Windows by test_ctypes.

Assisted-by: Claude

* _ctypes: keep the converted argument alive for by-value aggregates

The by-value struct/union argument path snapshotted the instance bytes
and returned `None` for the keep-alive slot, dropping the `from_param`
result before the foreign call. When the snapshot embeds pointers into
buffers owned by that object's keep-alive set, the call could read freed
memory. Return the converted instance as the keep-alive owner.

Assisted-by: Claude

* host_env: avoid indexing an empty by-value aggregate buffer in `call`

A zero-sized `Structure`/`Union` argument reaches the aggregate lowering
with `layout.size() == 0` and an empty buffer, which passed the
`buffer.len() < expected` check and then panicked on `&buffer[0]`. Use
`buffer.first().unwrap_or(&0u8)`; libffi reads nothing for a zero-size
type.

Assisted-by: Claude
2026-07-08 12:42:10 +09:00
Jeong, YunWon 55c012cffd unicode crate (#8211)
* Extract unicodedata core into rustpython-unicode crate

Move the vm-free Unicode character database access — the generated UCD 3.2.0 /
latest tables, their build-time generation, and the icu4x/unicode_names2 lookups
for category/bidirectional/combining/east_asian_width/mirrored/decomposition/
normalize/is_normalized/digit/decimal/numeric/name/lookup — into a new leaf crate
over char/CodePoint/&Wtf8. stdlib/unicodedata.rs keeps the UCD pyclass binding: it
extracts the code point, boxes results, and maps errors. The unicode data files,
build.rs table generation, and the icu_properties/icu_normalizer/unicode_names2
dependencies move out of stdlib.

Assisted-by: Claude

* Route str predicates, casefold, and printable through rustpython-unicode

Add classify/case/identifier modules to the shared crate over char/&str/&Wtf8:
isalpha/isalnum/isdecimal/isdigit/isnumeric/isspace/isprintable classification,
XID identifier predicates, and full-mapping casefold. vm/builtins/str.rs and
literal/char.rs now call these instead of icu_properties/icu_casemap directly.
String-level iteration with final-sigma handling (lower/upper/title/capitalize,
islower/isupper) stays in the runtime.

Assisted-by: Claude

* Route sre_engine char classes through rustpython-unicode

Add the regex module with the SRE character-class and case predicates
(is_word/is_space/is_digit, is_uni_* Unicode variants, ascii/locale/unicode case
folding). sre_engine/string.rs now forwards to it, keeping its public API and
behavior identical — including the ASCII-only is_uni_digit and the hardcoded
is_uni_space table.

Assisted-by: Claude

* Route \N{} name lookups through rustpython-unicode

codegen/string_parser.rs (\N{...} escapes) and common/encodings.rs (the
namereplace error handler) now resolve character names via rustpython-unicode
instead of depending on unicode_names2 directly, leaving the crate as the sole
owner of the name database.

Assisted-by: Claude

* Add differential Unicode sweep and shared-crate snippet test

tests/differential.rs sweeps the full 0..0x110000 range and compares each str
classification predicate against a committed CPython 3.14 reference dataset
(tests/data/cpython3.14_predicates.txt, produced by generate_reference.py). Code
points that differ only because the Rust std / icu4x build ships a later Unicode
release than CPython 3.14's 16.0.0 are recorded in
tests/data/version_skew_cpython3.14.txt, regenerable via
RUSTPYTHON_UNICODE_REGEN_SKEW=1; the regen refuses to record any
cpython=true/crate=false divergence, so only newly-assigned code points are
allowed. Any other divergence fails. Both data files use a run-length
`predicate start:end,...` encoding.

extra_tests/snippets/stdlib_unicode_shared.py exercises the routed surface end to
end (str predicates, casefold, identifiers, unicodedata, normalize, \N{}, and re
character classes) and passes identically on CPython 3.14 and RustPython.

Assisted-by: Claude

* Match regex \d to Unicode decimal digits

is_uni_digit previously matched only ASCII 0-9, so re's \d in Unicode mode
missed decimal digits like ٥ and ५. SRE_UNI_IS_DIGIT matches Py_UNICODE_ISDECIMAL
(category Nd), so route it through classify::is_decimal. Unmasks test_bug_6561 in
test_re and extends the shared-crate snippet with the Nd/Nl/No cases.

Assisted-by: Claude

* Replace shallow Unicode wrappers with re-exports

Address review feedback on the extraction.

Functions that only forwarded to the shared crate become `use ... as`
re-exports rather than hand-written wrappers:

- literal: is_printable is dropped; escape.rs calls
  rustpython_unicode::classify::is_repr_printable directly.
- unicode::identifier::is_continue re-exports is_xid_continue.
- unicode::data::lookup_character re-exports unicode_names2::character.
- Drop the unused repr(u8) on DecompositionType.

The SRE character-class and case predicates move back into
sre_engine::string (their pre-extraction home) instead of living in a
unicode::regex module that only sre_engine and the vm _sre binding used;
is_uni_digit/is_uni_alnum still delegate to rustpython_unicode::classify.
engine.rs and _sre consume them from sre_engine::string again.

The unicode crate's tests move from a single root tests module in lib.rs
into per-module test submodules (case, classify, data, identifier,
normalize).

Assisted-by: Claude

* no-std

* Address review feedback: test module, dead variant, WTF-8 normalization

- differential.rs: move the sweep tests into a `mod tests` block and drop
  the file-level allow of clippy::tests_outside_test_module and
  std_instead_of_alloc; the test uses alloc collections instead.
- data.rs: remove the never-constructed DecompositionType::Canonical variant
  and its allow(unused); compatibility decomposition never produces it and
  canonical decomposition is handled through icu4x.
- normalize.rs: is_normalized now takes &Wtf8 and checks each UTF-8 run,
  skipping lone surrogates, matching normalize's run-wise behavior.
- unicodedata.rs: pass as_wtf8() to is_normalized.

Assisted-by: Claude
2026-07-07 09:19:25 +09:00
Kwak Byoung Min 8bdc1cc5fd Fix csv.writer QUOTE_NONE with quotechar=None (#8201)
* Prevent csv QUOTE_NONE writer panics without quotechar

Handle csv.writer rows with QUOTE_NONE through a RustPython-owned unquoted writer path so quotechar=None no longer reaches the unfinished csv_core configuration branch. Escape delimiter, newline, quotechar, and escapechar bytes according to the active dialect, and preserve CPython's single-empty-field error behavior.

Constraint: Match CPython csv.writer behavior without changing Lib/ copied stdlib files.
Rejected: Relying on csv_core QuoteStyle::Never | it does not model CPython QUOTE_NONE escaping with quotechar=None.
Confidence: high
Scope-risk: narrow
Directive: Keep QUOTE_NONE writer behavior separate unless csv_core gains matching CPython semantics.
Tested: prek run --all-files; cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher; cargo build --release --features sqlite; pytest -v in extra_tests
Assisted-by: Codex:gpt-5.5

* Keep csv parity tests aligned with QUOTE_NONE support

Remove the stale RustPython expected-failure marker for the CPython escaped-field writer test that now passes, and cover CR/LF escaping in the snippet regression requested during review.

Constraint: RustPython test policy allows removing expectedFailure markers only when the upstream test passes.

Rejected: Refactoring writer row boilerplate in this follow-up | review marked it as a heavy-lift nitpick and it would broaden the CI fix.

Confidence: high

Scope-risk: narrow

Tested: cargo run --release --features sqlite -- -m test test_csv; cargo run -- extra_tests/snippets/stdlib_csv.py; PATH=/tmp/pyshim:$PATH prek run --all-files; git diff --check; cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher; pytest -v in extra_tests

Assisted-by: Codex:gpt-5.5

* Keep csv quote-style dispatch coherent

Review feedback pointed out that adjacent branches selected behavior from the same quoting discriminator. Use one match so future quote-style additions are routed in a single place.

Constraint: RustPython review requested merging adjacent quote-style checks.
Confidence: high
Scope-risk: narrow
Tested: cargo fmt --check
Tested: target/release/rustpython extra_tests/snippets/stdlib_csv.py
Tested: target/release/rustpython -m test test_csv
Tested: PATH=/tmp/pyshim:$PATH prek run --all-files
Tested: RUST_TEST_THREADS=1 cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher -- --test-threads=1
Tested: cargo clippy --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher --all-targets
Assisted-by: Codex:gpt-5.5
2026-07-05 01:17:46 +09:00
Jeong, YunWon a1ba6a662c Align compiler and AST behavior with CPython (#8138)
* Align compiler and AST behavior with CPython

Update the compiler pipeline, AST module support, and related VM compile/eval paths toward CPython 3.14 behavior.

Use upstream Ruff parser crates directly and keep RustPython-specific syntax preflight handling in the compile path.

Refresh opcode metadata, snapshots, and targeted tests for the aligned bytecode and AST behavior.

* fix

* Fix PR 8138 CI failures

* Fix match mapping wildcard scan complexity

* fixes

* Use Ruff runtime AST fields

* Minimize residual patch diff

* refactor error handling

* Remove _ast conversion context wrappers

* Clean up _ast conversion glue and compiler warning escalation

Rename the Node conversion parameter `ctx` to `vm` throughout the _ast
module.

Remove the unused compile_program, compile_program_single,
compile_block_expression, and compile_expression forwarders; compile_top
stays as the entry point.

Stash an escalated compiler SyntaxWarning so a non-SyntaxWarning category
propagates unchanged instead of being rewritten to SyntaxError, matching
PyErr_ExceptionMatches(SyntaxWarning) in compiler_warn. Drop the now-unused
CompileWarningError::into_codegen_error.

Replace the PositionalArguments two-variant enum with a struct holding a
shared range and a PositionalArgumentsKind enum.

Assisted-by: Claude

* Represent compiler flags as a CompilerFlags bitflags

Replace the loose PY_CF_*/CO_* i32 constants in compile_mode with a
CompilerFlags bitflags covering the PyCF_* flags and __future__
CO_FUTURE_* bits. The Python-visible ast.PyCF_* attribute values are
derived from it via bits(); parser input modes stay plain consts.

builtins::compile and the compile_string flag handling test flags
through CompilerFlags::contains instead of raw bit math.

Assisted-by: Claude

* Fix PR 8138 test regressions

* Fix PR 8138 CI failures

* Avoid shell interpolation in Linux deps action

* Fix review findings in compiler/AST changes

- frame.rs: compute the MATCH_CLASS class name lazily so a successful
  match no longer takes the type name lock or allocates; the
  __match_args__-not-a-tuple branch reuses it instead of recomputing.
- _ast/constant.rs: add the missing leading space to the with_recursion
  label ("maximum recursion depth exceeded during compilation").
- sys.set_int_max_str_digits: restore the "maxdigits must be 0 or larger
  than {n}" error text.
- codegen: set CO_MAXBLOCKS to 20 in both ir.rs and compile.rs.
- _ast/exception.rs: extract the duplicated excepthandler node guard
  into ensure_excepthandler_node.
- codegen: correct the validate_keywords doc comment.
- Drop redundant "CPython" qualifiers from comments added in this branch.

Assisted-by: Claude
2026-06-26 18:22:08 +09:00
Kwak Byoung MinandShahar Naveh 6d25033da6 Support csv writer QUOTE_STRINGS and QUOTE_NOTNULL (#8109)
* Support csv quoting modes added in Python 3.12

Implement writer handling for QUOTE_STRINGS and QUOTE_NOTNULL so the exported constants no longer panic and follow CPython behavior for string, non-null, None, and quotechar validation cases.

Constraint: RustPython contribution policy requires CPython-compatible behavior through Rust-side changes and regression coverage outside Lib/.

Rejected: Marking CPython Lib tests or hiding the constants | would preserve a runtime panic for supported public constants.

Confidence: high

Scope-risk: narrow

Directive: Keep QUOTE_STRINGS and QUOTE_NOTNULL writer behavior aligned with CPython's csv module when extending dialect validation.

Tested: cargo check -p rustpython-stdlib; cargo run --release -- extra_tests/snippets/stdlib_csv.py; cargo run --release -- -m test test_csv; cargo clippy; pre-commit run --all-files via temporary venv/PATH shim; cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher -- --test-threads=1

Not-tested: Remote CI and PR creation were not run because remote git operations require explicit approval.

Assisted-by: Codex:gpt-5.5

* Update crates/stdlib/src/csv.rs

Co-authored-by: Shahar Naveh <50263213+ShaharNaveh@users.noreply.github.com>

* Update crates/stdlib/src/csv.rs

Co-authored-by: Shahar Naveh <50263213+ShaharNaveh@users.noreply.github.com>

* Keep csv writer follow-up lint clean

Apply maintainer-requested expression cleanups and rustfmt wrapping so the PR lint job can pass without changing behavior.

Constraint: GitHub Actions Lint failed on rustfmt output after the review suggestion.

Rejected: Changing csv writer semantics | the failing check was formatting-only and all behavior tests already passed.

Confidence: high

Scope-risk: narrow

Directive: Keep future review suggestions rustfmt-clean before pushing.

Tested: cargo fmt --check; cargo check -p rustpython-stdlib; cargo run --release -- extra_tests/snippets/stdlib_csv.py; cargo run --release -- -m test test_csv; cargo clippy; pre-commit run --all-files; cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher -- --test-threads=1

Not-tested: Remote CI has not rerun yet; this commit will trigger it after push.

Assisted-by: Codex:gpt-5.5

---------

Co-authored-by: Shahar Naveh <50263213+ShaharNaveh@users.noreply.github.com>
2026-06-22 13:17:55 +09:00
Joshua Megnauth 5c1803e019 Fix most of unicodedata; unmask multiple tests (#7947) 2026-06-14 17:47:42 +09:00
Kwak Byoung Min 3492c1cef1 Avoid callable iterator deadlock during sentinel comparison (#8040)
Constraint: Python-level sentinel equality can re-enter the same callable iterator while internal iterator state is protected by a non-reentrant lock.

Rejected: Holding the callable iterator status lock across sentinel equality | user-defined __eq__ can call next() on the same iterator and deadlock.

Confidence: high

Scope-risk: moderate

Tested: pre-commit run --all-files; cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher; cargo build --release --features sqlite; pytest -v in extra_tests; cargo run --quiet -- extra_tests/snippets/protocol_iternext.py; cargo check -p rustpython-vm; cargo clippy -p rustpython-vm --all-targets -- -D warnings; git diff --check

Not-tested: push/PR creation

Assisted-by: Codex:gpt-5.5
2026-06-11 13:38:07 +09:00
copilot-swe-agent[bot] 242e88bde1 Merge main: adopt icu_properties approach, drop unic-ucd-category fallback 2026-06-01 08:50:31 +00:00
Jiseok CHOIandJeong, YunWon 913f8c86f7 sqlite3: fix Blob.__setitem__ value range validation (#7981)
* sqlite3: fix Blob.__setitem__ value range validation

Previously, assigning an out-of-range integer (negative or > 255) or an
integer too large for i64 (e.g. 2**65) to a Blob index raised OverflowError
instead of ValueError.

Mirror CPython's ass_subscript_index logic:
- Convert the value via to_i64(), treating any overflow as -1
- Validate the result is in [0, 255], raising ValueError("byte must be in range(0, 256)") otherwise
- Separate deletion error messages: "item deletion" for index, "slice deletion" for slice

* sqlite3: fix Blob.__setitem__ negative-step slice write

In the step != 1 branch of Blob.ass_subscript, the loop used
  i_in_temp += step as usize
where step is isize. For negative steps (e.g. step = -2),
  (-2isize) as usize = 18446744073709551614
causing an out-of-bounds panic whenever slice_len >= 2.

Fix: use SaturatedSliceIter (already used by the read path) to iterate
over the correct absolute blob indices, then map each index back to a
temp buffer offset via abs_idx - range_start.

Also fix a Clippy lint: replace
  val < 0 || val > 255
with the idiomatic
  !(0..=255).contains(&val)

Add a regression test in extra_tests/snippets/stdlib_sqlite.py that
exercises blob[9:0:-2] (negative step, slice_len=5).

* fix: guard blob negative-step snippet from CPython 3.11 bug

* style: add blank line after import sys in stdlib_sqlite snippet (ruff)

* Update extra_tests/snippets/stdlib_sqlite.py

---------

Co-authored-by: Jeong, YunWon <69878+youknowone@users.noreply.github.com>
2026-05-27 16:40:05 +09:00
James Clarke dd1955c095 Fix thread teardown panic when weakref callback fires during cleanup (#7965) 2026-05-25 13:55:32 +09:00
Ivan Mironov f2e7c8a096 Add missing test for select.select() (#7953)
This is a follow up for https://github.com/RustPython/RustPython/pull/7948
2026-05-24 13:43:56 +09:00
Ivan Mironov dbcd4687b2 Fix panic in select.select() when too many FDs specified (#7948)
Also:

* Add regression test into existing `extra_tests/snippets/stdlib_select.py`
* Stop calculating nfds on Windows as it is ignored there

Panic:

	thread 'main' (189598) panicked at /root/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/libc-0.2.186/src/unix/linux_like/mod.rs:1777:9:
	index out of bounds: the len is 16 but the index is 16
	note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

	thread 'main' (189598) panicked at library/core/src/panicking.rs:225:5:
	panic in a function that cannot unwind
	stack backtrace:
	   0:     0xaaab763a0b88 - <<std[1934960bf7f41d0a]::sys::backtrace::BacktraceLock>::print::DisplayBacktrace as core[f1abae5f1257fe69]::fmt::Display>::fmt
	   1:     0xaaab75590ff0 - core[f1abae5f1257fe69]::fmt::write
	   2:     0xaaab763a94fc - <std[1934960bf7f41d0a]::sys::stdio::unix::Stderr as std[1934960bf7f41d0a]::io::Write>::write_fmt
	   3:     0xaaab7638b714 - std[1934960bf7f41d0a]::panicking::default_hook::{closure#0}
	   4:     0xaaab7639b288 - std[1934960bf7f41d0a]::panicking::default_hook
	   5:     0xaaab7639b478 - std[1934960bf7f41d0a]::panicking::panic_with_hook
	   6:     0xaaab7638b7ec - std[1934960bf7f41d0a]::panicking::panic_handler::{closure#0}
	   7:     0xaaab76382654 - std[1934960bf7f41d0a]::sys::backtrace::__rust_end_short_backtrace::<std[1934960bf7f41d0a]::panicking::panic_handler::{closure#0}, !>
	   8:     0xaaab7638c504 - __rustc[b7425922bef61dcf]::rust_begin_unwind
	   9:     0xaaab754f778c - core[f1abae5f1257fe69]::panicking::panic_nounwind_fmt
	  10:     0xaaab754f7714 - core[f1abae5f1257fe69]::panicking::panic_nounwind
	  11:     0xaaab754f786c - core[f1abae5f1257fe69]::panicking::panic_cannot_unwind
	  12:     0xaaab75a6283c - rustpython_vm::function::builtin::<impl rustpython_vm::function::builtin::sealed::PyNativeFnInternal<(rustpython_vm::function::builtin::OwnedParam<T1>,rustpython_vm::function::builtin::OwnedParam<T2>,rustpython_vm::function::builtin::OwnedParam<T3>,rustpython_vm::function::builtin::OwnedParam<T4>),R,rustpython_vm::vm::VirtualMachine> for F>::call_::h2471c8e242c9b51d
	  13:     0xaaab75db1e68 - rustpython_vm::types::slot::Callable::slot_call::hd1c1ad0ad14f306b
	  14:     0xaaab762c0a50 - rustpython_vm::protocol::callable::PyCallable::invoke::h9f6d571fca351ca6
	  15:     0xaaab75c550e8 - rustpython_vm::protocol::callable::<impl rustpython_vm::object::core::PyObject>::call_with_args::hed1f4a61aba2dced
	  16:     0xaaab762e7c24 - rustpython_vm::frame::ExecutingFrame::execute_call::h0ad3490dd74ed1e3
	  17:     0xaaab762fed40 - rustpython_vm::frame::ExecutingFrame::run::hcf90f0950fc26812
	  18:     0xaaab761e6768 - rustpython_vm::vm::VirtualMachine::with_frame::hd49ba6fcdf2422e2
	  19:     0xaaab75c45398 - rustpython_vm::builtins::function::<impl rustpython_vm::object::core::Py<rustpython_vm::builtins::function::PyFunction>>::invoke_with_locals::h42de3d2316941ce2
	  20:     0xaaab76132a80 - rustpython_vm::builtins::function::vectorcall_function::h7331cb67b334e867
	  21:     0xaaab763369d8 - rustpython_vm::protocol::callable::<impl rustpython_vm::object::core::PyObject>::vectorcall::h9019c5d16685c89a
	  22:     0xaaab762f4b54 - rustpython_vm::frame::ExecutingFrame::execute_call_vectorcall::h120134e11a58c946
	  23:     0xaaab76302a7c - rustpython_vm::frame::ExecutingFrame::run::hcf90f0950fc26812
	  24:     0xaaab761e6768 - rustpython_vm::vm::VirtualMachine::with_frame::hd49ba6fcdf2422e2
	  25:     0xaaab761e7f24 - rustpython_vm::vm::VirtualMachine::run_code_obj::h354618be6e5cc553
	  26:     0xaaab761e2d18 - rustpython_vm::vm::python_run::file_run::<impl rustpython_vm::vm::VirtualMachine>::run_any_file::h783d3127fbc0b523
	  27:     0xaaab757d700c - rustpython::run_rustpython::h354efb8d817cefbf
	  28:     0xaaab757c79e0 - std::thread::local::LocalKey<T>::with::hc9728e249843a926
	  29:     0xaaab757db860 - rustpython_vm::vm::interpreter::Interpreter::run::h42ac1fe9ed2287a2
	  30:     0xaaab757d7b30 - rustpython::run::hf14a209db5b4289c
	  31:     0xaaab757e2eb4 - rustpython::main::h1b59d8e13276ac48
	  32:     0xaaab757e2eec - std::sys::backtrace::__rust_begin_short_backtrace::h47e4b1f073f2155c
	  33:     0xaaab757e2ed4 - std::rt::lang_start::{{closure}}::h663a6c3dc7d80101
	  34:     0xaaab76399fd4 - std[1934960bf7f41d0a]::rt::lang_start_internal
	  35:     0xaaab757e2f44 - main
	  36:     0xfffed057655c - __libc_start_call_main
	  37:     0xfffed057663c - __libc_start_main@@GLIBC_2.34
	  38:     0xaaab755526f0 - _start
	  39:                0x0 - <unknown>
	thread caused non-unwinding panic. aborting.
	Aborted                    (core dumped) cargo run --release -- extra_tests/snippets/stdlib_select.py
2026-05-22 20:10:24 +09:00