1414
1515import functools
1616import contextlib
17- from contextvars import ContextVar
17+ import threading
1818from typing import Dict , Optional , Any
1919
2020
@@ -48,33 +48,20 @@ def inner(self):
4848 return property (inner )
4949
5050
51- # 1. The ContextVar (Default is None)
52- # This replaces threading.local with the async-safe standard.
53- generation_cache : ContextVar [Optional [Dict [Any , Any ]]] = ContextVar (
54- "generation_cache" , default = None
55- )
56-
57- # Optimization: Bind .get for speed
58- _get_cache = generation_cache .get
51+ # Thread-local storage for the simple cache dictionary
52+ _thread_local = threading .local ()
5953
6054
6155@contextlib .contextmanager
6256def generation_cache_context ():
63- """Context manager to explicitly manage the cache lifecycle.
64-
65- Usage:
66- with generation_cache_context():
67- # Cache is active (fast)
68- ...
69- """
70- # Initialize: Create a new dictionary and set it in the ContextVar
71- token = generation_cache .set ({})
57+ """Context manager to explicitly manage the cache lifecycle."""
58+ # Initialize the cache as a standard dictionary
59+ _thread_local .cache = {}
7260 try :
7361 yield
7462 finally :
75- # Cleanup: Reset the ContextVar to its previous state (None)
76- # This allows the dictionary to be garbage collected.
77- generation_cache .reset (token )
63+ # Delete the dictionary to free all memory and pinned objects
64+ del _thread_local .cache
7865
7966
8067def cached_proto_context (func ):
@@ -84,7 +71,7 @@ def cached_proto_context(func):
8471 def wrapper (self , * , collisions , ** kwargs ):
8572 # 1. Initialize cache if not provided (handles the root call case)
8673
87- context_cache = _get_cache ( )
74+ context_cache = getattr ( _thread_local , "cache" , None )
8875 if context_cache is None :
8976 return func (self , collisions = collisions , ** kwargs )
9077
0 commit comments