Skip to content

Commit 5c75bae

Browse files
committed
Use dict keys-version stamps and entry-index hints in attr specializations
Add a keys-version stamp to Dict: a globally unique u32 assigned lazily and reset on any key-set change (new key, deletion, clear). Value-only updates keep the stamp. - LoadAttrMethodWithValues / LoadAttrNondescriptorWithValues: cache the instance dict's stamp in the pointer cache and skip the shadow probe while the stamp matches. - LoadAttrWithHint: cache the entry index at specialization time; a hit is an identity check on the entry key instead of a hash probe, with self-refresh on miss. - StoreAttrWithHint / StoreAttrInstanceValue: replace values through the cached entry index via set_item_with_hint. Fixes youknowone#42 Assisted-by: Claude
1 parent dd9bce5 commit 5c75bae

5 files changed

Lines changed: 385 additions & 40 deletions

File tree

‎crates/compiler-core/src/bytecode.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -776,12 +776,15 @@ impl CodeUnits {
776776
/// Store a pointer-sized value atomically in the pointer cache at `index`.
777777
///
778778
/// Uses a single `AtomicUsize` store to prevent torn writes when
779-
/// multiple threads specialize the same instruction concurrently.
779+
/// multiple threads specialize the same instruction concurrently. The
780+
/// tear-free width also makes this the right slot for non-pointer guard
781+
/// values (e.g. dict keys-version stamps) that must never be observed
782+
/// half-written.
780783
///
781784
/// # Safety
782785
/// - `index` must be in bounds.
783-
/// - `value` must be `0` or a valid `*const PyObject` encoded as `usize`.
784-
/// - Callers must follow the cache invalidation/upgrade protocol:
786+
/// - When the slot holds a `*const PyObject` encoded as `usize` (or `0`),
787+
/// callers must follow the cache invalidation/upgrade protocol:
785788
/// invalidate the version guard before writing and publish the new
786789
/// version after writing.
787790
pub unsafe fn write_cache_ptr(&self, index: usize, value: usize) {

‎crates/vm/src/builtins/dict.rs‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,63 @@ impl Py<PyDict> {
753753
}
754754
}
755755

756+
/// Lookup trying a cached entry index hint first.
757+
///
758+
/// When the hint misses but the key is present, also returns a refreshed
759+
/// hint (`None` when the hint hit or no hint is representable).
760+
pub(crate) fn get_item_opt_refresh_hint<K: DictKey + ?Sized>(
761+
&self,
762+
key: &K,
763+
hint: u16,
764+
vm: &VirtualMachine,
765+
) -> PyResult<Option<(PyObjectRef, Option<u16>)>> {
766+
if self.exact_dict(vm) {
767+
if let Some(value) = self.entries.get_hint(vm, key, usize::from(hint))? {
768+
return Ok(Some((value, None)));
769+
}
770+
self.entries.get_with_hint(vm, key)
771+
} else {
772+
Ok(self.get_item_opt(key, vm)?.map(|value| (value, None)))
773+
}
774+
}
775+
776+
/// Store using a cached entry index hint for the value-replace fast path.
777+
///
778+
/// Returns a refreshed hint for the key when the hinted slot was vacant
779+
/// (`None` otherwise).
780+
pub(crate) fn set_item_with_hint<K: DictKey + ?Sized>(
781+
&self,
782+
key: &K,
783+
hint: u16,
784+
value: PyObjectRef,
785+
vm: &VirtualMachine,
786+
) -> PyResult<Option<u16>> {
787+
if self.exact_dict(vm) {
788+
self.entries
789+
.insert_with_hint(vm, key, usize::from(hint), value)
790+
} else {
791+
self.as_object().set_item(key, value, vm)?;
792+
Ok(None)
793+
}
794+
}
795+
796+
/// Current keys-version stamp of the underlying storage (0 if unset).
797+
pub(crate) fn keys_version(&self) -> u32 {
798+
self.entries.keys_version()
799+
}
800+
801+
/// Current keys-version stamp, assigning one if none is set.
802+
///
803+
/// Returns 0 for dict subclasses: their lookup can be overridden, so a
804+
/// key-set attestation on the raw storage must never be cached for them.
805+
pub(crate) fn assign_keys_version(&self, vm: &VirtualMachine) -> u32 {
806+
if self.exact_dict(vm) {
807+
self.entries.assign_keys_version()
808+
} else {
809+
0
810+
}
811+
}
812+
756813
pub fn get_item<K: DictKey + ?Sized>(&self, key: &K, vm: &VirtualMachine) -> PyResult {
757814
if self.exact_dict(vm) {
758815
self.inner_getitem(key, vm)

‎crates/vm/src/dict_inner.rs‎

Lines changed: 136 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ use alloc::fmt;
2020
use core::mem::size_of;
2121
use core::ops::ControlFlow;
2222
use core::sync::atomic::{
23-
AtomicU64,
24-
Ordering::{Acquire, Release},
23+
AtomicU32, AtomicU64,
24+
Ordering::{AcqRel, Acquire, Relaxed, Release},
2525
};
2626
use num_traits::ToPrimitive;
2727

@@ -40,6 +40,24 @@ 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.
46+
keys_version: AtomicU32,
47+
}
48+
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.
52+
static KEYS_VERSION: AtomicU32 = AtomicU32::new(0);
53+
54+
/// Allocate a new keys-version stamp. Returns 0 once the stamp space is
55+
/// exhausted; stamps are only allocated on specialization, so exhaustion is
56+
/// unrealistic in practice.
57+
fn next_keys_version() -> u32 {
58+
KEYS_VERSION
59+
.fetch_update(Relaxed, Relaxed, |v| v.checked_add(1))
60+
.map_or(0, |v| v + 1)
4361
}
4462

4563
unsafe impl<T: Traverse> Traverse for Dict<T> {
@@ -105,6 +123,7 @@ impl<T: Clone> Clone for Dict<T> {
105123
Self {
106124
inner: PyRwLock::new(self.inner.read().clone()),
107125
version: AtomicU64::new(0),
126+
keys_version: AtomicU32::new(0),
108127
}
109128
}
110129
}
@@ -119,6 +138,7 @@ impl<T> Default for Dict<T> {
119138
entries: Vec::new(),
120139
}),
121140
version: AtomicU64::new(0),
141+
keys_version: AtomicU32::new(0),
122142
}
123143
}
124144
}
@@ -272,6 +292,56 @@ impl<T: Clone> Dict<T> {
272292
self.version.fetch_add(1, Release);
273293
}
274294

