@@ -20,8 +20,8 @@ use alloc::fmt;
2020use core:: mem:: size_of;
2121use core:: ops:: ControlFlow ;
2222use core:: sync:: atomic:: {
23- AtomicU64 ,
24- Ordering :: { Acquire , Release } ,
23+ AtomicU32 , AtomicU64 ,
24+ Ordering :: { AcqRel , Acquire , Relaxed , Release } ,
2525} ;
2626use num_traits:: ToPrimitive ;
2727
@@ -40,6 +40,24 @@ type EntryIndex = usize;
4040pub ( 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
4563unsafe 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