Skip to content

Commit 33b55c7

Browse files
committed
Share keys-version stamps between dicts with identical layouts
Derive the keys-version stamp from a shape — the ordered interned-key sequence of a hole-free dict — instead of always allocating a unique stamp. Dicts with identical layouts (instances of the same class built by the same __init__) now carry equal stamps, so a LOAD_ATTR cache entry populated by one instance skips the shadow probe for every instance sharing the layout. Shapes are held in a fixed-size lock-free table keyed by interned key addresses; dicts with holes, non-interned keys, or more than 32 keys fall back to dict-unique stamps. Assisted-by: Claude
1 parent 5c75bae commit 33b55c7

2 files changed

Lines changed: 177 additions & 15 deletions

File tree

‎crates/vm/src/dict_inner.rs‎

Lines changed: 126 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,20 @@ type EntryIndex = usize;
4040
pub(crate) struct Dict<T = PyObjectRef> {
4141
inner: PyRwLock<DictInner<T>>,
4242
version: AtomicU64,
43-
/// Keys-version stamp: nonzero values are globally unique per key set,
44-
/// assigned lazily by `assign_keys_version` and invalidated (reset to 0)
45-
/// whenever the key set changes. Value-only updates keep the stamp.
43+
/// Keys-version stamp, assigned lazily by `assign_keys_version` and
44+
/// reset to 0 whenever the key set changes. Value-only updates keep it.
45+
///
46+
/// A nonzero stamp identifies either a *shape* — an exact hole-free
47+
/// entry sequence of interned string keys, shared by every dict with
48+
/// that layout — or, when no shape is derivable, this dict's key set
49+
/// frozen at assignment time. Either way a stamp match guarantees the
50+
/// entry layout is exactly the one the stamp was issued for, so entry
51+
/// indexes cached against a stamp stay valid wherever the stamp matches.
4652
keys_version: AtomicU32,
4753
}
4854

49-
/// Source of keys-version stamps. Stamps are allocated globally so that a
50-
/// nonzero stamp is never shared by two dicts: equal nonzero stamps imply
51-
/// the same dict with an unchanged key set. Stamps are never reused.
55+
/// Source of keys-version stamps. Allocated globally so a shape stamp and a
56+
/// dict-unique stamp can never collide.
5257
static KEYS_VERSION: AtomicU32 = AtomicU32::new(0);
5358

5459
/// Allocate a new keys-version stamp. Returns 0 once the stamp space is
@@ -60,6 +65,85 @@ fn next_keys_version() -> u32 {
6065
.map_or(0, |v| v + 1)
6166
}
6267

