Allow `list`, `tuple`, `...` constructors to suspend

JA
4d ago
+1071-274

Collection constructors currently raise NotImplementedError when a custom iterator, generator, or unread file needs a host call while it is being consumed. For example, list(open(path)) and shlex.split(open(path)) fail on an unread file.

Allow list, tuple, set, frozenset, dict, bytes, deque, Counter, and defaultdict constructors to suspend while iterating. Keep synchronous paths for known safe inputs; the other paths use frozen frames that survive session dumps. Set insertion, dict pair validation, byte conversion, and counting happen as items arrive so errors stop the source before it advances again. Synchronous callbacks within these operations retain their existing limitations.

Tuple and frozenset construction use temporary mutable collections; bytes construction uses a temporary byte buffer.

Tests:

  • cargo test -p monty --features memory-model-checks
  • Monty fixture suite with memory-model-checks (831 passed)
  • Collection suspension cases against CPython, including incremental errors and dump/restore
  • cargo clippy -p monty --all-targets --features memory-model-checks -- -D warnings

Related: #1416, #1475.


Summary by cubic

list(), tuple(), set(), frozenset(), dict(), bytes(), collections.deque(), collections.Counter(), and collections.defaultdict() constructors now suspend while consuming iterables that need host calls, so patterns like list(open(path)) work on unread files instead of raising NotImplementedError.

  • Fast synchronous paths run first — native iterables flagged sync_iterable, dict sources, and exact-type passthroughs (tuples, frozensets, bytes) never enter a Python frame. map and filter callbacks can now suspend when driven by a collection constructor, for, or functools.reduce(); sorted(), sum, and itertools adaptors still cannot.
  • Suspension uses frozen frames that survive session dumps; insertion, pair validation, byte conversion, and counting run item-by-item so errors stop the source before it advances again. tuple(), frozenset(), and bytes() build through temporary mutable collections on the suspendable path. New tests cover incremental errors and dump/restore for every constructor.
  • Adds a test-hooks-gated list._sync() so tests can keep exercising synchronous collection now that list() suspends; CI enables the test-hooks feature, and the pyattrs macro accepts #[cfg]-gated attributes.