295+
/// Current keys-version stamp, or 0 if none has been assigned since the
296+
/// last key-set change. Equal nonzero stamps guarantee an unchanged key
297+
/// set (values may differ).
298+
pub(crate) fn keys_version(&self) -> u32 {
299+
self.keys_version.load(Acquire)
300+
}
301+
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.
304+
///
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.
311+
pub(crate) fn assign_keys_version(&self) -> u32 {
312+
let version = self.keys_version.load(Acquire);
313+
if version != 0 {
314+
return version;
315+
}
316+
let new_version = next_keys_version();
317+
if new_version == 0 {
318+
return 0;
319+
}
320+
// Only install over 0 so an already-valid stamp is never replaced.
321+
match self
322+
.keys_version
323+
.compare_exchange(0, new_version, AcqRel, Acquire)
324+
{
325+
Ok(_) => new_version,
326+
Err(current) => current,
327+
}
328+
}
329+
330+
/// Reset the keys-version stamp on a key-set change (insert of a new
331+
/// key, deletion, or clear). Value-only updates keep the stamp.
332+
///
333+
/// Must be called while holding the write lock, *before* the key set is
334+
/// modified: a lock-free stamp reader that still observes the old stamp
335+
/// then provably ran before the change became visible, so acting on the
336+
/// old key set is linearizable. A stamp assigned concurrently (between
337+
/// this reset and the mutation) can only be trusted by a caller whose
338+
/// subsequent probe serializes after the mutation through the inner
339+
/// lock, which then reflects the new key set. Since stamps are never
340+
/// reused, a cached stamp can never spuriously match again.
341+
fn invalidate_keys_version(&self) {
342+
self.keys_version.store(0, Release);
343+
}
344+
275345
fn read(&self) -> PyRwLockReadGuard<'_, DictInner<T>> {
276346
self.inner.read()
277347
}
@@ -320,6 +390,7 @@ impl<T: Clone> Dict<T> {
320390
// Dict was resized since lookup, retry
321391
continue;
322392
}
393+
self.invalidate_keys_version();
323394
inner.unchecked_push(index_index, hash, key.to_pyobject(vm), value, entry_index);
324395
self.bump_version();
325396
break None;
@@ -366,6 +437,62 @@ impl<T: Clone> Dict<T> {
366437
Ok(u16::try_from(index).ok())
367438
}
368439

