11"""The existing same-Session FIFO, preparation and recovery consumer."""
22from collections import deque
3- from collections .abc import Callable , Iterator
3+ from collections .abc import Callable , Iterator , Mapping
44from contextlib import contextmanager
5+ from dataclasses import dataclass
6+ import logging
7+ import math
58import os
69from pathlib import Path
710from typing import Any , Literal
1013from ...chat_store import CHAT_SESSION_MODE_ATTACHED , TERMINAL_TURN_STATES , scheduled_task_completion_request
1114
1215STEWARD_MAX_CONCURRENT_LANES_DEFAULT = 12
16+ STEWARD_FAST_LANE_RESERVED_DEFAULT = 4
17+
18+ LaneClass = Literal ["fast" , "slow" ]
1319
1420
1521def _resolve_steward_max_concurrent_lanes (controller : Any ) -> int :
@@ -24,6 +30,46 @@ def _resolve_steward_max_concurrent_lanes(controller: Any) -> int:
2430 return STEWARD_MAX_CONCURRENT_LANES_DEFAULT
2531
2632
33+ def _resolve_steward_fast_lane_reserved_slots (controller : Any , limit : int ) -> int :
34+ if limit <= 1 :
35+ return 0
36+ max_reservable = limit - 1
37+ configured = getattr (controller , "steward_fast_lane_reserved_slots" , None )
38+ if isinstance (configured , int ) and not isinstance (configured , bool ) and configured >= 0 :
39+ return min (configured , max_reservable )
40+ raw_env = os .environ .get ("LOOPX_STEWARD_FAST_LANE_RESERVED_SLOTS" , "" ).strip ()
41+ if raw_env .isdigit ():
42+ return min (int (raw_env ), max_reservable )
43+ return min (STEWARD_FAST_LANE_RESERVED_DEFAULT , max_reservable , max (1 , limit // 3 ))
44+
45+
46+ def _resolve_steward_foreground_soft_timeout_sec (controller : Any ) -> float | None :
47+ configured = getattr (controller , "steward_foreground_soft_timeout_sec" , None )
48+ if configured is not None :
49+ if isinstance (configured , bool ) or not isinstance (configured , (int , float )):
50+ return None
51+ val = float (configured )
52+ return val if math .isfinite (val ) and val > 0 else None
53+ raw_env = os .environ .get ("LOOPX_STEWARD_FOREGROUND_SOFT_TIMEOUT_SECONDS" , "" ).strip ()
54+ if raw_env :
55+ try :
56+ val = float (raw_env )
57+ except ValueError :
58+ return None
59+ return val if math .isfinite (val ) and val > 0 else None
60+ return None
61+
62+
63+ @dataclass (slots = True )
64+ class _StewardSlotLease :
65+ """Single-use ownership handle for an acquired Steward lane concurrency slot."""
66+
67+ ticket : int
68+ lane : LaneClass
69+ released : bool = False
70+ handed_off : bool = False
71+
72+
2773class _StewardLaneWaitAborted (Exception ):
2874 """Signal that a waiting Steward Topic Lane was closed or cancelled."""
2975
@@ -33,60 +79,120 @@ def __init__(self, reason: Literal["closed", "cancelled"]) -> None:
3379
3480
3581class _StewardLaneLimiter :
36- """FIFO concurrency gate for active upstream Steward Topic Lanes ."""
82+ """FIFO fast/slow-isolated concurrency gate for active upstream Steward lanes ."""
3783
3884 def __init__ (self ) -> None :
3985 self ._condition = threading .Condition ()
4086 self ._waiters : deque [int ] = deque ()
87+ self ._waiter_lanes : dict [int , LaneClass ] = {}
4188 self ._next_ticket = 0
4289 self ._active_count = 0
90+ self ._fast_active = 0
91+ self ._slow_active = 0
4392
4493 def notify_all (self ) -> None :
4594 """Wake queued Steward Topic Lanes after limit or cancellation changes."""
4695 with self ._condition :
4796 self ._condition .notify_all ()
4897
98+ def _slot_available_locked (self , lane : LaneClass , limit : int , reserved_fast : int ) -> bool :
99+ if self ._active_count >= limit :
100+ return False
101+ if lane == "fast" :
102+ return True
103+ slow_limit = max (0 , limit - reserved_fast )
104+ return self ._slow_active < slow_limit
105+
106+ def _can_acquire_locked (self , ticket : int , lane : LaneClass , limit : int , reserved_fast : int ) -> bool :
107+ if not self ._slot_available_locked (lane , limit , reserved_fast ):
108+ return False
109+ # Strict FIFO across all waiters whose lane currently has runnable capacity.
110+ # Blocked slow waiters cannot starve an eligible fast interactive waiter behind them.
111+ for queued_ticket in self ._waiters :
112+ if queued_ticket == ticket :
113+ return True
114+ queued_lane = self ._waiter_lanes .get (queued_ticket , "fast" )
115+ if self ._slot_available_locked (queued_lane , limit , reserved_fast ):
116+ return False
117+ return False
118+
119+ def _decrement_active_locked (self , lane : LaneClass ) -> None :
120+ if self ._active_count > 0 :
121+ self ._active_count -= 1
122+ if lane == "fast" :
123+ if self ._fast_active > 0 :
124+ self ._fast_active -= 1
125+ elif self ._slow_active > 0 :
126+ self ._slow_active -= 1
127+
49128 def acquire (
50129 self ,
51130 controller : Any ,
52131 * ,
132+ lane : LaneClass = "fast" ,
53133 is_cancelled : Callable [[], bool ],
54- ) -> Literal [ "acquired" , "closed" , "cancelled" ] :
55- """Wait in FIFO order for an active lane slot unless closed or cancelled."""
134+ ) -> _StewardSlotLease :
135+ """Wait in FIFO order for a lane slot unless closed or cancelled."""
56136 with self ._condition :
57137 ticket = self ._next_ticket
58138 self ._next_ticket += 1
59139 self ._waiters .append (ticket )
140+ self ._waiter_lanes [ticket ] = lane
60141 acquired = False
61142 try :
62143 while True :
63144 if controller .closed .is_set ():
64- return "closed"
145+ raise _StewardLaneWaitAborted ( "closed" )
65146 if is_cancelled ():
66- return "cancelled"
147+ raise _StewardLaneWaitAborted ( "cancelled" )
67148 limit = _resolve_steward_max_concurrent_lanes (controller )
68- if self ._waiters and self ._waiters [0 ] == ticket and self ._active_count < limit :
69- self ._waiters .popleft ()
149+ reserved_fast = _resolve_steward_fast_lane_reserved_slots (controller , limit )
150+ if self ._can_acquire_locked (ticket , lane , limit , reserved_fast ):
151+ self ._waiters .remove (ticket )
152+ self ._waiter_lanes .pop (ticket , None )
70153 self ._active_count += 1
154+ if lane == "fast" :
155+ self ._fast_active += 1
156+ else :
157+ self ._slow_active += 1
71158 acquired = True
72159 if self ._waiters and self ._active_count < limit :
73160 self ._condition .notify_all ()
74- return "acquired"
161+ return _StewardSlotLease ( ticket = ticket , lane = lane )
75162 self ._condition .wait (timeout = 0.5 )
76163 finally :
77164 if not acquired :
78165 try :
79166 self ._waiters .remove (ticket )
80167 except ValueError :
81168 pass
169+ self ._waiter_lanes .pop (ticket , None )
82170 self ._condition .notify_all ()
83171
84- def release (self ) -> None :
85- """Release one active lane slot and wake waiting lanes."""
172+ def release (self , lease : _StewardSlotLease | None = None ) -> None :
173+ """Release one active lane slot idempotently and wake waiting lanes."""
174+ with self ._condition :
175+ if lease is None :
176+ if self ._active_count > 0 :
177+ self ._active_count -= 1
178+ self ._condition .notify_all ()
179+ return
180+ if lease .released :
181+ return
182+ lease .released = True
183+ self ._decrement_active_locked (lease .lane )
184+ self ._condition .notify_all ()
185+
186+ def handoff (self , lease : _StewardSlotLease ) -> bool :
187+ """Release a soft-timed-out foreground slot once so waiting lanes proceed."""
86188 with self ._condition :
87- if self ._active_count > 0 :
88- self ._active_count -= 1
189+ if lease .released :
190+ return False
191+ lease .released = True
192+ lease .handed_off = True
193+ self ._decrement_active_locked (lease .lane )
89194 self ._condition .notify_all ()
195+ return True
90196
91197
92198def _steward_lane_limiter (controller : Any ) -> _StewardLaneLimiter :
@@ -110,6 +216,87 @@ def _turn_cancelled(controller: Any, session_id: str, turn_id: str) -> bool:
110216 return (session_id , turn_id ) in getattr (controller , "cancelled_turns" , ())
111217
112218
219+ def _classify_steward_turn_lane (
220+ session : Mapping [str , Any ] | None ,
221+ turn : Mapping [str , Any ] | None ,
222+ ) -> LaneClass :
223+ """Classify a Steward turn into 'fast' (interactive foreground) or 'slow' (heavy/background)."""
224+ if isinstance (session , Mapping ) and isinstance (session .get ("steward_background_context" ), Mapping ):
225+ return "slow"
226+ if not isinstance (turn , Mapping ):
227+ return "fast"
228+ explicit = turn .get ("lane_class" )
229+ if explicit in ("fast" , "slow" ):
230+ return explicit
231+ request = turn .get ("loopx_request" )
232+ if isinstance (request , Mapping ):
233+ req_lane = request .get ("lane_class" )
234+ if req_lane in ("fast" , "slow" ):
235+ return req_lane
236+ if request .get ("work_kind" ) in {"report" , "native_turn" , "scheduled_task" }:
237+ return "slow"
238+ if turn .get ("loopx_execution" ) is True :
239+ return "slow"
240+ if turn .get ("origin" ) in {"native_loopx" , "peer" , "scheduler" , "background" }:
241+ return "slow"
242+ return "fast"
243+
244+
245+ def _emit_foreground_soft_timeout_handoff (
246+ controller : Any ,
247+ * ,
248+ session_id : str ,
249+ turn_id : str ,
250+ lane : LaneClass ,
251+ soft_timeout_sec : float ,
252+ ) -> None :
253+ payload = {
254+ "lane" : lane ,
255+ "soft_timeout_sec" : soft_timeout_sec ,
256+ "slot_released" : True ,
257+ }
258+ with controller .lock :
259+ event_buffer = getattr (controller , "turn_event_buffers" , {}).get ((session_id , turn_id ))
260+ store = getattr (controller , "store" , None )
261+ if event_buffer is not None :
262+ try :
263+ event_buffer .emit ("turn.soft_timeout_handoff" , payload )
264+ if store is not None :
265+ store .flush_events (session_id , turn_id )
266+ except Exception :
267+ logging .getLogger (__name__ ).debug (
268+ "Failed emitting turn.soft_timeout_handoff event" , exc_info = True
269+ )
270+ elif store is not None :
271+ try :
272+ store .append_event (
273+ session_id ,
274+ turn_id ,
275+ kind = "turn.soft_timeout_handoff" ,
276+ payload = payload ,
277+ )
278+ except Exception :
279+ logging .getLogger (__name__ ).debug (
280+ "Failed appending turn.soft_timeout_handoff event" , exc_info = True
281+ )
282+ hook = getattr (controller , "steward_foreground_soft_timeout_hook" , None )
283+ if callable (hook ):
284+ try :
285+ hook (
286+ session_id = session_id ,
287+ turn_id = turn_id ,
288+ lane = lane ,
289+ soft_timeout_sec = soft_timeout_sec ,
290+ )
291+ except Exception :
292+ logging .getLogger (__name__ ).warning (
293+ "Steward foreground soft-timeout hook failed: session=%s turn=%s" ,
294+ session_id ,
295+ turn_id ,
296+ exc_info = True ,
297+ )
298+
299+
113300@contextmanager
114301def _acquire_steward_lane_slot (
115302 controller : Any ,
@@ -121,25 +308,60 @@ def _acquire_steward_lane_slot(
121308) -> Iterator [None ]:
122309 """Bound concurrent active upstream model Turns across Steward Topic Lanes."""
123310 channel_id = str ((session or {}).get ("channel_id" ) or "" )
311+ has_steward_ctx = isinstance (
312+ (session or {}).get ("steward_context" ) or (session or {}).get ("steward_background_context" ),
313+ Mapping ,
314+ )
124315 if (
125316 not session
126- or not isinstance ( session . get ( "steward_context" ), dict )
317+ or not has_steward_ctx
127318 or not channel_id .startswith ("manager.external.native." )
128319 or _is_observation_only_monitor_turn (turn )
129320 ):
130321 yield
131322 return
132323 limiter = _steward_lane_limiter (controller )
133- outcome = limiter .acquire (
324+ lane = _classify_steward_turn_lane (session , turn )
325+ lease = limiter .acquire (
134326 controller ,
327+ lane = lane ,
135328 is_cancelled = lambda : _turn_cancelled (controller , session_id , turn_id ),
136329 )
137- if outcome != "acquired" :
138- raise _StewardLaneWaitAborted (outcome )
330+ timer : threading .Timer | None = None
139331 try :
332+ soft_timeout_sec = _resolve_steward_foreground_soft_timeout_sec (controller ) if lane == "fast" else None
333+ if soft_timeout_sec is not None :
334+ def _on_soft_timeout () -> None :
335+ if controller .closed .is_set () or _turn_cancelled (controller , session_id , turn_id ):
336+ return
337+ if not limiter .handoff (lease ):
338+ return
339+ _emit_foreground_soft_timeout_handoff (
340+ controller ,
341+ session_id = session_id ,
342+ turn_id = turn_id ,
343+ lane = lane ,
344+ soft_timeout_sec = soft_timeout_sec ,
345+ )
346+
347+ candidate_timer = threading .Timer (soft_timeout_sec , _on_soft_timeout )
348+ candidate_timer .daemon = True
349+ try :
350+ candidate_timer .start ()
351+ except RuntimeError :
352+ logging .getLogger (__name__ ).warning (
353+ "Steward foreground soft-timeout timer start failed; proceeding without soft timeout: session=%s turn=%s" ,
354+ session_id ,
355+ turn_id ,
356+ exc_info = True ,
357+ )
358+ else :
359+ timer = candidate_timer
140360 yield
141361 finally :
142- limiter .release ()
362+ if timer is not None :
363+ timer .cancel ()
364+ limiter .release (lease )
143365
144366
145367def _is_observation_only_monitor_turn (turn : dict [str , Any ] | None ) -> bool :
@@ -250,7 +472,7 @@ def _drain_session_queue_events(controller: Any, *, session_id: str, work_dir: P
250472 continue
251473 active = controller .store .load_turn (session_id , active_turn_id )
252474 if active and active .get ("status" ) not in TERMINAL_TURN_STATES :
253- controller . closed . wait (0.05 )
475+ wakeup . wait (timeout = 0.05 )
254476 continue
255477 controller .store .release_active_turn (session_id , active_turn_id )
256478 refreshed = controller .store .load_session (session_id )
@@ -357,6 +579,18 @@ def _drain_session_queue_events(controller: Any, *, session_id: str, work_dir: P
357579 # A failed error checkpoint must not kill this queue worker;
358580 # the next iteration reconciles the original durable state.
359581 controller .closed .wait (0.25 )
582+ except Exception as exc :
583+ logging .getLogger (__name__ ).warning (
584+ "Steward lane setup failed before turn execution: session=%s turn=%s" ,
585+ session_id ,
586+ turn_id ,
587+ exc_info = True ,
588+ )
589+ try :
590+ controller ._fail_queue_preparation (session_id , turn_id , exc )
591+ finally :
592+ controller ._release_done_event ((session_id , turn_id ), done_event , drop_event = True )
593+ continue
360594 finally :
361595 with controller .lock :
362596 worker = controller .session_queue_threads .get (session_id )
0 commit comments