@@ -171,13 +171,29 @@ async def _wait_with_stall_detection(
171171 timeout : float | None ,
172172 stall_timeout : float ,
173173 ) -> None :
174- """Poll for result with heartbeat-based stall detection."""
174+ """Wait for the result with heartbeat-based stall detection.
175+
176+ Uses the backend's blocking ``get_result`` (long-poll on HTTP
177+ backends) in bounded slices, with a heartbeat check between
178+ slices. The slice length is derived from ``stall_timeout`` so
179+ we still detect a silent worker in time.
180+ """
175181 deadline = None if timeout is None else time .monotonic () + timeout
182+ slice_seconds = max (1.0 , min (stall_timeout / 2 , 30.0 ))
176183 last_hb_value : float | None = None
177184 last_hb_change : float | None = None
178185
179186 while True :
180- raw = await self ._backend .try_get_result (self ._task_id )
187+ remaining = None if deadline is None else deadline - time .monotonic ()
188+ if remaining is not None and remaining <= 0 :
189+ raise TimeoutError (
190+ f"Timed out waiting for result of task { self ._task_id } "
191+ )
192+ wait_for = slice_seconds if remaining is None else min (slice_seconds , remaining )
193+ try :
194+ raw = await self ._backend .get_result (self ._task_id , timeout = wait_for )
195+ except TimeoutError :
196+ raw = None
181197 if raw is not None :
182198 self ._envelope = ResultEnvelope .from_json (raw )
183199 logger .debug (
@@ -186,14 +202,6 @@ async def _wait_with_stall_detection(
186202 )
187203 return
188204
189- if deadline is not None :
190- remaining = deadline - time .monotonic ()
191- if remaining <= 0 :
192- raise TimeoutError (
193- f"Timed out waiting for result of task { self ._task_id } "
194- )
195-
196- logger .debug ("Polling heartbeat for task %s" , self ._task_id [:8 ])
197205 hb = await self ._backend .get_heartbeat (self ._task_id )
198206 now = time .monotonic ()
199207 if hb is not None and hb != last_hb_value :
@@ -206,8 +214,6 @@ async def _wait_with_stall_detection(
206214 f"{ elapsed :.1f} s (threshold: { stall_timeout } s)"
207215 )
208216
209- await asyncio .sleep (1.0 )
210-
211217 def __await__ (self ) -> Generator [Any , None , Any ]:
212218 """Allow ``await result`` as shorthand for ``await result.result()``."""
213219 return self .result ().__await__ ()
0 commit comments