mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-29 03:04:38 +08:00
* _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
73 lines
1.8 KiB
Python
73 lines
1.8 KiB
Python
"""Stress contextvars from several threads at once.
|
|
|
|
A Context holds the variable map, and both the map and the per-variable cache
|
|
are shared between every thread that touches the Context. Reading and writing
|
|
them has to be done under a lock rather than a cell borrow.
|
|
|
|
Dropping a value that a set() or reset() displaced can run a __del__ that comes
|
|
straight back into the same Context, so the displaced value has to be released
|
|
after the lock is, not while it is held.
|
|
"""
|
|
|
|
import contextvars
|
|
import threading
|
|
|
|
ROUNDS = 2000
|
|
|
|
var = contextvars.ContextVar("v", default=0)
|
|
shared = contextvars.Context()
|
|
errors = []
|
|
|
|
|
|
class Reentrant:
|
|
"""__del__ runs while the variable that held this value is being replaced."""
|
|
|
|
def __del__(self):
|
|
try:
|
|
var.get()
|
|
except Exception: # a different context, or no value: not what is tested
|
|
pass
|
|
|
|
|
|
def churn():
|
|
try:
|
|
for i in range(ROUNDS):
|
|
token = var.set(Reentrant())
|
|
var.get()
|
|
var.reset(token)
|
|
var.set(i)
|
|
var.get()
|
|
contextvars.copy_context()
|
|
except Exception as exc: # noqa: BLE001
|
|
errors.append(exc)
|
|
|
|
|
|
def run_in_shared():
|
|
for i in range(ROUNDS):
|
|
try:
|
|
shared.run(var.set, i)
|
|
except RuntimeError:
|
|
# the Context is already entered by another thread
|
|
pass
|
|
|
|
|
|
threads = [threading.Thread(target=churn) for _ in range(4)]
|
|
threads += [threading.Thread(target=run_in_shared) for _ in range(4)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join()
|
|
|
|
assert not errors, errors
|
|
|
|
# the map itself still behaves
|
|
ctx = contextvars.copy_context()
|
|
ctx.run(var.set, 42)
|
|
assert ctx[var] == 42
|
|
assert var in ctx
|
|
assert list(ctx) == [var]
|
|
assert ctx.get(var) == 42
|
|
assert len(ctx) == 1
|
|
|
|
print("ok")
|