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
69 lines
2.1 KiB
Python
69 lines
2.1 KiB
Python
"""The cycle collector has to walk the internal fields of containers and
|
|
iterators.
|
|
|
|
Every type below is built into the cycle
|
|
|
|
node -> node.__dict__ -> wrapper -> container -> node
|
|
|
|
so the only path back to `node` runs through a field of the wrapper. A type
|
|
that reports nothing while being traversed, or reports the objects it iterates
|
|
instead of the iterator it holds, leaves its own reference unaccounted for: the
|
|
cycle is then classified as reachable and `node` is never freed.
|
|
"""
|
|
|
|
import gc
|
|
import itertools
|
|
import weakref
|
|
from collections import defaultdict, deque
|
|
|
|
|
|
class Node:
|
|
pass
|
|
|
|
|
|
def collects(wrap):
|
|
"""Report whether the collector breaks the cycle built around wrap()."""
|
|
|
|
def build():
|
|
container = []
|
|
node = Node()
|
|
container.append(node)
|
|
node.held = wrap(container)
|
|
return weakref.ref(node)
|
|
|
|
gc.collect()
|
|
ref = build()
|
|
gc.collect()
|
|
return ref() is None
|
|
|
|
|
|
# containers keeping their items in a field of their own
|
|
assert collects(deque)
|
|
assert collects(lambda c: defaultdict(int, {"k": c}))
|
|
assert collects(lambda c: classmethod(lambda cls: c))
|
|
|
|
# iterators: the wrapper holds an iterator, and that iterator holds the
|
|
# container
|
|
assert collects(iter)
|
|
assert collects(lambda c: map(str, c))
|
|
assert collects(lambda c: filter(None, c))
|
|
assert collects(lambda c: zip(c))
|
|
assert collects(enumerate)
|
|
assert collects(reversed)
|
|
assert collects(itertools.chain)
|
|
assert collects(itertools.cycle)
|
|
assert collects(lambda c: itertools.islice(c, 5))
|
|
assert collects(itertools.groupby)
|
|
assert collects(itertools.accumulate)
|
|
assert collects(lambda c: itertools.starmap(str, c))
|
|
assert collects(lambda c: itertools.takewhile(bool, c))
|
|
assert collects(lambda c: itertools.dropwhile(bool, c))
|
|
assert collects(lambda c: itertools.filterfalse(None, c))
|
|
assert collects(lambda c: itertools.compress(c, [1]))
|
|
assert collects(lambda c: itertools.product(c))
|
|
assert collects(lambda c: itertools.combinations(c, 1))
|
|
# tee holds its buffer through a second object, which has to be walked too
|
|
assert collects(lambda c: itertools.tee(c)[0])
|
|
|
|
print("ok")
|