Introduce VM scopes for temporary Python values

Draft
JA
16d ago
+376-90

vm.scope owns temporary Python values for the duration of a native operation. Borrow a retained value through its
handle, use scope.vm() to continue executing, and use scope.take(handle) when the value transfers to the caller or
a container. The scope releases everything it still owns on exit, including error paths.

  • dict.update and the dict constructor let the scope own their iterators. Synchronous completion registers the
    iterator before it reaches the caller. The short-lived key–value pair stays in a stack guard while its row is checked.
  • dict.get holds both arguments through the lookup and transfers the default out on a miss.
  • issubclass holds its two arguments at the call boundary. Its per-item guards remain in place.

defer_drop! and defer_drop_mut! remain available for explicit cleanup. The argument binding guards stay as they are.

Validation

  • 1,167 Monty tests passed with memory-model and reference-count checks, including nested scope cleanup and ownership transfer.
  • The compile-fail test verifies that an inner scope cannot take an outer scope's handle.
  • 1,572 Monty and CPython fixture runs and all 114 subprocess tests passed.
  • Clippy, Rust formatting, and the import check passed.

Lolek

Same-base release builds, 100 samples per build in each of two orders. Values are changes in repeated median latency.

WorkloadRun 1Run 2
dict.update, integers−0.8%−1.7%
dict.update, heap-backed−1.2%−1.6%
dict.update, rejected row−0.5%+0.3%
dict.get, hits and misses−3.4%−1.8%
issubclass, tuple and union−0.4%+1.3%

Negative values mean lower latency. The repeat was inconclusive for heap-backed dict.update, dict.get, and
issubclass at the benchmark's 1% and 0.01 ms thresholds. One-shot integer and heap-backed dict.update improved by
3.1–4.0% in both orders.


Summary by cubic

Replaces the deferred-drop macros' temporary handling with a VM scope API so Python temporaries are released on every exit path, including ?, early returns, and errors.

  • vm.scope(|scope| ...) keeps raw Values in a small buffer and releases them when the callback exits; scope.take(handle) transfers a value back out so it can be returned or stored.
  • vm.with_args binds native call arguments via generated FromArgs impls and drops their extracted fields, including *args and **kwargs, when the callback returns.
  • Handles carry a lifetime brand tying them to their scope, so taking a value from a different nested scope fails to compile (covered by a new compile-fail test).
  • Migrated dict.get, the dict.update merge paths, unpack_update_pair, issubclass, and print to scopes; the row scope now also guards the unpacked key and value; CallResult::synchronous gains a scope-aware variant.