Skip to content

Commit b9626df

Browse files
committed
fix(python): cancel queued requests and clean up pytest descendants
1 parent 806106b commit b9626df

6 files changed

Lines changed: 320 additions & 122 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
1111
1. **语言与编辑器基础(`languages: python`)**
1212
- 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` / `.conda` 项目依赖目录。
1313
2. **后端解析的语言服务器启动与解释器自动注入(`backend` + `languageServers: python` / Pyrefly `1.4.1`)**
14+
- 启动语言服务器前,宿主需要能够发现 Python 3.9 或更高版本以执行启动解析后端。宿主会传入可用于自动启动的解释器路径,项目内环境交由 Pyrefly 按自身规则发现。
1415
- 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),6 个平台发布包共享同一套纯 Python(`python -I -B`)插件后端 `scripts/backend.py`。
1516
- `languageServers[0]` 采用 `"launch": {"kind": "backend", "function": "pyrefly.resolveLaunch", "timeoutMilliseconds": 30000}`:根据 `platform.os` 动态返回包内 `bin/pyrefly` 或 `bin/pyrefly.exe` 与 `arguments: ["lsp"]`,合并全部即时设置(`typeCheckingMode`、`displayTypeErrors`、`diagnosticMode`、`autoImportCompletions`、`completeFunctionParens`、`importFormat`)。
1617
- 当宿主在调用参数中传入已选定的非项目内解释器 `tools.python.executable`(如外部 `conda`、`uv`、`pyenv` 或系统环境)时,自动注入 `workspaceConfiguration.python.pythonPath`;当 `tools.python` 缺失(未选定或项目内虚拟环境尚未获信任)时优雅省略 `pythonPath`,保留 `pyrefly` 原生 `.venv` / `pyproject.toml` 自动发现且不阻断启动。
@@ -21,7 +22,7 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
2122
- `python`:通过纯 Python 构建提供者 `scripts/build_provider.py --cache ${workspaceStateDir}`(`python -I -B`,`executesProjectCode: true`,`mayUseNetwork: false`)承载:
2223
- `lithe/build/model`:复用 `scripts/build_model.py` 纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户代码),派生 7 类声明式 `run` 配置;
2324
- `lithe/build/discoverTests`:运行有界、可随 `$/cancelRequest` 整组终止的 `pytest --collect-only` 收集函数、类方法与 `@pytest.mark.parametrize` 参数化用例(缓存写入 `${workspaceStateDir}`,不向工作区写 `.pytest_cache`),返回标准 `litheTestDiscovery` v0;
24-
- `lithe/build/test`:支持从动态测试树精确 nodeid 或 JUnit XML 类名运行单个用例/套件,实时推送 `lithe/build/progress` 并产出 `.pytest_cache/lithe-junit.xml` 供 Core `junitXml` 解码;
25+
- `lithe/build/test`:支持从动态测试树精确 nodeid 或 JUnit XML 类名运行单个用例和套件,实时推送 `lithe/build/progress` 并产出 `.pytest_cache/lithe-junit.xml` 供 Core `junitXml` 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。
2526
- `lithe/build/runEntrypoints`:协商 `litheBuild` 1 时按文件静态识别入口并抑制高频成功日志;
2627
- 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。
2728
- `uv`(`uv.lock`):`uv sync`、`uv lock`。

‎io.github.lithe-idea.python-support/scripts/lithe_rpc.py‎

Lines changed: 78 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
MAX_SAFE_INTEGER = 9_007_199_254_740_991
2323
MAX_INCOMING_FRAME_BYTES = 16 * 1024 * 1024
24+
MAX_IN_FLIGHT_REQUESTS = 32
2425
MAX_FUNCTION_RESULT_BYTES = 1024 * 1024
2526
MAX_BUILD_RESULT_BYTES = 32 * 1024 * 1024
2627
MAX_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-
229185
class 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

272206
def 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

364311
class 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

Comments
 (0)