@@ -95,6 +95,7 @@ def __init__(
9595 kwargs : dict ,
9696 metadata : TokenMetadata
9797 ):
98+ self .state : TokenState = TokenState .CREATED
9899 self .token_id = token_id
99100 self .func = func
100101 self .args = args
@@ -103,7 +104,6 @@ def __init__(
103104
104105 # State management
105106 self .on_state_change = None
106- self .state = TokenState .CREATED
107107 self ._state_lock = threading .Lock ()
108108
109109 # Result delivery
@@ -115,6 +115,13 @@ def __init__(
115115 self ._kill_requested = threading .Event ()
116116 self ._killed_reason : Optional [str ] = None
117117
118+ def __await__ (self ):
119+ """
120+ Makes this Token awaitable in asyncio loops.
121+ It wraps the underlying thread-safe concurrent.futures.Future.
122+ """
123+ return asyncio .wrap_future (self ._result_future ).__await__ ()
124+
118125 def transition_state (self , new_state : TokenState ) -> bool :
119126 """Attempt a validated lifecycle transition.
120127
@@ -238,6 +245,7 @@ class TokenPool:
238245 a coordinator retrieves and admits the token.
239246 """
240247 def __init__ (self ):
248+ self .state : TokenState = TokenState .CREATED
241249 self .quarantine_mgr = None
242250 self .tokens : Dict [str , TaskToken ] = {}
243251 self ._lock = threading .Lock ()
@@ -450,7 +458,7 @@ def _get_loop():
450458def task_token_guard (
451459 operation_type : str ,
452460 tags : Optional [Dict [str , Any ]] = None ,
453- ) -> Callable [[Callable [[ P ] , R ]], Callable [[ P ] , "TaskToken[R]" ]]:
461+ ) -> Callable [[Callable [P , R ]], Callable [P , "TaskToken[R]" ]]:
454462 """Decorate a callable so calls return TaskToken instead of executing immediately.
455463
456464 The wrapper performs optional code analysis, optional quarantine checks,
@@ -468,9 +476,9 @@ def task_token_guard(
468476 The wrapped callable is not executed at call time. It is captured as a
469477 token-managed task for later admission and execution.
470478 """
471- def decorator (func : Callable [[ P ] , R ]) -> Callable [[ P ], R ]:
479+ def decorator (func : Callable [P , R ]) -> Callable [P , "TaskToken[R]" ]:
472480 @wraps (func )
473- def wrapper (* args : P .args , ** kwargs : P .kwargs ) -> R :
481+ def wrapper (* args : P .args , ** kwargs : P .kwargs ) -> "TaskToken[R]" :
474482 from .code_inspector import CodeInspector
475483 from .spike_detector import TokenQuarantinedException
476484
0 commit comments