@@ -503,6 +503,8 @@ unsafe impl Traverse for PyCData {
503503#[ derive( Debug , Default ) ]
504504struct PrivateRefs {
505505 writer_prune_remaining : usize ,
506+ // Exact-key hints only: these IDs never own or reconstruct Python objects.
507+ object_index : Option < Box < ObjectIndex > > ,
506508 // A registration cache, not a backing owner; do not copy it with values.
507509 writer_paths : Option < WriterPaths > ,
508510 // Views are temporary; retain their caches on the same root as KeepRef.
@@ -532,6 +534,7 @@ unsafe impl Traverse for PrivateRefs {
532534 }
533535 }
534536 fn clear ( & mut self , out : & mut Vec < PyObjectRef > ) {
537+ self . object_index = None ;
535538 self . slots . clear ( ) ;
536539 out. extend ( self . owners . drain ( ) . map ( |( _, ( owner, _) ) | owner) ) ;
537540 for paths in self
@@ -585,7 +588,7 @@ impl PrivateRefs {
585588 }
586589}
587590
588- #[ derive( Clone , Debug ) ]
591+ #[ derive( Clone , Debug , PartialEq , Eq , PartialOrd , Ord , Hash ) ]
589592enum WriterKey {
590593 String ( String ) ,
591594 Id ( usize ) ,
@@ -602,6 +605,85 @@ struct WriterLink {
602605 keys : Vec < WriterKey > ,
603606}
604607
608+ // Index direct retention entries, including duplicate values, without retaining
609+ // their keys or values as Python objects. Native writes update a warmed index.
610+ #[ derive( Debug ) ]
611+ struct ObjectIndex {
612+ dictionary : usize ,
613+ slots : std:: collections:: HashMap < WriterKey , usize > ,
614+ values : std:: collections:: HashMap < usize , ObjectKeys > ,
615+ }
616+
617+ impl ObjectIndex {
618+ fn set ( & mut self , key : WriterKey , value : Option < usize > ) {
619+ if let Some ( old) = self . slots . remove ( & key) {
620+ let keys = self . values . get_mut ( & old) . expect ( "indexed retention slot" ) ;
621+ if keys. remove ( & key) {
622+ self . values . remove ( & old) ;
623+ }
624+ }
625+ if let Some ( value) = value {
626+ self . slots . insert ( key. clone ( ) , value) ;
627+ match self . values . entry ( value) {
628+ std:: collections:: hash_map:: Entry :: Occupied ( mut entry) => {
629+ entry. get_mut ( ) . insert ( key)
630+ }
631+ std:: collections:: hash_map:: Entry :: Vacant ( entry) => {
632+ entry. insert ( ObjectKeys :: One ( key) ) ;
633+ }
634+ }
635+ }
636+ }
637+ }
638+
639+ // Most referents occur once. Allocate a tree only for duplicate keys, whose
640+ // removal must not require scanning all other references to the same object.
641+ #[ derive( Debug ) ]
642+ enum ObjectKeys {
643+ One ( WriterKey ) ,
644+ Many ( alloc:: collections:: BTreeSet < WriterKey > ) ,
645+ }
646+
647+ impl ObjectKeys {
648+ fn insert ( & mut self , key : WriterKey ) {
649+ match self {
650+ Self :: One ( old) if * old == key => { }
651+ Self :: One ( old) => * self = Self :: Many ( [ old. clone ( ) , key] . into ( ) ) ,
652+ Self :: Many ( keys) => {
653+ keys. insert ( key) ;
654+ }
655+ }
656+ }
657+
658+ // Return true when the last key was removed.
659+ fn remove ( & mut self , key : & WriterKey ) -> bool {
660+ match self {
661+ Self :: One ( old) => old == key,
662+ Self :: Many ( keys) => {
663+ keys. remove ( key) ;
664+ if keys. len ( ) == 1 {
665+ * self = Self :: One ( keys. pop_first ( ) . unwrap ( ) ) ;
666+ }
667+ false
668+ }
669+ }
670+ }
671+
672+ fn first ( & self ) -> & WriterKey {
673+ match self {
674+ Self :: One ( key) => key,
675+ Self :: Many ( keys) => keys. first ( ) . expect ( "nonempty retention keys" ) ,
676+ }
677+ }
678+
679+ fn len ( & self ) -> usize {
680+ match self {
681+ Self :: One ( _) => 1 ,
682+ Self :: Many ( keys) => keys. len ( ) ,
683+ }
684+ }
685+ }
686+
605687// Retention metadata is user-mutable. Its fast lookup must not call Python
606688// equality on a colliding key; non-exact string keys use the graph fallback.
607689struct ObjectKey < ' a > ( & ' a str ) ;
@@ -1170,8 +1252,9 @@ impl PyCData {
11701252 if let Some ( dict_obj) = dict_obj
11711253 && let Some ( dict) = dict_obj. downcast_ref :: < PyDict > ( )
11721254 {
1173- let key_obj: PyObjectRef = vm. ctx . new_str ( key) . into ( ) ;
1255+ let key_obj: PyObjectRef = vm. ctx . new_str ( key. as_str ( ) ) . into ( ) ;
11741256 dict. set_item ( & * key_obj, keep, vm) ?;
1257+ self . update_object_index ( dict, & key, vm) ?;
11751258 }
11761259
11771260 Ok ( ( ) )
@@ -1260,6 +1343,9 @@ impl PyCData {
12601343 {
12611344 let key_obj: PyObjectRef = vm. ctx . new_str ( key) . into ( ) ;
12621345 dict. set_item ( & * key_obj, value, vm) ?;
1346+ obj. downcast_ref :: < Self > ( )
1347+ . unwrap ( )
1348+ . update_object_index ( dict, key, vm) ?;
12631349 }
12641350
12651351 Ok ( ( ) )
@@ -1696,7 +1782,7 @@ impl PyCData {
16961782 valid = false ;
16971783 break ;
16981784 } ;
1699- let Some ( root) = Self :: storage_root ( & source, address, size) else {
1785+ let Some ( root) = Self :: overlapping_storage_root ( & source, address, size) else {
17001786 continue ;
17011787 } ;
17021788 // Resurrection may have cleared the registry's weakref even
@@ -1719,7 +1805,7 @@ impl PyCData {
17191805 for ( root, path) in targets {
17201806 if root
17211807 . downcast_ref :: < Self > ( )
1722- . is_some_and ( |root| root. contains_storage ( address, size) )
1808+ . is_some_and ( |root| root. overlaps_storage ( address, size) )
17231809 {
17241810 Self :: register_writer ( & root, pointer, vm) ?;
17251811 target = Some ( root) ;
@@ -1758,9 +1844,10 @@ impl PyCData {
17581844 if !visited. insert ( obj. get_id ( ) ) {
17591845 continue ;
17601846 }
1761- if let Some ( root) = Self :: storage_root ( & obj, address, size) {
1847+ if let Some ( root) = Self :: overlapping_storage_root ( & obj, address, size) {
17621848 Self :: register_writer ( & root, pointer, vm) ?;
1763- let owned = !root. downcast_ref :: < Self > ( ) . unwrap ( ) . is_borrowed ( ) ;
1849+ let storage = root. downcast_ref :: < Self > ( ) . unwrap ( ) ;
1850+ let owned = !storage. is_borrowed ( ) && storage. contains_storage ( address, size) ;
17641851 target = Some ( root) ;
17651852 if owned {
17661853 continue ;
@@ -1787,7 +1874,7 @@ impl PyCData {
17871874 . and_then ( |obj| obj. downcast_ref :: < PyDict > ( ) )
17881875 {
17891876 dict. inner_getitem_opt ( & ObjectKey ( key) , vm) ?
1790- . and_then ( |owner| Self :: storage_root ( & owner, address, size) )
1877+ . and_then ( |owner| Self :: overlapping_storage_root ( & owner, address, size) )
17911878 } else {
17921879 None
17931880 } ;
@@ -1875,13 +1962,35 @@ impl PyCData {
18751962 Ok ( ( ) )
18761963 }
18771964
1878- fn storage_root ( obj : & PyObject , address : usize , size : usize ) -> Option < PyObjectRef > {
1965+ fn overlapping_storage_root (
1966+ obj : & PyObject ,
1967+ address : usize ,
1968+ size : usize ,
1969+ ) -> Option < PyObjectRef > {
18791970 let root = Self :: find_root_object ( obj) ;
18801971 root. downcast_ref :: < Self > ( )
1881- . is_some_and ( |storage| storage. contains_storage ( address, size) )
1972+ . is_some_and ( |storage| storage. overlaps_storage ( address, size) )
18821973 . then_some ( root)
18831974 }
18841975
1976+ // Register every affected reader, even if the assignment is wider than its
1977+ // view. This is provenance bookkeeping, not validation of the native write.
1978+ fn overlaps_storage ( & self , address : usize , size : usize ) -> bool {
1979+ let buffer = self . buffer . read ( ) ;
1980+ let start = buffer. as_ptr ( ) as usize ;
1981+ self . base
1982+ . read ( )
1983+ . as_ref ( )
1984+ . is_none_or ( |base| base. downcast_ref :: < Self > ( ) . is_none ( ) )
1985+ && size != 0
1986+ && !buffer. is_empty ( )
1987+ && if address >= start {
1988+ address - start < buffer. len ( )
1989+ } else {
1990+ start - address < size
1991+ }
1992+ }
1993+
18851994 fn contains_storage ( & self , address : usize , size : usize ) -> bool {
18861995 let buffer = self . buffer . read ( ) ;
18871996 self . base
@@ -1903,7 +2012,7 @@ impl PyCData {
19032012 size : usize ,
19042013 vm : & VirtualMachine ,
19052014 ) -> PyResult < Option < PyObjectRef > > {
1906- let Some ( mut storage) = Self :: storage_root ( writer, address, size) else {
2015+ let Some ( mut storage) = Self :: overlapping_storage_root ( writer, address, size) else {
19072016 return Ok ( None ) ;
19082017 } ;
19092018 if !storage. downcast_ref :: < Self > ( ) . unwrap ( ) . is_borrowed ( ) {
@@ -1916,7 +2025,7 @@ impl PyCData {
19162025 return Ok ( Some ( storage) ) ;
19172026 }
19182027 if let Some ( cdata) = source. downcast_ref :: < Self > ( ) {
1919- let Some ( root) = Self :: storage_root ( & source, address, size) else {
2028+ let Some ( root) = Self :: overlapping_storage_root ( & source, address, size) else {
19202029 // A buffer view can be based on a pointer whose contents
19212030 // require the regular cast/contents provenance search.
19222031 return Ok ( None ) ;
@@ -1970,6 +2079,139 @@ impl PyCData {
19702079 Ok ( None )
19712080 }
19722081
2082+ fn update_object_index (
2083+ & self ,
2084+ dict : & Py < PyDict > ,
2085+ key : & str ,
2086+ vm : & VirtualMachine ,
2087+ ) -> PyResult < ( ) > {
2088+ if self . kept_refs . read ( ) . as_ref ( ) . is_none_or ( |refs| {
2089+ refs. object_index
2090+ . as_ref ( )
2091+ . is_none_or ( |index| index. dictionary != dict. get_id ( ) )
2092+ } ) {
2093+ return Ok ( ( ) ) ;
2094+ }
2095+ // set_item can run a displaced owner's finalizer. Observe the value
2096+ // after reentry, rather than publishing the outer assignment's value.
2097+ let value = dict. inner_getitem_opt ( & ObjectKey ( key) , vm) ?;
2098+ let len = dict. entries . len ( ) ;
2099+ let mut refs = self . kept_refs . write ( ) ;
2100+ if let Some ( refs) = refs. as_mut ( )
2101+ && let Some ( index) = refs. object_index . as_mut ( )
2102+ && index. dictionary == dict. get_id ( )
2103+ {
2104+ index. set (
2105+ WriterKey :: String ( key. to_owned ( ) ) ,
2106+ value. as_ref ( ) . map ( |v| v. get_id ( ) ) ,
2107+ ) ;
2108+ // Direct user edits can remove keys without passing through KeepRef.
2109+ // Bound obsolete hints instead of accumulating assignment history.
2110+ if index. slots . len ( ) > len. saturating_mul ( 2 ) . saturating_add ( 64 ) {
2111+ refs. object_index = None ;
2112+ }
2113+ }
2114+ drop ( refs) ;
2115+ drop ( value) ;
2116+ Ok ( ( ) )
2117+ }
2118+
2119+ fn indexed_object ( & self , address : usize , vm : & VirtualMachine ) -> PyResult < Option < PyObjectRef > > {
2120+ // Private owners already have an identity index; do not snapshot them
2121+ // merely to find a single retained object.
2122+ let private = self
2123+ . kept_refs
2124+ . read ( )
2125+ . as_ref ( )
2126+ . and_then ( |refs| refs. owners . get ( & address) . map ( |( value, _) | value. clone ( ) ) ) ;
2127+ if let Some ( value) = private {
2128+ return Ok ( Some ( value) ) ;
2129+ }
2130+ let objects = self . objects . read ( ) . clone ( ) ;
2131+ let Some ( dict) = objects
2132+ . as_ref ( )
2133+ . and_then ( |obj| obj. downcast_ref :: < PyDict > ( ) )
2134+ else {
2135+ return Ok ( None ) ;
2136+ } ;
2137+ let build = self . kept_refs . read ( ) . as_ref ( ) . is_none_or ( |refs| {
2138+ refs. object_index
2139+ . as_ref ( )
2140+ . is_none_or ( |index| index. dictionary != dict. get_id ( ) )
2141+ } ) ;
2142+ if build {
2143+ let mut index = ObjectIndex {
2144+ dictionary : dict. get_id ( ) ,
2145+ slots : Default :: default ( ) ,
2146+ values : Default :: default ( ) ,
2147+ } ;
2148+ // No metadata lock while snapshots release Python references.
2149+ for ( key, value) in dict. items_vec ( ) {
2150+ let key = if let Some ( key) = key
2151+ . downcast_ref_if_exact :: < PyStr > ( vm)
2152+ . and_then ( |key| key. as_wtf8 ( ) . as_str ( ) . ok ( ) )
2153+ {
2154+ WriterKey :: String ( key. to_owned ( ) )
2155+ } else if let Some ( key) = key
2156+ . downcast_ref_if_exact :: < PyInt > ( vm)
2157+ . and_then ( |key| key. as_bigint ( ) . to_usize ( ) )
2158+ {
2159+ WriterKey :: Id ( key)
2160+ } else {
2161+ continue ;
2162+ } ;
2163+ index. set ( key, Some ( value. get_id ( ) ) ) ;
2164+ }
2165+ self . kept_refs
2166+ . write ( )
2167+ . get_or_insert_with ( Default :: default)
2168+ . object_index = Some ( Box :: new ( index) ) ;
2169+ }
2170+ let attempts = self
2171+ . kept_refs
2172+ . read ( )
2173+ . as_ref ( )
2174+ . and_then ( |refs| refs. object_index . as_ref ( ) )
2175+ . filter ( |index| index. dictionary == dict. get_id ( ) )
2176+ . and_then ( |index| index. values . get ( & address) )
2177+ . map_or ( 0 , ObjectKeys :: len) ;
2178+ // Concurrent writers can reinsert stale hints. Bound retries and fall
2179+ // back to the ordinary graph search rather than spinning in the cache.
2180+ for _ in 0 ..attempts {
2181+ let key = self
2182+ . kept_refs
2183+ . read ( )
2184+ . as_ref ( )
2185+ . and_then ( |refs| refs. object_index . as_ref ( ) )
2186+ . filter ( |index| index. dictionary == dict. get_id ( ) )
2187+ . and_then ( |index| index. values . get ( & address) . map ( |keys| keys. first ( ) . clone ( ) ) ) ;
2188+ let Some ( key) = key else { return Ok ( None ) } ;
2189+ let value = match & key {
2190+ WriterKey :: String ( key) => dict. inner_getitem_opt ( & ObjectKey ( key) , vm) ?,
2191+ WriterKey :: Id ( key) => dict. inner_getitem_opt ( & ObjectIdKey ( * key) , vm) ?,
2192+ WriterKey :: Index ( _) => unreachable ! ( "dictionary retention key" ) ,
2193+ } ;
2194+ // A concurrent write or direct _objects mutation may stale a hint.
2195+ // Only the current dictionary reference can establish ownership.
2196+ if value
2197+ . as_ref ( )
2198+ . is_some_and ( |value| value. get_id ( ) == address)
2199+ {
2200+ return Ok ( value) ;
2201+ }
2202+ let mut refs = self . kept_refs . write ( ) ;
2203+ if let Some ( index) = refs. as_mut ( ) . and_then ( |refs| refs. object_index . as_mut ( ) )
2204+ && index. dictionary == dict. get_id ( )
2205+ && index. slots . get ( & key) == Some ( & address)
2206+ {
2207+ index. set ( key, value. as_ref ( ) . map ( |value| value. get_id ( ) ) ) ;
2208+ }
2209+ drop ( refs) ;
2210+ drop ( value) ;
2211+ }
2212+ Ok ( None )
2213+ }
2214+
19732215 // Resolve a py_object through owned references, never by turning an
19742216 // arbitrary integer from native memory into a Rust reference. Views can
19752217 // reach the object through nested _objects dictionaries or cast cycles.
@@ -2030,6 +2272,11 @@ impl PyCData {
20302272 if !visited. insert ( obj. get_id ( ) ) {
20312273 continue ;
20322274 }
2275+ if let Some ( cdata) = obj. downcast_ref :: < Self > ( )
2276+ && let Some ( value) = cdata. indexed_object ( address, vm) ?
2277+ {
2278+ return Ok ( value) ;
2279+ }
20332280 Self :: provenance_children ( & obj, & mut pending) ;
20342281 }
20352282 Err ( vm. new_value_error ( "PyObject is NULL" ) )
0 commit comments