Reduce MutableProxy per-element overhead and cache per-field proxies

Closed
AL
2mo ago
+88-7

Linear: ENG-10094

Description

  • MutableProxy._wrap_recursive walked 5 stack frames (_is_called_from_dataclasses_internal) for every element retrieved through a proxy, before the cheap is_mutable_type check that usually decides nothing needs wrapping. The checks are reordered so immutable elements (the common case: ints, strings in a proxied list) skip the frame walk entirely. The dataclasses-internal check still runs for mutable values, preserving dataclasses.asdict/astuple behavior.
  • BaseState._get_attribute constructed a fresh MutableProxy on every read of a mutable state var. The proxy is now cached per instance and field name, invalidated by identity when the underlying value is reassigned. The cache is excluded from pickling (__getstate__), and copy/deepcopy already round-trip through __getstate__, so copies never share or carry proxies.

One deliberate nuance: when _wrap_recursive receives an already-proxied value and is called from dataclasses internals, it now returns the unwrapped value (previously the still-wrapped proxy), matching the documented intent of that path.

Benchmarks (GitHub Actions runner, run, 2 passes each)

Casemainthis PRspeedup
iterate 1000-int list via proxy0.977 / 0.973 ms0.219 / 0.214 ms~4.5x
index 1000 elements via proxy1.204 / 1.171 ms0.396 / 0.381 ms~3.0x
read mutable var attribute2.82 / 2.87 us1.17 / 1.15 us~2.4x

cProfile (20 iterations + 2000 attr reads): _is_called_from_dataclasses_internal (20,000 calls, 0.028s cumulative) disappears from the profile; total function calls drop from 168k to 72k.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
    • tests/units/istate/test_proxy.py: proxy reused across reads and invalidated on reassignment; cache never serialized (pickle round-trip rebinds proxies to the restored state); iteration yields plain immutables while mutable elements stay wrapped.
  • Have you successfully ran tests with your changes locally?

šŸ¤– Generated with Claude Code

https://claude.ai/code/session_01G8cXh3TUbNtbjm2ERqE62X


Generated by Claude Code