Tag heap references to avoid type-only heap reads

JA
7d ago
+1707-1338

Store each heap value’s native kind alongside its full-width arena index in Value::Ref(HeapKind, HeapId). Checking whether a value is a list can match Value::Ref(HeapKind::List, _) without reading the arena. Types whose Python identity depends on payload data still consult the payload.

Construction and reads

  • Value::allocate(payload, heap) takes its tag and storage representation from the payload registry. For example, Value::allocate(range, vm.heap) stores the range inline in the slot, and Value::allocate(m, heap) boxes a regex match.
  • Type-only checks match the tag directly. value.get_as::<Slice>(vm.heap) checks the tag and borrows the payload. value.read_as::<List>(vm.heap) returns a typed reader for operations that mutate the object or call back into the VM.
  • value.as_bytes(vm) and value.as_long_int(vm) borrow either interned or heap-backed data. Set and frozenset operations share a reader for their common storage.

Layout and dumps

HeapId wraps a full usize, including usize::MAX. The single-field wrapper uses #[repr(Rust, packed(4))] to give all heap IDs four-byte alignment on 64-bit targets. Value retains its 15-byte inline strings and its compile-time 16-byte size assertion. Heap access uses the existing checked projections.

Dump version 18 writes tagged references. When loading supported dumps from versions 13–17, the loader recovers each reference’s tag from its saved heap slot.

Release benchmarks

After #1421 merged, compared the tagged implementation at 44c86d10 with main at 78cb6ac8 on arm64 macOS with Rust 1.100.0. Each workload ran three warmup pairs and 40 measured pairs. Each round randomized the workload and binary order and verified the results. Times exclude startup and setup. The change is the paired median difference in elapsed time, with a per-workload 95% bootstrap interval.

WorkloadMain median (ms)PR median (ms)Change vs main
Heap type queries70.71263.438-10.32% [-10.46, -10.23]
Mixed heap comparisons41.85540.001-4.73% [-4.86, -4.31]
Range iterator next()10.47410.558+0.11% [-1.14, +1.04]
List +=8.9298.707-2.26% [-2.87, -1.88]
JSON round trip5.2305.259+0.83% [+0.07, +1.01]
Integer loop control4.7804.769+0.02% [-1.94, +1.78]
Set, frozenset and dict-keys equality5.9966.167+2.87% [+2.56, +3.18]
Slicing lists, tuples and bytes10.15110.021-1.10% [-2.05, -0.41]
Before merging #1421, at `5eb2b86f`

Compared 5eb2b86f with its main baseline c5099ea3 and the previous PR head b8eea12e on arm64 macOS. Each workload ran three warmup rounds followed by 40 measured rounds. Each round shuffled workload and binary order and checked every result. A fourth binary, the initial cleanup at 47c2341c, ran in the same rounds. The set workload checks set/frozenset equality in both directions and dict-keys/frozenset equality 25,000 times. The slice workload applies one slice to a list, tuple and bytes 25,000 times. Elapsed time excludes process startup and setup. Negative changes indicate faster execution. Brackets give the 95% paired bootstrap interval for the median change.

WorkloadPR median (ms)Change vs mainChange vs previous PR head
Heap type queries64.965-8.2% [-8.4, -7.9]-1.2% [-1.6, -0.9]
Mixed heap comparisons40.440-3.3% [-4.0, -3.2]+2.2% [+1.8, +2.8]
Range iterator next()10.723+4.3% [+2.8, +5.3]+2.3% [+1.4, +2.7]
JSON round trip5.263-0.4% [-0.8, -0.0]+0.9% [+0.5, +1.6]
List extend8.705-1.9% [-2.3, -1.7]-0.6% [-1.3, +0.1]
Integer control4.802+1.1% [+0.2, +3.2]-0.3% [-2.6, +1.3]
Set, frozenset and dict-keys equality6.156+3.0% [+2.7, +3.4]+3.8% [+3.6, +4.1]
Slicing lists, tuples and bytes10.136+0.0% [-0.4, +0.4]+0.5% [-0.1, +1.3]
Earlier release benchmarks at `b4606107`

Compared the branch at b4606107 with its main baseline eeeb2a6f on arm64 macOS using Rust 1.100.0. Each run used three warmup pairs and 50 measured pairs per workload. The runs used different seeds to randomize workload order and binary order within each pair. Timing begins inside the interpreter after setup, and each sample verifies its checksum. Percentages are paired median changes in elapsed time. Intervals are per-workload 95% bootstrap intervals.

WorkloadRun 1 main / PR median (ms)Run 1 change [interval]Run 2 main / PR median (ms)Run 2 change [interval]
Heap type queries69.652 / 63.926−8.16% [−8.64, −7.95]69.456 / 63.800−8.29% [−8.41, −8.06]
Mixed heap comparisons42.344 / 39.862−5.84% [−6.03, −5.52]42.249 / 39.796−5.70% [−6.21, −5.26]
Range iterator next()10.667 / 10.460−1.87% [−2.56, −1.09]10.759 / 10.331−3.51% [−4.30, −2.88]
List +=8.960 / 8.785−1.92% [−2.33, −1.35]8.910 / 8.742−1.27% [−2.06, −0.77]
JSON round trip5.255 / 5.232−0.31% [−0.57, −0.20]5.256 / 5.255+0.14% [−0.19, +0.35]
Integer loop control4.760 / 4.920+3.57% [+2.19, +4.19]4.741 / 4.920+3.66% [+2.53, +4.91]

The integer control performs 300,000 modulo-and-add iterations. Its slowdown was reproducible on b4606107 and sensitive to native code placement. In 100 paired runs, moving three unrelated functions at link time reduced the gap against main from +4.88% to +1.90%. With both binaries warmed up, the same relink changed +4.39% to −0.80%. Both links used the same compiled objects. The JSON workload gave mixed results.

Local validation

At 44c86d10, 1,239 Rust tests passed with memory-model-checks and three were ignored. All 812 Monty Python fixtures passed. Clippy, formatting, the import check and the 32-bit WASI check passed.

Historical Flying Circus measurements on the earlier base

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:

WorkloadMainFinal PRTime reductionClassification
Capacity planning30.72 ms29.50 ms4.0%Improvement
Portfolio risk61.84 ms56.90 ms8.0%Improvement
N-body441.33 ms420.47 ms4.7%Improvement
Float233.77 ms224.01 ms4.2%Improvement
JSON parse, medium10.08 ms8.45 ms16.2%Improvement
JSON transform, medium11.93 ms10.14 ms15.0%Improvement
JSON lines, medium15.22 ms13.66 ms10.3%Improvement
Heap type queries107.81 ms91.23 ms15.4%Improvement
Heap iterator next20.76 ms18.59 ms10.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.

RunWorkload / modeRepresentation onlyFinal PRTime reduction
ForwardType queries, one-shot100.32 ms91.39 ms8.90%
ForwardType queries, repeated100.27 ms91.73 ms8.52%
ReverseType queries, one-shot101.18 ms92.05 ms9.02%
ReverseType queries, repeated101.43 ms91.46 ms9.84%
ForwardIterator next, one-shot19.92 ms18.81 ms5.55%
ForwardIterator next, repeated19.81 ms18.72 ms5.48%
ReverseIterator next, one-shot20.00 ms18.98 ms5.14%
ReverseIterator next, repeated19.67 ms18.77 ms4.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())