440+
/// Retrieve a key along with its entry index, for hint caching.
441+
///
442+
/// Same as [`Self::get`], but on a hit also returns the entry index
443+
/// usable as a `hint` for [`Self::get_hint`] (`None` if it doesn't fit).
444+
pub(crate) fn get_with_hint<K: DictKey + ?Sized>(
445+
&self,
446+
vm: &VirtualMachine,
447+
key: &K,
448+
) -> PyResult<Option<(T, Option<u16>)>> {
449+
let hash = key.key_hash(vm)?;
450+
let ret = loop {
451+
let (entry, index_index) = self.lookup(vm, key, hash, None)?;
452+
if let Some(index) = entry.index() {
453+
let inner = self.read();
454+
if let Some(entry) = inner.get_entry_checked(index, index_index) {
455+
// The dict was not changed since we did lookup
456+
break Some((entry.value.clone(), u16::try_from(index).ok()));
457+
}
458+
// The dict was changed since we did lookup. Let's try again.
459+
} else {
460+
break None;
461+
}
462+
};
463+
Ok(ret)
464+
}
465+
466+
/// Replace the value at entry index `hint` if that entry's key is
467+
/// identical to `key`, otherwise fall back to a full probing store.
468+
///
469+
/// On a hint miss, returns a refreshed hint for the key (`None` when the
470+
/// hint hit or no hint is representable).
471+
pub(crate) fn insert_with_hint<K: DictKey + ?Sized>(
472+
&self,
473+
vm: &VirtualMachine,
474+
key: &K,
475+
hint: usize,
476+
value: T,
477+
) -> PyResult<Option<u16>> {
478+
let value = {
479+
let mut inner = self.write();
480+
match inner.entries.get_mut(hint) {
481+
Some(Some(entry)) if key.key_is(&entry.key) => {
482+
let removed = core::mem::replace(&mut entry.value, value);
483+
self.bump_version();
484+
drop(inner);
485+
// defer dec RC until after the lock is released
486+
drop(removed);
487+
return Ok(None);
488+
}
489+
_ => value,
490+
}
491+
};
492+
self.insert(vm, key, value)?;
493+
self.hint_for_key(vm, key)
494+
}
495+
369496
/// Fast path lookup using a cached entry index (`hint`).
370497
///
371498
/// Returns `None` if the hint is stale or the key no longer matches.
@@ -433,6 +560,7 @@ impl<T: Clone> Dict<T> {
433560
pub(crate) fn clear(&self) {
434561
let _removed = {
435562
let mut inner = self.write();
563+
self.invalidate_keys_version();
436564
inner.indices.clear();
437565
inner.indices.resize(8, IndexEntry::FREE);
438566
inner.used = 0;
@@ -521,6 +649,7 @@ impl<T: Clone> Dict<T> {
521649
if inner.indices.get(index_index) != Some(&entry) {
522650
continue;
523651
}
652+
self.invalidate_keys_version();
524653
inner.unchecked_push(index_index, hash, key.to_owned(), value, entry);
525654
self.bump_version();
526655
break None;
@@ -551,6 +680,7 @@ impl<T: Clone> Dict<T> {
551680
let value = default
552681
.take()
553682
.expect("default must only be computed on insertion")();
683+
self.invalidate_keys_version();
554684
inner.unchecked_push(
555685
index_index,
556686
hash,
@@ -594,6 +724,7 @@ impl<T: Clone> Dict<T> {
594724
.expect("default must only be computed on insertion")();
595725
let key_obj = key.to_pyobject(vm);
596726
let ret = (key_obj.clone(), value.clone());
727+
self.invalidate_keys_version();
597728
inner.unchecked_push(index_index, hash, key_obj, value, index_entry);
598729
self.bump_version();
599730
return Ok(ret);
@@ -787,6 +918,7 @@ impl<T: Clone> Dict<T> {
787918
// The dict was changed since we did lookup. Let's try again.
788919
_ => return Ok(ControlFlow::Continue(())),
789920
}
921+
self.invalidate_keys_version();
790922
*unsafe {
791923
// index_index is result of lookup
792924
inner.indices.get_unchecked_mut(index_index)
@@ -822,6 +954,7 @@ impl<T: Clone> Dict<T> {
822954
break entry;
823955
}
824956
};
957+
self.invalidate_keys_version();
825958
inner.used -= 1;
826959
*unsafe {
827960
// entry.index always refers valid index
@@ -843,6 +976,7 @@ impl<T: Clone> Dict<T> {
843976
/// This is used for circular reference resolution in GC.
844977
/// Requires &mut self to avoid lock contention.
845978
pub(crate) fn drain_entries(&mut self) -> impl Iterator<Item = (PyObjectRef, T)> + '_ {
979+
self.keys_version.store(0, Release);
846980
let inner = self.inner.get_mut();
847981
inner.used = 0;
848982
inner.filled = 0;

0 commit comments

Comments
 (0)