2121
2222MAX_SAFE_INTEGER = 9_007_199_254_740_991
2323MAX_INCOMING_FRAME_BYTES = 16 * 1024 * 1024
24+ MAX_IN_FLIGHT_REQUESTS = 32
2425MAX_FUNCTION_RESULT_BYTES = 1024 * 1024
2526MAX_BUILD_RESULT_BYTES = 32 * 1024 * 1024
2627MAX_BUILD_MESSAGE_BYTES = 4096
@@ -181,58 +182,11 @@ class FramingError(Exception):
181182 """Raised when the incoming stdio stream violates Content-Length framing."""
182183
183184
184- def terminate_process_tree (proc : subprocess .Popen [Any ]) -> None :
185- """Terminates a child process and its process group with bounded escalation."""
186- if proc .poll () is not None :
187- return
188- if os .name == "nt" :
189- try :
190- subprocess .run (
191- ["taskkill" , "/T" , "/F" , "/PID" , str (proc .pid )],
192- stdout = subprocess .DEVNULL ,
193- stderr = subprocess .DEVNULL ,
194- timeout = 3.0 ,
195- check = False ,
196- )
197- except Exception :
198- pass
199- try :
200- proc .kill ()
201- except OSError :
202- pass
203- else :
204- try :
205- os .killpg (proc .pid , signal .SIGTERM )
206- except OSError :
207- try :
208- proc .terminate ()
209- except OSError :
210- pass
211- try :
212- proc .wait (timeout = 1.5 )
213- return
214- except subprocess .TimeoutExpired :
215- pass
216- try :
217- os .killpg (proc .pid , signal .SIGKILL )
218- except OSError :
219- try :
220- proc .kill ()
221- except OSError :
222- pass
223- try :
224- proc .wait (timeout = 2.0 )
225- except Exception :
226- pass
227-
228-
229185class CancelToken :
230- """Tracks request cancellation and owns every child subprocess started by the request."""
186+ """Shares cancellation with a queued or running request."""
231187
232188 def __init__ (self ) -> None :
233189 self ._event = threading .Event ()
234- self ._lock = threading .Lock ()
235- self ._procs : set [subprocess .Popen [Any ]] = set ()
236190
237191 @property
238192 def cancelled (self ) -> bool :
@@ -245,28 +199,8 @@ def raise_if_cancelled(self) -> None:
245199 def wait (self , timeout : float ) -> bool :
246200 return self ._event .wait (timeout )
247201
248- def register_process (self , proc : subprocess .Popen [Any ]) -> None :
249- kill_now = False
250- with self ._lock :
251- if self ._event .is_set ():
252- kill_now = True
253- else :
254- self ._procs .add (proc )
255- if kill_now :
256- terminate_process_tree (proc )
257- raise CancelledError ("Request cancelled" )
258-
259- def unregister_process (self , proc : subprocess .Popen [Any ]) -> None :
260- with self ._lock :
261- self ._procs .discard (proc )
262-
263202 def cancel (self ) -> None :
264- with self ._lock :
265- self ._event .set ()
266- procs = list (self ._procs )
267- self ._procs .clear ()
268- for proc in procs :
269- terminate_process_tree (proc )
203+ self ._event .set ()
270204
271205
272206def run_bounded_process (
@@ -285,20 +219,24 @@ def run_bounded_process(
285219 Returns (exit_code, combined_output, timed_out).
286220 """
287221 cancel_token .raise_if_cancelled ()
288- popen_kwargs : dict [str , Any ] = {
289- "cwd" : cwd ,
290- "env" : env ,
291- "stdin" : subprocess .DEVNULL ,
292- "stdout" : subprocess .PIPE ,
293- "stderr" : subprocess .STDOUT ,
294- }
222+ job = None
295223 if os .name == "nt" :
296- popen_kwargs ["creationflags" ] = getattr (subprocess , "CREATE_NEW_PROCESS_GROUP" , 0 )
297- else :
298- popen_kwargs ["start_new_session" ] = True
224+ from windows_job import WindowsJob
299225
300- proc = subprocess .Popen (argv , ** popen_kwargs )
301- cancel_token .register_process (proc )
226+ job = WindowsJob ()
227+ try :
228+ # A Windows virtualenv redirector can create a child before its
229+ # interpreter starts. The base executable keeps bootstrap atomic.
230+ proc = job .start (sys ._base_executable , argv , cwd = cwd , env = env )
231+ except Exception :
232+ job .close ()
233+ raise
234+ else :
235+ proc = subprocess .Popen (
236+ argv , cwd = cwd , env = env , stdin = subprocess .DEVNULL ,
237+ stdout = subprocess .PIPE , stderr = subprocess .STDOUT ,
238+ start_new_session = True ,
239+ )
302240 chunks : list [bytes ] = []
303241 captured_bytes = 0
304242 lock = threading .Lock ()
@@ -310,7 +248,7 @@ def _reader() -> None:
310248 return
311249 try :
312250 while True :
313- data = stream .read (4096 )
251+ data = stream .read1 (4096 )
314252 if not data :
315253 break
316254 text_chunk : Optional [str ] = None
@@ -332,33 +270,42 @@ def _reader() -> None:
332270 pass
333271
334272 reader_thread = threading .Thread (target = _reader , daemon = True )
335- reader_thread .start ()
336-
337273 deadline = time .monotonic () + max (0.1 , timeout_seconds )
338274 timed_out = False
339275 try :
276+ reader_thread .start ()
340277 while proc .poll () is None :
341- if cancel_token .cancelled :
342- terminate_process_tree (proc )
343- raise CancelledError ("Request cancelled" )
278+ cancel_token .raise_if_cancelled ()
344279 remaining = deadline - time .monotonic ()
345280 if remaining <= 0 :
346281 timed_out = True
347- terminate_process_tree (proc )
348282 break
349283 try :
350284 proc .wait (timeout = min (0.05 , remaining ))
351285 except subprocess .TimeoutExpired :
352286 continue
353- reader_thread .join (timeout = 2.0 )
354- cancel_token .raise_if_cancelled ()
355- exit_code = proc .returncode if proc .returncode is not None else - 1
356- output = b"" .join (chunks ).decode ("utf-8" , errors = "replace" )
357- return exit_code , output , timed_out
358287 finally :
359- cancel_token .unregister_process (proc )
360- if proc .poll () is None :
361- terminate_process_tree (proc )
288+ # The request owns the whole group, even after its direct child exits.
289+ # Closing the Windows job or killing the POSIX group releases inherited
290+ # output handles left open by surviving descendants before draining.
291+ if job is not None :
292+ job .close ()
293+ else :
294+ try :
295+ os .killpg (proc .pid , signal .SIGKILL )
296+ except ProcessLookupError :
297+ pass
298+ proc .wait (timeout = 2.0 )
299+ if reader_thread .ident is None :
300+ proc .stdout .close ()
301+ else :
302+ reader_thread .join (timeout = 2.0 )
303+
304+ cancel_token .raise_if_cancelled ()
305+ exit_code = proc .returncode
306+ with lock :
307+ output = b"" .join (chunks ).decode ("utf-8" , errors = "replace" )
308+ return exit_code , output , timed_out
362309
363310
364311class DiagnosticsReporter :
@@ -753,7 +700,7 @@ def _handle_request(self, req_id: Any, method: str, params: Any) -> None:
753700 return
754701
755702 if method == "lithe/function/invoke" :
756- self ._executor . submit ( self ._invoke_function , req_id , params )
703+ self ._submit ( req_id , self ._invoke_function , params )
757704 return
758705 if method in self ._build_handlers and self ._build_version is not None :
759706 if method == "lithe/build/runEntrypoints" and self ._build_version < 1 :
@@ -762,17 +709,40 @@ def _handle_request(self, req_id: Any, method: str, params: Any) -> None:
762709 error = {"code" : ERROR_METHOD_NOT_FOUND , "message" : "The requested method is not supported." },
763710 )
764711 return
765- self ._executor . submit ( self ._invoke_build , req_id , method , params )
712+ self ._submit ( req_id , self ._invoke_build , method , params )
766713 return
767714 if method == "toolchains/query" and self ._selected_toolchain_providers :
768- self ._executor . submit ( self ._invoke_toolchain_query , req_id , params )
715+ self ._submit ( req_id , self ._invoke_toolchain_query , params )
769716 return
770717
771718 self ._respond (
772719 req_id ,
773720 error = {"code" : ERROR_METHOD_NOT_FOUND , "message" : "The requested method is not supported." },
774721 )
775722
723+ def _submit (self , req_id : Any , invoke : Callable [..., None ], * args : Any ) -> None :
724+ key = request_key (req_id )
725+ token = CancelToken ()
726+ with self ._state_lock :
727+ admitted = key not in self ._incoming and len (self ._incoming ) < MAX_IN_FLIGHT_REQUESTS
728+ if admitted :
729+ self ._incoming [key ] = token
730+ if not admitted :
731+ self ._respond (
732+ req_id ,
733+ error = {"code" : ERROR_INVALID_REQUEST , "message" : "The backend cannot accept this request." },
734+ )
735+ return
736+
737+ def run () -> None :
738+ try :
739+ invoke (req_id , token , * args )
740+ finally :
741+ with self ._state_lock :
742+ self ._incoming .pop (key , None )
743+
744+ self ._executor .submit (run )
745+
776746 def _handle_initialize (self , req_id : Any , params : dict [str , Any ]) -> None :
777747 if self ._phase != "listening" :
778748 self ._respond (
@@ -899,7 +869,7 @@ def _handle_shutdown(self, req_id: Any) -> None:
899869 self .diagnostics .terminal ("shutdown" , "internal_error" , 0 )
900870 self ._respond (req_id , result = None )
901871
902- def _invoke_function (self , req_id : Any , raw_params : Any ) -> None :
872+ def _invoke_function (self , req_id : Any , token : CancelToken , raw_params : Any ) -> None :
903873 if not isinstance (raw_params , dict ):
904874 self ._respond (req_id , error = {"code" : ERROR_INVALID_PARAMS , "message" : "Function invoke requires object params." })
905875 return
@@ -945,6 +915,7 @@ def _stop_reporting() -> None:
945915
946916 self ._execute_tracked (
947917 req_id = req_id ,
918+ token = token ,
948919 operation = fn_id ,
949920 wire_op_id = op_id ,
950921 invoke = lambda ctx : handler (call_params , ctx ),
@@ -955,7 +926,7 @@ def _stop_reporting() -> None:
955926 emit_logging = True ,
956927 )
957928
958- def _invoke_build (self , req_id : Any , method : str , raw_params : Any ) -> None :
929+ def _invoke_build (self , req_id : Any , token : CancelToken , method : str , raw_params : Any ) -> None :
959930 progressing = method in (
960931 "lithe/build/execute" ,
961932 "lithe/build/test" ,
@@ -1019,6 +990,7 @@ def _stop_reporting() -> None:
1019990
1020991 self ._execute_tracked (
1021992 req_id = req_id ,
993+ token = token ,
1022994 operation = method ,
1023995 wire_op_id = op_id ,
1024996 invoke = lambda ctx : handler (raw_params , ctx ),
@@ -1029,7 +1001,7 @@ def _stop_reporting() -> None:
10291001 emit_logging = True ,
10301002 )
10311003
1032- def _invoke_toolchain_query (self , req_id : Any , raw_params : Any ) -> None :
1004+ def _invoke_toolchain_query (self , req_id : Any , token : CancelToken , raw_params : Any ) -> None :
10331005 if not isinstance (raw_params , dict ):
10341006 self ._respond (
10351007 req_id ,
@@ -1063,18 +1035,14 @@ def _invoke_toolchain_query(self, req_id: Any, raw_params: Any) -> None:
10631035 return
10641036
10651037 handler = self ._toolchain_providers [provider_id ]
1066- key = request_key (req_id )
1067- token = CancelToken ()
1068- with self ._state_lock :
1069- self ._incoming [key ] = token
1070-
10711038 ctx = CallContext (
10721039 cancel_token = token ,
10731040 diagnostics = self ._make_diagnostics (request_operation_id (op_id , req_id )),
10741041 suppress_cb = lambda : None ,
10751042 operation_id = op_id ,
10761043 )
10771044 try :
1045+ token .raise_if_cancelled ()
10781046 result = handler (raw_params , ctx )
10791047 token .raise_if_cancelled ()
10801048 self ._respond (req_id , result = result )
@@ -1135,15 +1103,11 @@ def _invoke_toolchain_query(self, req_id: Any, raw_params: Any) -> None:
11351103 },
11361104 },
11371105 )
1138- finally :
1139- with self ._state_lock :
1140- self ._incoming .pop (key , None )
1141- token .cancel ()
1142-
11431106 def _execute_tracked (
11441107 self ,
11451108 * ,
11461109 req_id : Any ,
1110+ token : CancelToken ,
11471111 operation : str ,
11481112 wire_op_id : Any ,
11491113 invoke : Callable [[CallContext ], Any ],
@@ -1161,11 +1125,6 @@ def _suppress() -> None:
11611125 nonlocal quiet_call
11621126 quiet_call = True
11631127
1164- token = CancelToken ()
1165- key = request_key (req_id )
1166- with self ._state_lock :
1167- self ._incoming [key ] = token
1168-
11691128 ctx = CallContext (
11701129 cancel_token = token ,
11711130 diagnostics = diag ,
@@ -1181,9 +1140,10 @@ def _suppress() -> None:
11811140 was_cancelled = False
11821141
11831142 try :
1184- raw_value = invoke (ctx )
11851143 token .raise_if_cancelled ()
1144+ raw_value = invoke (ctx )
11861145 result_val = shape (raw_value )
1146+ token .raise_if_cancelled ()
11871147 except CancelledError :
11881148 was_cancelled = True
11891149 error_obj = {"code" : ERROR_REQUEST_CANCELLED , "message" : "The request was cancelled." }
@@ -1212,9 +1172,6 @@ def _suppress() -> None:
12121172 finally :
12131173 elapsed_ms = (time .monotonic () - started ) * 1000.0
12141174 on_settled ()
1215- with self ._state_lock :
1216- self ._incoming .pop (key , None )
1217- token .cancel ()
12181175
12191176 # Emit terminal lithe/log notification strictly BEFORE the RPC response frame
12201177 # so Core correlates wire operationId with the still-active host operation.
0 commit comments