← Back to Pull requests

Tag heap references to avoid type-only heap reads #1024

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Oct 12, 2026 07:32 UTC
Author

Motivation

Value::Ref(HeapId) required reading the heap entry to identify an object's type, even for predicates such as is_str and type queries whose answer is fixed for that allocation. Store the heap kind alongside its identity so these queries can avoid the arena lookup and scoped reader dispatch.

Design

  • Represent references as Value::Ref(HeapKind, HeapId). Generate HeapKind from the same payload list as HeapData, and attach known kinds at allocation and reference-construction sites.

  • Reduce HeapId from usize to u32, using checked index conversion. Compile-time assertions keep HeapId at 4 bytes and Value at 16 bytes, including the production WASM32 build.

  • Preserve reference identity, hashing and reference-count behavior. Debug assertions check tags during clone/drop; heap reads still match the actual payload, with no new unsafe projections based on tags.

  • Use tags for fixed Python types, string/callable predicates, and the preliminary checks in type(). Preserve heap reads for payload-dependent types: specialized dictionaries, instances, exceptions, named tuples, hash objects, files and iterator subtypes.

  • Bump the dump version to 14 and regenerate the compatibility fixture for the changed serialized reference representation.

  • Add a regression test for payload-dependent types and scripts/bench_heap_types.py, a standalone Flying Circus stress benchmark with a checked result.
  • Type-specific conversion and collection helpers now filter tags before arena reads. Ordinary iterators skip the file-buffer type read, non-temporal formatting skips temporal probes, and union operands classify directly from tags. HeapData::py_type shares HeapKind::fixed_type instead of duplicating its fixed-type table.

    The representation change and tag-based optimizations are separate commits so they can be evaluated independently.

    Compatibility and capacity limit

    Changing HeapId from usize to u32 reduces the representable arena index range on 64-bit targets to 2³² slots (about 4.29 billion). This limits arena capacity, not cumulative allocations over a session: freed slots can be reused. It is a capacity reduction even though ordinary memory limits are expected to be reached much earlier. Exceeding the index range currently panics at the checked conversion rather than returning a Python resource error. WASM32 already had a 32-bit index range.

    The serialized reference representation also changes. The dump-version bump to 14 makes this snapshot compatibility break explicit; older dumps are not compatible with this version.

    Flying Circus (updated for 68b02136)

    Measured on an Apple M1 Pro, macOS 27. All binaries use cargo build -p monty-runtime --release, fat LTO, one codegen unit and default runtime arguments. Runs were serial, with no concurrent builds. Flying Circus shuffles timing samples across runtimes; workload timings exclude process startup.

    Full suite against origin/main

    The final PR binary was compared with f190cda9 across the full suite plus both stress benchmarks: 20 timing samples per runtime/mode, three repeated warmups, three separate RSS samples and ten startup samples. The run took 14m 31s. There were 34 comparable default workloads, plus the two stress benchmarks.

    Across the 34 default workloads, geometric means of median timing ratios were 2.2% lower one-shot and 3.1% lower repeated. These are descriptive aggregates without aggregate confidence intervals. There were no classified timing or RSS regressions in this run; many individual comparisons remained inconclusive. Three RSS samples provide limited evidence about memory variability.

    Selected repeated-mode results against origin/main:

    | Workload | Main | Final PR | Time reduction | Classification |
    | --- | --- | --- | --- | --- |
    | Capacity planning | 30.72 ms | 29.50 ms | 4.0% | Improvement |
    | Portfolio risk | 61.84 ms | 56.90 ms | 8.0% | Improvement |
    | N-body | 441.33 ms | 420.47 ms | 4.7% | Improvement |
    | Float | 233.77 ms | 224.01 ms | 4.2% | Improvement |
    | JSON parse, medium | 10.08 ms | 8.45 ms | 16.2% | Improvement |
    | JSON transform, medium | 11.93 ms | 10.14 ms | 15.0% | Improvement |
    | JSON lines, medium | 15.22 ms | 13.66 ms | 10.3% | Improvement |
    | Heap type queries | 107.81 ms | 91.23 ms | 15.4% | Improvement |
    | Heap iterator next | 20.76 ms | 18.59 ms | 10.4% | Improvement |

    The fresh-worker next() comparison measured 9.3% lower median time but was inconclusive. Both binaries retained the same two unsupported workloads and two OS-call harness failures (game_regex_dna, game_meteor_contest); there were no compatibility changes. The harness exits nonzero for these existing failures.

    Stress comparisons against intermediate builds

    bench_heap_types.py performs 600,000 type queries on six heap-backed types, with allocation before the hot loop and an asserted checksum. bench_heap_iterator_next.py performs 200,000 next() calls on a single range iterator and verifies the sum and exhausted default. These are focused stress tests, not application workloads.

    A separate run compared representation-only 57ac7663, the earlier optimized build 5b4187e4, and final 68b02136, with 30 samples per runtime/mode and no RSS samples. A second run reversed the final/representation runtime list. All stress comparisons between final and representation-only exclude zero in family-adjusted 95% bootstrap intervals, with no workload failures.

    | Run | Workload / mode | Representation only | Final PR | Time reduction |
    | --- | --- | --- | --- | --- |
    | Forward | Type queries, one-shot | 100.32 ms | 91.39 ms | 8.90% |
    | Forward | Type queries, repeated | 100.27 ms | 91.73 ms | 8.52% |
    | Reverse | Type queries, one-shot | 101.18 ms | 92.05 ms | 9.02% |
    | Reverse | Type queries, repeated | 101.43 ms | 91.46 ms | 9.84% |
    | Forward | Iterator next, one-shot | 19.92 ms | 18.81 ms | 5.55% |
    | Forward | Iterator next, repeated | 19.81 ms | 18.72 ms | 5.48% |
    | Reverse | Iterator next, one-shot | 20.00 ms | 18.98 ms | 5.14% |
    | Reverse | Iterator next, repeated | 19.67 ms | 18.77 ms | 4.59% |

    In the three-runtime run, the earlier optimized build measured 19.53 / 19.34 ms for iterator next (one-shot / repeated), versus 18.81 / 18.72 ms for the final build: another 3.7% / 3.2% lower median time. Type-query medians differed by less than 1% between those optimized builds. The latest fixes improve the targeted iterator path while retaining the earlier type-query gain.

    These runs support local benefits on this machine, not a universal application speedup claim. Original representation-only results and their borderline slowdowns were exploratory; the measurements above use the final PR code.

    Cache identities used for reproduction:

  • Main: @tagged-heap-main-f190cda9 (f190cda9).

  • Representation only: @tagged-heap-candidate-f190cda9 (57ac7663).

  • Earlier optimized: @tagged-heap-optimized-57ac7663 (5b4187e4).

  • Final: @tagged-heap-review-68b02136 (68b02136).
  • Reproduce with locally cached release builds:

    flying-circus --diff --threshold 1 --samples 20 --memory-samples 3 \
      -r main=@tagged-heap-main-f190cda9 -r reviewed=@tagged-heap-review-68b02136 \
      --include-defaults --benchmark scripts/bench_heap_types.py \
      --benchmark scripts/bench_heap_iterator_next.py
    
    flying-circus --diff --threshold 1 --samples 30 --memory-samples 0 \
      -r representation=@tagged-heap-candidate-f190cda9 \
      -r previous=@tagged-heap-optimized-57ac7663 -r reviewed=@tagged-heap-review-68b02136 \
      --benchmark scripts/bench_heap_types.py --benchmark scripts/bench_heap_iterator_next.py
    

    Stress benchmark source

    scripts/bench_heap_types.py:

    """Stress type() on heap values whose Python type is determined by HeapKind.
    
    Run with Flying Circus's --benchmark option. This isolates type queries;
    allocation happens before the hot loop, and the checksum checks every query.
    """
    
    
    def heap_type_queries():
        values = [
            [1, 2, 3],
            tuple([1, 2, 3]),
            set([1, 2, 3]),
            frozenset([1, 2, 3]),
            'heap-' + str(123),
            'heap-bytes'.encode(),
        ]
        expected = [list, tuple, set, frozenset, str, bytes]
        checksum = 0
        for _ in range(100_000):
            for index in range(6):
                checksum += type(values[index]) is expected[index]
        assert checksum == 600_000
        return checksum
    
    
    print(heap_type_queries())
    

    scripts/bench_heap_iterator_next.py:

    """Stress next() on a heap iterator that never needs file-buffer handling.
    
    Run with Flying Circus's --benchmark option. The iterator is allocated once;
    the hot loop exercises the OpenFile tag rejection and checks the final sum.
    """
    
    
    def heap_iterator_next():
        iterator = iter(range(200_000))
        checksum = 0
        for _ in range(200_000):
            checksum += next(iterator)
        assert checksum == 19_999_900_000
        assert next(iterator, None) is None
        return checksum
    
    
    print(heap_iterator_next())
    

    Validation

  • cargo test -p monty --features memory-model-checks: 872 tests passed, including payload-dependent type and tag fast-path regression coverage.

  • cargo run -p monty-datatest --features memory-model-checks -- run_test_cases_monty: 654 passed.

  • cargo clippy -p monty --tests --all-features -- -D warnings passed.

  • cargo check -p monty-wasm-runtime --target wasm32-wasip1 passed.

  • Rust formatting, import checks, Python benchmark Ruff checks and git diff --check passed.
  • The combined Monty/CPython fixture run had eight CPython-side failures; all Monty cases passed. The standalone monty WASM32 check retains an existing HeapData size-budget failure without SmallVec's union feature, also reproduced on unchanged main; the production WASI runtime enables that feature and passes.

    <!-- This is an auto-generated description by cubic. -->
    ---

    Summary by cubic


    Heap references now carry their HeapKind alongside a 32-bit heap ID, so fixed-kind predicates, type queries, and conversion payload reads can avoid reading the heap entry. Payload-dependent type checks still inspect the heap, and heap access remains guarded by matching the actual payload.

  • The latest commit adds file-iterator recognition to the tag fast paths and tightens the tagged value tests around it.

  • The serialized reference format changed, so the dump version is now 14.

  • A focused type-query stress benchmark showed an 8.8–9.4% time reduction; this is not evidence of an application-wide speedup.

  • The 32-bit heap ID caps the arena at 2³² entries; exceeding it currently panics at the checked conversion instead of raising a Python resource error.
  • <sup>Written for commit fd0ea9bf827f002c18c4f14f8e090b749fe7955a. Summary will update on new commits.</sup>

    <a href="https://cubic.dev/pr/pydantic/monty/pull/1024?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

    <!-- End of auto-generated description by cubic. -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jaheba Review duration: 21125m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #1024"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%
    Repository