68+
/// Largest key count eligible for a shared shape stamp.
69+
const SHAPE_MAX_KEYS: usize = 32;
70+
/// Shape registry slot count (power of two).
71+
const SHAPE_TABLE_SIZE: usize = 1 << 12;
72+
/// Linear-probe limit before giving up on registering a shape.
73+
const SHAPE_MAX_PROBE: usize = 8;
74+
75+
/// A registered shape: the ordered interned-key-pointer sequence of a
76+
/// hole-free dict, plus the stamp shared by every dict with that layout.
77+
/// Interned strings are never freed, so the addresses are stable identities.
78+
struct ShapeData {
79+
keys: Box<[usize]>,
80+
stamp: u32,
81+
}
82+
83+
/// Lock-free registry mapping shapes to shared stamps. Fixed-size open
84+
/// addressing; slots are installed with CAS and never removed, so a stamp
85+
/// permanently means "exactly this entry sequence". Registered `ShapeData`
86+
/// is intentionally leaked (bounded by the table size). Lock-free makes the
87+
/// registry safe across fork() without reinitialization.
88+
static SHAPE_TABLE: std::sync::LazyLock<Box<[core::sync::atomic::AtomicPtr<ShapeData>]>> =
89+
std::sync::LazyLock::new(|| {
90+
(0..SHAPE_TABLE_SIZE)
91+
.map(|_| core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()))
92+
.collect()
93+
});
94+
95+
fn shape_stamp(shape: &[usize]) -> Option<u32> {
96+
use core::sync::atomic::AtomicPtr;
97+
// The hasher seed must be process-stable so equal shapes always probe
98+
// the same slots.
99+
static SHAPE_HASHER: std::sync::LazyLock<rapidhash::quality::RandomState> =
100+
std::sync::LazyLock::new(Default::default);
101+
let hash = {
102+
use core::hash::{BuildHasher, Hash, Hasher};
103+
let mut hasher = SHAPE_HASHER.build_hasher();
104+
shape.hash(&mut hasher);
105+
hasher.finish() as usize
106+
};
107+
let mut candidate: *mut ShapeData = core::ptr::null_mut();
108+
let mut result = None;
109+
for probe in 0..SHAPE_MAX_PROBE {
110+
let slot: &AtomicPtr<ShapeData> = &SHAPE_TABLE[(hash + probe) & (SHAPE_TABLE_SIZE - 1)];
111+
let mut installed = slot.load(Acquire);
112+
if installed.is_null() {
113+
if candidate.is_null() {
114+
let stamp = next_keys_version();
115+
if stamp == 0 {
116+
break;
117+
}
118+
candidate = Box::into_raw(Box::new(ShapeData {
119+
keys: shape.into(),
120+
stamp,
121+
}));
122+
}
123+
match slot.compare_exchange(core::ptr::null_mut(), candidate, AcqRel, Acquire) {
124+
Ok(_) => {
125+
// SAFETY: candidate was just leaked into the table.
126+
result = Some(unsafe { (*candidate).stamp });
127+
candidate = core::ptr::null_mut();
128+
break;
129+
}
130+
Err(current) => installed = current,
131+
}
132+
}
133+
// SAFETY: non-null slots reference leaked ShapeData, never freed.
134+
let data = unsafe { &*installed };
135+
if *data.keys == *shape {
136+
result = Some(data.stamp);
137+
break;
138+
}
139+
}
140+
if !candidate.is_null() {
141+
// SAFETY: the candidate lost the race and was never shared.
142+
drop(unsafe { Box::from_raw(candidate) });
143+
}
144+
result
145+
}
146+
63147
unsafe impl<T: Traverse> Traverse for Dict<T> {
64148
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
65149
self.inner.traverse(tracer_fn);
@@ -299,21 +383,30 @@ impl<T: Clone> Dict<T> {
299383
self.keys_version.load(Acquire)
300384
}
301385

302-
/// Return the current keys-version stamp, assigning a fresh one if none
303-
/// is set. Returns 0 only if the global stamp space is exhausted.
386+
/// Return the current keys-version stamp, assigning one if none is set.
387+
/// Returns 0 only if no stamp could be allocated.
388+
///
389+
/// When the dict is hole-free and all keys are interned strings, the
390+
/// stamp is the *shared shape stamp* for that exact key sequence, so
391+
/// dicts with identical layouts (e.g. instances of the same class built
392+
/// by the same `__init__`) carry equal stamps and one cached stamp or
393+
/// entry index serves them all. Otherwise a dict-unique stamp is used.
304394
///
305-
/// A caller that wants to prove a key absent must call this *before*
306-
/// probing: "stamp still equals V" then implies the key set is unchanged
307-
/// since before the probe. This is safe against concurrent key-set
308-
/// changes because their reset trails the mutation (see
309-
/// `bump_version_keys_changed`): a stamp installed during a change is
310-
/// retired by that trailing reset before it could ever match again.
395+
/// The shape inspection and the stamp install happen under the inner
396+
/// read lock. Key-set changes reset the stamp under the write lock, so
397+
/// an installed stamp always attests the layout it was derived from.
311398
pub(crate) fn assign_keys_version(&self) -> u32 {
312399
let version = self.keys_version.load(Acquire);
313400
if version != 0 {
314401
return version;
315402
}
316-
let new_version = next_keys_version();
403+
let inner = self.read();
404+
// Re-check under the lock: a concurrent assign may have won.
405+
let version = self.keys_version.load(Acquire);
406+
if version != 0 {
407+
return version;
408+
}
409+
let new_version = Self::derive_shape_stamp(&inner).unwrap_or_else(next_keys_version);
317410
if new_version == 0 {
318411
return 0;
319412
}
@@ -327,6 +420,24 @@ impl<T: Clone> Dict<T> {
327420
}
328421
}
329422

423+
/// Compute the shared shape stamp for the current layout, if it
424+
/// qualifies: hole-free entries, bounded size, all keys interned strings.
425+
fn derive_shape_stamp(inner: &DictInner<T>) -> Option<u32> {
426+
if inner.entries.len() != inner.used || inner.used > SHAPE_MAX_KEYS {
427+
return None;
428+
}
429+
let shape = inner
430+
.entries
431+
.iter()
432+
.map(|entry| {
433+
let key = &entry.as_ref()?.key;
434+
key.is_interned()
435+
.then(|| key.as_ref() as *const PyObject as usize)
436+
})
437+
.collect::<Option<Vec<usize>>>()?;
438+
shape_stamp(&shape)
439+
}
440+
330441
/// Reset the keys-version stamp on a key-set change (insert of a new
331442
/// key, deletion, or clear). Value-only updates keep the stamp.
332443
///

‎extra_tests/snippets/vm_specialization.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,3 +156,54 @@ def store_hint_survives_dict_replacement():
156156

157157

158158
store_hint_survives_dict_replacement()
159+
160+
161+
## Shared shape stamps: same-layout instances share the shadow-check stamp
162+
163+
164+
class ShapedCounter:
165+
def __init__(self):
166+
self.a = 1
167+
self.b = 2
168+
169+
def m(self):
170+
return "method"
171+
172+
173+
def shape_sharing_shadow_one_instance():
174+
objs = [ShapedCounter() for _ in range(30)]
175+
for _ in range(300):
176+
for o in objs:
177+
assert o.m() == "method"
178+
objs[13].m = lambda: "thirteen"
179+
for i, o in enumerate(objs):
180+
expected = "thirteen" if i == 13 else "method"
181+
assert o.m() == expected
182+
del objs[13].m
183+
for o in objs:
184+
assert o.m() == "method"
185+
186+
187+
shape_sharing_shadow_one_instance()
188+
189+
190+
def holey_dict_falls_back():
191+
class Holey:
192+
def m(self):
193+
return "g"
194+
195+
g1, g2 = Holey(), Holey()
196+
for o in (g1, g2):
197+
o.x = 1
198+
o.y = 2
199+
o.z = 3
200+
del o.y # leaves a hole in the entries
201+
for _ in range(300):
202+
assert g1.m() == "g"
203+
assert g2.m() == "g"
204+
g2.m = lambda: "g2"
205+
assert g1.m() == "g"
206+
assert g2.m() == "g2"
207+
208+
209+
holey_dict_falls_back()

0 commit comments

Comments
 (0)