Introduce VM scopes for temporary Python values
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.updateand 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.getholds both arguments through the lookup and transfers the default out on a miss.issubclassholds 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.
| Workload | Run 1 | Run 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 rawValues 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_argsbinds native call arguments via generatedFromArgsimpls and drops their extracted fields, including*argsand**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, thedict.updatemerge paths,unpack_update_pair,issubclass, andprintto scopes; the row scope now also guards the unpacked key and value;CallResult::synchronousgains a scope-aware variant.