From a2f53d1ba5efe0aa76e43de735d04983006f6ea4 Mon Sep 17 00:00:00 2001 From: Grammy Jiang Date: Wed, 21 Oct 2026 23:06:01 +1100 Subject: [PATCH 1/8] feat(python): add opt-in Pyright language server adapter --- README.md | 9 +- src/multilspy/language_server.py | 13 +- .../pyright_language_server/__init__.py | 0 .../pyright_language_server/pyright_server.py | 154 ++++++++++++++++ src/multilspy/multilspy_config.py | 4 +- tests/multilspy/test_multilspy_pyright.py | 173 ++++++++++++++++++ 6 files changed, 349 insertions(+), 4 deletions(-) create mode 100644 src/multilspy/language_servers/pyright_language_server/__init__.py create mode 100644 src/multilspy/language_servers/pyright_language_server/pyright_server.py create mode 100644 tests/multilspy/test_multilspy_pyright.py diff --git a/README.md b/README.md index d9bc4514..c6698dd8 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ pip install multilspy | Code Language | Language Server | | --- | --- | | java | Eclipse JDTLS | -| python | jedi-language-server | +| python | jedi-language-server (default) or Pyright | | rust | Rust Analyzer | | csharp | OmniSharp / RazorSharp | | typescript | TypeScriptLanguageServer | @@ -53,6 +53,13 @@ pip install multilspy | cpp | clangd | +Pyright is an optional Python backend. Install pyright-langserver and +select it with MultilspyConfig(code_language=Language.PYTHON, +python_server="pyright"); pass server_binary="/absolute/path/to/pyright-langserver" +if the executable is not on PATH. The adapter launches the server with +--stdio and does not automatically install it. Existing Python users +continue using Jedi by default. + ## Usage Example usage: ```python diff --git a/src/multilspy/language_server.py b/src/multilspy/language_server.py index dbf75b53..acb43594 100644 --- a/src/multilspy/language_server.py +++ b/src/multilspy/language_server.py @@ -74,6 +74,14 @@ def create(cls, config: MultilspyConfig, logger: MultilspyLogger, repository_roo :return LanguageServer: A language specific LanguageServer instance. """ if config.code_language == Language.PYTHON: + if config.python_server == "pyright": + from multilspy.language_servers.pyright_language_server.pyright_server import ( + PyrightServer, + ) + + return PyrightServer(config, logger, repository_root_path) + if config.python_server != "jedi": + raise MultilspyException("Unsupported Python language server") from multilspy.language_servers.jedi_language_server.jedi_server import ( JediServer, ) @@ -425,8 +433,7 @@ async def request_definition( new_item["relativePath"] = PathUtils.get_relative_path(new_item["absolutePath"], self.repository_root_path) ret.append(multilspy_types.Location(new_item)) elif ( - LSPConstants.ORIGIN_SELECTION_RANGE in item - and LSPConstants.TARGET_URI in item + LSPConstants.TARGET_URI in item and LSPConstants.TARGET_RANGE in item and LSPConstants.TARGET_SELECTION_RANGE in item ): @@ -490,6 +497,8 @@ async def request_references( ) ret: List[multilspy_types.Location] = [] + if response is None: + return ret assert isinstance(response, list), f"Unexpected response from Language Server: {response}" for item in response: assert isinstance(item, dict) diff --git a/src/multilspy/language_servers/pyright_language_server/__init__.py b/src/multilspy/language_servers/pyright_language_server/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/multilspy/language_servers/pyright_language_server/pyright_server.py b/src/multilspy/language_servers/pyright_language_server/pyright_server.py new file mode 100644 index 00000000..7f46ca82 --- /dev/null +++ b/src/multilspy/language_servers/pyright_language_server/pyright_server.py @@ -0,0 +1,154 @@ +"""Pyright LSP backend for multilspy's existing Python language API. + +Pyright must already be installed. This backend doesn't download binaries, +edit project files, or require a VS Code extension process. +""" + +import asyncio +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any, AsyncIterator + +from multilspy.language_server import LanguageServer +from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo +from multilspy.multilspy_config import MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + + +class PyrightServer(LanguageServer): + """Use pyright-langserver --stdio instead of the default Jedi backend.""" + + def __init__( + self, config: MultilspyConfig, logger: MultilspyLogger, repository_root_path: str + ): + root = str(Path(repository_root_path).resolve()) + super().__init__( + config, + logger, + root, + ProcessLaunchInfo( + cmd=[config.server_binary or "pyright-langserver", "--stdio"], + cwd=root, + ), + "python", + ) + self.diagnostics: asyncio.Queue[dict] = asyncio.Queue(maxsize=64) + self.diagnostics_dropped = False + + async def next_diagnostics(self, timeout: float = 5.0) -> dict: + """Read an asynchronous publishDiagnostics notification.""" + return await asyncio.wait_for(self.diagnostics.get(), timeout) + + @asynccontextmanager + async def start_server(self) -> AsyncIterator["PyrightServer"]: + async def configuration(params: Any) -> list: + if not isinstance(params, dict): + return [] + items = params.get("items") + if not isinstance(items, list) or len(items) > 64: + return [] + defaults = { + "python": {"analysis": {}}, + "pyright": { + "disableLanguageServices": False, + "disableOrganizeImports": True, + }, + } + return [ + defaults.get(item.get("section")) + if isinstance(item, dict) and isinstance(item.get("section"), str) + else None + for item in items + ] + + async def refuse_edit(_params: Any) -> dict: + return { + "applied": False, + "failureReason": "multilspy Pyright client is read-only", + } + + async def diagnostics(params: Any) -> None: + if not isinstance(params, dict) or not isinstance(params.get("uri"), str): + return + if self.diagnostics.full(): + self.diagnostics_dropped = True + return + self.diagnostics.put_nowait(params) + + async def ignore_notification(_params: Any) -> None: + return None + + self.server.on_request("workspace/configuration", configuration) + self.server.on_request("workspace/applyEdit", refuse_edit) + self.server.on_notification("textDocument/publishDiagnostics", diagnostics) + self.server.on_notification("window/logMessage", ignore_notification) + self.server.on_notification("$/progress", ignore_notification) + + async with super().start_server(): + initialized = False + try: + await self.server.start() + root = Path(self.repository_root_path) + init = await asyncio.wait_for( + self.server.send.initialize( + { + "processId": None, + "rootUri": root.as_uri(), + "rootPath": str(root), + "workspaceFolders": [ + {"uri": root.as_uri(), "name": root.name} + ], + "clientInfo": {"name": "multilspy"}, + "capabilities": { + "general": {"positionEncodings": ["utf-16"]}, + "workspace": { + "applyEdit": False, + "configuration": True, + "workspaceFolders": False, + "symbol": {}, + }, + "textDocument": { + "definition": {"linkSupport": True}, + "typeDefinition": {"linkSupport": True}, + "references": {}, + "hover": { + "contentFormat": ["markdown", "plaintext"] + }, + "completion": { + "completionItem": { + "snippetSupport": False, + "documentationFormat": ["plaintext"], + } + }, + "signatureHelp": { + "signatureInformation": { + "documentationFormat": ["plaintext"], + } + }, + "documentSymbol": { + "hierarchicalDocumentSymbolSupport": True + }, + "publishDiagnostics": { + "relatedInformation": True + }, + }, + }, + } + ), + timeout=30, + ) + capabilities = init.get("capabilities") if isinstance(init, dict) else None + if not isinstance(capabilities, dict): + raise ValueError("Invalid Pyright initialization capabilities") + if capabilities.get("positionEncoding", "utf-16") != "utf-16": + raise ValueError("Unsupported Pyright position encoding") + self.server.notify.initialized({}) + self.completions_available.set() + initialized = True + yield self + finally: + try: + if initialized: + await asyncio.wait_for(self.server.shutdown(), timeout=8) + finally: + await self.server.stop() diff --git a/src/multilspy/multilspy_config.py b/src/multilspy/multilspy_config.py index b12a8ca2..7b8c7975 100644 --- a/src/multilspy/multilspy_config.py +++ b/src/multilspy/multilspy_config.py @@ -4,7 +4,7 @@ from enum import Enum from dataclasses import dataclass -from typing import Optional +from typing import Literal, Optional class Language(str, Enum): """ @@ -34,6 +34,8 @@ class MultilspyConfig: Configuration parameters """ code_language: Language + # Preserve Jedi as the default Python backend; explicitly opt in to Pyright. + python_server: Literal["jedi", "pyright"] = "jedi" trace_lsp_communication: bool = False start_independent_lsp_process: bool = True diff --git a/tests/multilspy/test_multilspy_pyright.py b/tests/multilspy/test_multilspy_pyright.py new file mode 100644 index 00000000..1ffa13d6 --- /dev/null +++ b/tests/multilspy/test_multilspy_pyright.py @@ -0,0 +1,173 @@ +"""Pyright backend regression tests; real provider is opt-in through env. + +No auto-install, project clone or network request in the default test suite. +""" + +import asyncio +import os +from contextlib import contextmanager +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from multilspy.language_server import LanguageServer +from multilspy.language_servers.jedi_language_server.jedi_server import JediServer +from multilspy.language_servers.pyright_language_server.pyright_server import PyrightServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_exceptions import MultilspyException +from multilspy.multilspy_logger import MultilspyLogger + + +def _server(tmp_path: Path, *, backend: str = "pyright", executable=None): + config = MultilspyConfig( + code_language=Language.PYTHON, python_server=backend, server_binary=executable + ) + return LanguageServer.create(config, MultilspyLogger(), str(tmp_path.resolve())) + + +def test_existing_python_users_still_get_jedi(tmp_path): + lsp = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON), + MultilspyLogger(), + str(tmp_path), + ) + assert isinstance(lsp, JediServer) + + +def test_explicit_pyright_factory_uses_stdio_without_downloading(tmp_path): + executable = "/some/preinstalled/pyright-langserver" + lsp = _server(tmp_path, executable=executable) + assert isinstance(lsp, PyrightServer) + assert lsp.language_id == "python" + assert lsp.server.process_launch_info.cmd == [executable, "--stdio"] + assert lsp.server.process_launch_info.cwd == str(tmp_path.resolve()) + assert lsp.server.process is None + + +def test_pyright_default_binary_is_an_existing_install_requirement(tmp_path): + lsp = _server(tmp_path) + assert lsp.server.process_launch_info.cmd == [ + "pyright-langserver", + "--stdio", + ] + assert lsp.server.process is None + + +def test_unknown_python_backend_is_not_silently_jedi(tmp_path): + with pytest.raises(MultilspyException, match="Unsupported Python"): + _server(tmp_path, backend="invalid") + + +@pytest.mark.parametrize("kind", ["location", "link"]) +def test_definition_accepts_location_and_optional_origin_link(tmp_path, kind): + """LocationLink.originSelectionRange is optional in LSP 3.17.""" + lsp = _server(tmp_path) + source = tmp_path / "example.py" + source.write_text("def hello(): return 1\n") + location = source.resolve().as_uri() + span = { + "start": {"line": 0, "character": 4}, + "end": {"line": 0, "character": 9}, + } + response = ( + {"uri": location, "range": span} + if kind == "location" + else { + "targetUri": location, + "targetRange": span, + "targetSelectionRange": span, + # No originSelectionRange! + } + ) + + @contextmanager + def noop_open(_path: str): + yield + + async def definition(_params): + return [response] + + lsp.server_started = True + lsp.open_file = noop_open + lsp.server.send = SimpleNamespace(definition=definition) + actual = asyncio.run(lsp.request_definition("example.py", 0, 5)) + assert len(actual) == 1 + assert actual[0]["relativePath"] == "example.py" + assert actual[0]["range"] == span + + +def test_null_references_become_empty_list(tmp_path): + lsp = _server(tmp_path) + (tmp_path / "example.py").write_text("hello = 1\n") + + @contextmanager + def noop_open(_path: str): + yield + + async def references(_params): + return None + + lsp.server_started = True + lsp.open_file = noop_open + lsp.server.send = SimpleNamespace(references=references) + assert asyncio.run(lsp.request_references("example.py", 0, 2)) == [] + + +def test_real_pyright_navigation_and_diagnostics(tmp_path): + """Optional official Pyright LSP integration, no implicit install.""" + executable = os.environ.get("MULTILSPY_PYRIGHT_TEST_BINARY") + if not executable: + pytest.skip("Set MULTILSPY_PYRIGHT_TEST_BINARY to a trusted binary") + binary = Path(executable) + if not binary.is_absolute() or not binary.is_file(): + pytest.skip("Explicit Pyright binary not found") + root = tmp_path.resolve() + source = root / "sample.py" + original = ( + "def say_hello(name: str) -> str:\n" + " return 123\n" + "\n" + "answer = say_hello('Ada')\n" + ) + source.write_text(original) + (root / "pyrightconfig.json").write_text('{"typeCheckingMode":"standard"}') + lsp = _server(root, executable=str(binary)) + + async def exercise(): + async with lsp.start_server(): + definition = await asyncio.wait_for( + lsp.request_definition("sample.py", 3, 12), 8 + ) + assert len(definition) == 1 + assert definition[0]["relativePath"] == "sample.py" + references = await asyncio.wait_for( + lsp.request_references("sample.py", 0, 4), 8 + ) + assert isinstance(references, list) + assert len(references) >= 1 + hover = await asyncio.wait_for( + lsp.request_hover("sample.py", 3, 12), 8 + ) + assert hover is not None + # A push diagnostic is asynchronous and can arrive after + # an earlier empty didClose diagnostic for the same URI. + while not lsp.diagnostics.empty(): + lsp.diagnostics.get_nowait() + with lsp.open_file("sample.py"): + observed = set() + for _ in range(10): + message = await lsp.next_diagnostics(timeout=2) + if message.get("uri") != source.as_uri(): + continue + observed.update( + item.get("code") + for item in message.get("diagnostics", []) + if isinstance(item, dict) + ) + if "reportReturnType" in observed: + break + assert "reportReturnType" in observed + asyncio.run(asyncio.wait_for(exercise(), timeout=30)) + assert lsp.server.process is None + assert source.read_text() == original From f6f7e6a3c2021b56fc99c4ac7d4530e8d9a94c44 Mon Sep 17 00:00:00 2001 From: Grammy Jiang Date: Thu, 22 Oct 2026 00:05:21 +1100 Subject: [PATCH 2/8] test(pyright): align multilspy adapter, fixtures and protocol regressions --- README.md | 35 +- src/multilspy/language_server.py | 18 +- .../initialize_params.json | 47 +++ .../pyright_language_server/pyright_server.py | 123 +++--- src/multilspy/multilspy_config.py | 6 +- tests/multilspy/test_completion_responses.py | 22 + tests/multilspy/test_lsp_result_shapes.py | 113 ++++++ tests/multilspy/test_multilspy_pyright.py | 377 ++++++++++++------ .../test_pyright_adapter_notifications.py | 269 +++++++++++++ .../test_pyright_process_lifecycle.py | 111 ++++++ 10 files changed, 917 insertions(+), 204 deletions(-) create mode 100644 src/multilspy/language_servers/pyright_language_server/initialize_params.json create mode 100644 tests/multilspy/test_lsp_result_shapes.py create mode 100644 tests/multilspy/test_pyright_adapter_notifications.py create mode 100644 tests/multilspy/test_pyright_process_lifecycle.py diff --git a/README.md b/README.md index c6698dd8..695acced 100644 --- a/README.md +++ b/README.md @@ -53,12 +53,35 @@ pip install multilspy | cpp | clangd | -Pyright is an optional Python backend. Install pyright-langserver and -select it with MultilspyConfig(code_language=Language.PYTHON, -python_server="pyright"); pass server_binary="/absolute/path/to/pyright-langserver" -if the executable is not on PATH. The adapter launches the server with ---stdio and does not automatically install it. Existing Python users -continue using Jedi by default. +For Python, Jedi remains the default language server. To use Pyright instead, +install [Pyright](https://github.com/microsoft/pyright) and explicitly select +the optional backend: + +```python +from multilspy import LanguageServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + +config = MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary="/absolute/path/to/pyright-langserver", +) +lsp = LanguageServer.create(config, MultilspyLogger(), "/path/to/python/project") +async with lsp.start_server(): + definitions = await lsp.request_definition("module.py", 10, 4) +``` + +The server binary must already be installed; the adapter adds the --stdio +argument and does not download/install Pyright. If server_binary is +omitted, it uses pyright-langserver from PATH. The existing +MultilspyConfig(code_language=Language.PYTHON) continues using Jedi. + +Real Pyright integration tests require a preinstalled language server. Set +MULTILSPY_PYRIGHT_TEST_BINARY to its absolute executable path before running +pytest on tests/multilspy/test_multilspy_pyright.py. Without this variable +the real-server tests skip; mock/fixture coverage still runs offline. +This keeps the normal test suite independent of automatic Pyright downloads. ## Usage Example usage: diff --git a/src/multilspy/language_server.py b/src/multilspy/language_server.py index acb43594..423838a2 100644 --- a/src/multilspy/language_server.py +++ b/src/multilspy/language_server.py @@ -548,6 +548,9 @@ async def request_completions( response = {"items": response, "isIncomplete": False} if not response["isIncomplete"]: break + completion_params["context"] = { + "triggerKind": LSPTypes.CompletionTriggerKind.TriggerForIncompleteCompletions + } # TODO: Understand how to appropriately handle `isIncomplete` if response is None or (response["isIncomplete"] and not(allow_incomplete)): @@ -559,26 +562,27 @@ async def request_completions( response: List[LSPTypes.CompletionItem] = response # TODO: Handle the case when the completion is a keyword - items = [item for item in response if item["kind"] != LSPTypes.CompletionItemKind.Keyword] + items = [item for item in response if item.get("kind") != LSPTypes.CompletionItemKind.Keyword] completions_list: List[multilspy_types.CompletionItem] = [] for item in items: - assert "insertText" in item or "textEdit" in item - assert "kind" in item + # LSP CompletionItem requires label; insertText, textEdit, + # and kind are all optional. + kind = item.get("kind", LSPTypes.CompletionItemKind.Text) completion_item = {} if "detail" in item: completion_item["detail"] = item["detail"] if "label" in item: completion_item["completionText"] = item["label"] - completion_item["kind"] = item["kind"] + completion_item["kind"] = kind elif "insertText" in item: completion_item["completionText"] = item["insertText"] - completion_item["kind"] = item["kind"] + completion_item["kind"] = kind elif "textEdit" in item and "newText" in item["textEdit"]: completion_item["completionText"] = item["textEdit"]["newText"] - completion_item["kind"] = item["kind"] + completion_item["kind"] = kind elif "textEdit" in item and "range" in item["textEdit"]: new_dot_lineno, new_dot_colno = ( completion_params["position"]["line"], @@ -595,7 +599,7 @@ async def request_completions( ) completion_item["completionText"] = item["textEdit"]["newText"] - completion_item["kind"] = item["kind"] + completion_item["kind"] = kind elif "textEdit" in item and "insert" in item["textEdit"]: assert False else: diff --git a/src/multilspy/language_servers/pyright_language_server/initialize_params.json b/src/multilspy/language_servers/pyright_language_server/initialize_params.json new file mode 100644 index 00000000..47aa89ec --- /dev/null +++ b/src/multilspy/language_servers/pyright_language_server/initialize_params.json @@ -0,0 +1,47 @@ +{ + "_description": "Conservative LSP 3.17 capabilities for the Python Pyright language server.", + "processId": "$processId", + "rootPath": "$rootPath", + "rootUri": "$rootUri", + "workspaceFolders": [ + {"name": "$name", "uri": "$uri"} + ], + "clientInfo": {"name": "multilspy"}, + "capabilities": { + "general": { + "positionEncodings": ["utf-16"] + }, + "workspace": { + "applyEdit": false, + "configuration": true, + "workspaceFolders": false, + "symbol": {"dynamicRegistration": false}, + "workspaceEdit": {"documentChanges": true} + }, + "textDocument": { + "definition": {"linkSupport": true}, + "declaration": {"linkSupport": true}, + "typeDefinition": {"linkSupport": true}, + "references": {}, + "hover": {"contentFormat": ["markdown", "plaintext"]}, + "completion": { + "dynamicRegistration": false, + "completionItem": { + "snippetSupport": false, + "documentationFormat": ["plaintext"] + } + }, + "signatureHelp": { + "dynamicRegistration": false, + "signatureInformation": { + "documentationFormat": ["plaintext"], + "parameterInformation": {"labelOffsetSupport": true} + } + }, + "rename": {"dynamicRegistration": false, "prepareSupport": true}, + "documentHighlight": {"dynamicRegistration": false}, + "documentSymbol": {"hierarchicalDocumentSymbolSupport": true}, + "publishDiagnostics": {"relatedInformation": true} + } + } +} diff --git a/src/multilspy/language_servers/pyright_language_server/pyright_server.py b/src/multilspy/language_servers/pyright_language_server/pyright_server.py index 7f46ca82..091e57ca 100644 --- a/src/multilspy/language_servers/pyright_language_server/pyright_server.py +++ b/src/multilspy/language_servers/pyright_language_server/pyright_server.py @@ -1,27 +1,35 @@ -"""Pyright LSP backend for multilspy's existing Python language API. +"""Pyright Python language server adapter for multilspy. -Pyright must already be installed. This backend doesn't download binaries, -edit project files, or require a VS Code extension process. +Uses the existing language server protocol handler and a preinstalled +pyright-langserver executable. No automatic provider install is performed. """ import asyncio +import json +import logging +import os +import pathlib +from collections.abc import AsyncIterator from contextlib import asynccontextmanager -from pathlib import Path -from typing import Any, AsyncIterator +from typing import Any from multilspy.language_server import LanguageServer -from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo +from multilspy.lsp_protocol_handler.lsp_types import ErrorCodes, InitializeParams +from multilspy.lsp_protocol_handler.server import Error, ProcessLaunchInfo from multilspy.multilspy_config import MultilspyConfig from multilspy.multilspy_logger import MultilspyLogger class PyrightServer(LanguageServer): - """Use pyright-langserver --stdio instead of the default Jedi backend.""" + """Python semantic requests using pyright-langserver --stdio.""" def __init__( - self, config: MultilspyConfig, logger: MultilspyLogger, repository_root_path: str + self, + config: MultilspyConfig, + logger: MultilspyLogger, + repository_root_path: str, ): - root = str(Path(repository_root_path).resolve()) + root = str(pathlib.Path(repository_root_path).resolve()) super().__init__( config, logger, @@ -32,11 +40,26 @@ def __init__( ), "python", ) + self._initialize_timeout_seconds = 30 self.diagnostics: asyncio.Queue[dict] = asyncio.Queue(maxsize=64) self.diagnostics_dropped = False + def _get_initialize_params(self, repository_absolute_path: str) -> InitializeParams: + """Load Pyright's read-only client capabilities, like other adapters.""" + config_file = pathlib.Path(__file__).with_name("initialize_params.json") + with config_file.open(encoding="utf-8") as reader: + params = json.load(reader) + del params["_description"] + root = pathlib.Path(repository_absolute_path).resolve() + params["processId"] = os.getpid() + params["rootPath"] = str(root) + params["rootUri"] = root.as_uri() + params["workspaceFolders"][0]["name"] = root.name + params["workspaceFolders"][0]["uri"] = root.as_uri() + return params + async def next_diagnostics(self, timeout: float = 5.0) -> dict: - """Read an asynchronous publishDiagnostics notification.""" + """Read one asynchronous publishDiagnostics notification.""" return await asyncio.wait_for(self.diagnostics.get(), timeout) @asynccontextmanager @@ -67,6 +90,9 @@ async def refuse_edit(_params: Any) -> dict: "failureReason": "multilspy Pyright client is read-only", } + async def refuse_registration(_params: Any) -> None: + raise Error(ErrorCodes.MethodNotFound, "Dynamic registration disabled") + async def diagnostics(params: Any) -> None: if not isinstance(params, dict) or not isinstance(params.get("uri"), str): return @@ -80,75 +106,48 @@ async def ignore_notification(_params: Any) -> None: self.server.on_request("workspace/configuration", configuration) self.server.on_request("workspace/applyEdit", refuse_edit) + self.server.on_request("client/registerCapability", refuse_registration) self.server.on_notification("textDocument/publishDiagnostics", diagnostics) self.server.on_notification("window/logMessage", ignore_notification) self.server.on_notification("$/progress", ignore_notification) async with super().start_server(): + self.logger.log("Starting Pyright language server process", logging.INFO) initialized = False try: await self.server.start() - root = Path(self.repository_root_path) - init = await asyncio.wait_for( + self.logger.log("Initializing Pyright language server", logging.INFO) + result = await asyncio.wait_for( self.server.send.initialize( - { - "processId": None, - "rootUri": root.as_uri(), - "rootPath": str(root), - "workspaceFolders": [ - {"uri": root.as_uri(), "name": root.name} - ], - "clientInfo": {"name": "multilspy"}, - "capabilities": { - "general": {"positionEncodings": ["utf-16"]}, - "workspace": { - "applyEdit": False, - "configuration": True, - "workspaceFolders": False, - "symbol": {}, - }, - "textDocument": { - "definition": {"linkSupport": True}, - "typeDefinition": {"linkSupport": True}, - "references": {}, - "hover": { - "contentFormat": ["markdown", "plaintext"] - }, - "completion": { - "completionItem": { - "snippetSupport": False, - "documentationFormat": ["plaintext"], - } - }, - "signatureHelp": { - "signatureInformation": { - "documentationFormat": ["plaintext"], - } - }, - "documentSymbol": { - "hierarchicalDocumentSymbolSupport": True - }, - "publishDiagnostics": { - "relatedInformation": True - }, - }, - }, - } + self._get_initialize_params(self.repository_root_path) ), - timeout=30, + timeout=self._initialize_timeout_seconds, + ) + capabilities = ( + result.get("capabilities") if isinstance(result, dict) else None ) - capabilities = init.get("capabilities") if isinstance(init, dict) else None if not isinstance(capabilities, dict): - raise ValueError("Invalid Pyright initialization capabilities") + raise TypeError("Invalid Pyright initialization capabilities") if capabilities.get("positionEncoding", "utf-16") != "utf-16": raise ValueError("Unsupported Pyright position encoding") + for required in ( + "definitionProvider", + "referencesProvider", + "hoverProvider", + ): + capability = capabilities.get(required) + if capability is not True and not isinstance(capability, dict): + raise ValueError( + f"Pyright missing required capability: {required}" + ) + self.server.notify.initialized({}) self.completions_available.set() initialized = True - yield self - finally: try: + yield self + finally: if initialized: await asyncio.wait_for(self.server.shutdown(), timeout=8) - finally: - await self.server.stop() + finally: + await self.server.stop() diff --git a/src/multilspy/multilspy_config.py b/src/multilspy/multilspy_config.py index 7b8c7975..73983ba4 100644 --- a/src/multilspy/multilspy_config.py +++ b/src/multilspy/multilspy_config.py @@ -34,8 +34,6 @@ class MultilspyConfig: Configuration parameters """ code_language: Language - # Preserve Jedi as the default Python backend; explicitly opt in to Pyright. - python_server: Literal["jedi", "pyright"] = "jedi" trace_lsp_communication: bool = False start_independent_lsp_process: bool = True @@ -48,6 +46,10 @@ class MultilspyConfig: # Ignored when server_binary is set. server_install_dir: Optional[str] = None + # Append new options after existing fields to preserve positional callers. + # Jedi remains the default; Pyright requires an explicit choice. + python_server: Literal["jedi", "pyright"] = "jedi" + @classmethod def from_dict(cls, env: dict): """ diff --git a/tests/multilspy/test_completion_responses.py b/tests/multilspy/test_completion_responses.py index 8f770d57..9bd52fc8 100644 --- a/tests/multilspy/test_completion_responses.py +++ b/tests/multilspy/test_completion_responses.py @@ -31,6 +31,9 @@ def server(tmp_path): ([[]], []), ([[ITEM]], EXPECTED), ([{"isIncomplete": False, "items": [ITEM]}], EXPECTED), + # A valid CompletionItem may be label-only, with no edit or kind. + ([[{"label": "example", "kind": 6}]], EXPECTED), + ([[{"label": "example"}]], [{"completionText": "example", "kind": 1}]), ([{"isIncomplete": True, "items": []}, None], []), ([{"isIncomplete": True, "items": []}, {"isIncomplete": False, "items": [ITEM]}], EXPECTED), ]) @@ -52,3 +55,22 @@ async def test_incomplete_completion_retries_are_bounded(server, allow_incomplet assert result == (EXPECTED if allow_incomplete else []) assert server.server.send.completion.await_count == 30 assert not server.open_file_buffers + +@pytest.mark.asyncio +async def test_retry_incomplete_completions_uses_protocol_trigger(server): + seen = [] + responses = [ + {"isIncomplete": True, "items": []}, + {"isIncomplete": True, "items": []}, + {"isIncomplete": False, "items": [ITEM]}, + ] + + async def completion(params): + seen.append(params["context"]["triggerKind"]) + return responses[len(seen) - 1] + + server.server.send.completion = AsyncMock(side_effect=completion) + result = await server.request_completions("example.py", 0, 0) + assert result == EXPECTED + assert seen == [1, 3, 3] + assert not server.open_file_buffers diff --git a/tests/multilspy/test_lsp_result_shapes.py b/tests/multilspy/test_lsp_result_shapes.py new file mode 100644 index 00000000..253ebcdf --- /dev/null +++ b/tests/multilspy/test_lsp_result_shapes.py @@ -0,0 +1,113 @@ +"""Normalize valid LSP return shapes across Python language server adapters. + +Like test_completion_responses.py, inject a mocked LSP response and verify the +language-agnostic API without launching or downloading a language server. +""" + +from contextlib import contextmanager +from types import SimpleNamespace + +import pytest + +from multilspy import LanguageServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + + +@pytest.fixture(params=("jedi", "pyright")) +def server(tmp_path, request): + (tmp_path / "example.py").write_text("def greet(): return 'hi'\n") + instance = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server=request.param, + ), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + + @contextmanager + def open_file(_relative_path): + yield + + instance.open_file = open_file + instance.server_started = True + return instance, tmp_path.resolve() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "response_kind", + ("location", "link_without_origin", "link_with_origin", "null", "empty"), +) +async def test_definition_accepts_lsp_3_17_result_variants(server, response_kind): + instance, root = server + uri = (root / "example.py").as_uri() + selection = { + "start": {"line": 0, "character": 4}, + "end": {"line": 0, "character": 9}, + } + variants = { + "location": {"uri": uri, "range": selection}, + "link_without_origin": { + "targetUri": uri, + "targetRange": selection, + "targetSelectionRange": selection, + }, + "link_with_origin": { + "originSelectionRange": selection, + "targetUri": uri, + "targetRange": selection, + "targetSelectionRange": selection, + }, + } + response = ( + None + if response_kind == "null" + else [] + if response_kind == "empty" + else [variants[response_kind]] + ) + + async def definition(_params): + return response + + instance.server.send = SimpleNamespace(definition=definition) + normalized = await instance.request_definition("example.py", 0, 5) + if response_kind in ("null", "empty"): + assert normalized == [] + else: + assert len(normalized) == 1 + assert normalized[0]["relativePath"] == "example.py" + assert normalized[0]["range"] == selection + + +@pytest.mark.asyncio +@pytest.mark.parametrize("response", (None, [])) +async def test_references_support_null_or_empty_list(server, response): + instance, _ = server + + async def references(_params): + return response + + instance.server.send = SimpleNamespace(references=references) + assert await instance.request_references("example.py", 0, 5) == [] + + +@pytest.mark.asyncio +async def test_references_preserve_valid_locations(server): + instance, root = server + target = root / "example.py" + span = { + "start": {"line": 0, "character": 4}, + "end": {"line": 0, "character": 9}, + } + + async def references(_params): + return [{"uri": target.as_uri(), "range": span}] + + instance.server.send = SimpleNamespace(references=references) + normalized = await instance.request_references("example.py", 0, 5) + assert len(normalized) == 1 + assert normalized[0]["relativePath"] == "example.py" + assert normalized[0]["range"] == span diff --git a/tests/multilspy/test_multilspy_pyright.py b/tests/multilspy/test_multilspy_pyright.py index 1ffa13d6..a0bb5a60 100644 --- a/tests/multilspy/test_multilspy_pyright.py +++ b/tests/multilspy/test_multilspy_pyright.py @@ -1,173 +1,296 @@ -"""Pyright backend regression tests; real provider is opt-in through env. +"""Pyright language-server integration, following the other adapter tests. -No auto-install, project clone or network request in the default test suite. +Use a disposable local workspace instead of cloning a remote repository. +The integration tests require an explicit, preinstalled Pyright executable; +they skip rather than download/install when it is unavailable. """ import asyncio import os -from contextlib import contextmanager from pathlib import Path -from types import SimpleNamespace import pytest -from multilspy.language_server import LanguageServer +from multilspy import LanguageServer, SyncLanguageServer from multilspy.language_servers.jedi_language_server.jedi_server import JediServer -from multilspy.language_servers.pyright_language_server.pyright_server import PyrightServer +from multilspy.language_servers.pyright_language_server.pyright_server import ( + PyrightServer, +) from multilspy.multilspy_config import Language, MultilspyConfig from multilspy.multilspy_exceptions import MultilspyException from multilspy.multilspy_logger import MultilspyLogger -def _server(tmp_path: Path, *, backend: str = "pyright", executable=None): - config = MultilspyConfig( - code_language=Language.PYTHON, python_server=backend, server_binary=executable +@pytest.fixture +def python_project(tmp_path): + root = tmp_path.resolve() + files = { + "lib.py": ("def greet(name: str) -> str:\n return name.upper()\n"), + "app.py": ( + "from lib import greet\n\nfirst = greet('Ada')\nsecond = greet('Bob')\n" + ), + "worker.py": ( + "class Worker:\n" + " def process(self) -> int:\n" + " return 3\n\n" + "worker = Worker()\n" + "result = worker.process()\n" + ), + "invalid.py": ("def faulty(name: str) -> str:\n return 123\n"), + } + for name, contents in files.items(): + (root / name).write_text(contents) + (root / "pyrightconfig.json").write_text( + '{"typeCheckingMode":"standard","include":["."]}\n' ) - return LanguageServer.create(config, MultilspyLogger(), str(tmp_path.resolve())) - + return root -def test_existing_python_users_still_get_jedi(tmp_path): - lsp = LanguageServer.create( - MultilspyConfig(code_language=Language.PYTHON), - MultilspyLogger(), - str(tmp_path), - ) - assert isinstance(lsp, JediServer) +@pytest.fixture +def pyright_binary(): + provided = os.environ.get("MULTILSPY_PYRIGHT_TEST_BINARY") + if not provided: + pytest.skip("Set MULTILSPY_PYRIGHT_TEST_BINARY to a preinstalled executable") + binary = Path(provided) + if not binary.is_absolute() or not binary.is_file(): + pytest.skip("The explicit Pyright executable is unavailable") + return str(binary) -def test_explicit_pyright_factory_uses_stdio_without_downloading(tmp_path): - executable = "/some/preinstalled/pyright-langserver" - lsp = _server(tmp_path, executable=executable) - assert isinstance(lsp, PyrightServer) - assert lsp.language_id == "python" - assert lsp.server.process_launch_info.cmd == [executable, "--stdio"] - assert lsp.server.process_launch_info.cwd == str(tmp_path.resolve()) - assert lsp.server.process is None +@pytest.fixture +def create_pyright(python_project, pyright_binary): + def create(): + return LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), + str(python_project), + ) -def test_pyright_default_binary_is_an_existing_install_requirement(tmp_path): - lsp = _server(tmp_path) - assert lsp.server.process_launch_info.cmd == [ - "pyright-langserver", - "--stdio", - ] - assert lsp.server.process is None + return create -def test_unknown_python_backend_is_not_silently_jedi(tmp_path): - with pytest.raises(MultilspyException, match="Unsupported Python"): - _server(tmp_path, backend="invalid") - - -@pytest.mark.parametrize("kind", ["location", "link"]) -def test_definition_accepts_location_and_optional_origin_link(tmp_path, kind): - """LocationLink.originSelectionRange is optional in LSP 3.17.""" - lsp = _server(tmp_path) - source = tmp_path / "example.py" - source.write_text("def hello(): return 1\n") - location = source.resolve().as_uri() - span = { - "start": {"line": 0, "character": 4}, - "end": {"line": 0, "character": 9}, - } - response = ( - {"uri": location, "range": span} - if kind == "location" - else { - "targetUri": location, - "targetRange": span, - "targetSelectionRange": span, - # No originSelectionRange! - } +@pytest.mark.parametrize( + "backend, expected", + [ + ("jedi", JediServer), + ("pyright", PyrightServer), + ], +) +def test_python_backend_selection_is_explicit(tmp_path, backend, expected): + instance = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server=backend, + ), + MultilspyLogger(), + str(tmp_path.resolve()), ) + assert isinstance(instance, expected) + assert instance.server.process is None - @contextmanager - def noop_open(_path: str): - yield - async def definition(_params): - return [response] +def test_existing_jedi_default_and_explicit_server_command(tmp_path): + root = str(tmp_path.resolve()) + default = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON), + MultilspyLogger(), + root, + ) + assert isinstance(default, JediServer) + pyright = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary="/preinstalled/pyright-langserver", + ), + MultilspyLogger(), + root, + ) + assert pyright.server.process_launch_info.cmd == [ + "/preinstalled/pyright-langserver", + "--stdio", + ] + assert pyright.server.process_launch_info.cwd == root + assert pyright.server.process is None - lsp.server_started = True - lsp.open_file = noop_open - lsp.server.send = SimpleNamespace(definition=definition) - actual = asyncio.run(lsp.request_definition("example.py", 0, 5)) - assert len(actual) == 1 - assert actual[0]["relativePath"] == "example.py" - assert actual[0]["range"] == span +def test_existing_positional_config_arguments_are_unchanged(): + config = MultilspyConfig(Language.PYTHON, True, False, None, None) + assert config.trace_lsp_communication is True + assert config.start_independent_lsp_process is False + assert config.server_binary is None + assert config.server_install_dir is None + assert config.python_server == "jedi" -def test_null_references_become_empty_list(tmp_path): - lsp = _server(tmp_path) - (tmp_path / "example.py").write_text("hello = 1\n") - @contextmanager - def noop_open(_path: str): - yield +def test_pyright_selection_through_from_dict_and_sync_factory(tmp_path): + config = MultilspyConfig.from_dict( + { + "code_language": Language.PYTHON, + "python_server": "pyright", + "server_binary": "/preinstalled/pyright-langserver", + } + ) + sync = SyncLanguageServer.create( + config, MultilspyLogger(), str(tmp_path.resolve()), timeout=15 + ) + assert isinstance(sync.language_server, PyrightServer) + assert sync.language_server.server.process is None - async def references(_params): - return None - lsp.server_started = True - lsp.open_file = noop_open - lsp.server.send = SimpleNamespace(references=references) - assert asyncio.run(lsp.request_references("example.py", 0, 2)) == [] +def test_invalid_python_backend_cannot_fall_back_to_jedi(tmp_path): + config = MultilspyConfig( + code_language=Language.PYTHON, + python_server="unknown", + ) + with pytest.raises(MultilspyException, match="Unsupported Python"): + LanguageServer.create(config, MultilspyLogger(), str(tmp_path.resolve())) -def test_real_pyright_navigation_and_diagnostics(tmp_path): - """Optional official Pyright LSP integration, no implicit install.""" - executable = os.environ.get("MULTILSPY_PYRIGHT_TEST_BINARY") - if not executable: - pytest.skip("Set MULTILSPY_PYRIGHT_TEST_BINARY to a trusted binary") - binary = Path(executable) - if not binary.is_absolute() or not binary.is_file(): - pytest.skip("Explicit Pyright binary not found") - root = tmp_path.resolve() - source = root / "sample.py" - original = ( - "def say_hello(name: str) -> str:\n" - " return 123\n" - "\n" - "answer = say_hello('Ada')\n" - ) - source.write_text(original) - (root / "pyrightconfig.json").write_text('{"typeCheckingMode":"standard"}') - lsp = _server(root, executable=str(binary)) +@pytest.mark.asyncio +async def test_real_pyright_definition_references_hover_and_symbols( + python_project, + create_pyright, +): + server = create_pyright() async def exercise(): - async with lsp.start_server(): + async with server.start_server(): definition = await asyncio.wait_for( - lsp.request_definition("sample.py", 3, 12), 8 + server.request_definition("app.py", 2, 9), timeout=8 ) assert len(definition) == 1 - assert definition[0]["relativePath"] == "sample.py" + assert definition[0]["relativePath"] == "lib.py" + assert definition[0]["range"]["start"] == {"line": 0, "character": 4} + references = await asyncio.wait_for( - lsp.request_references("sample.py", 0, 4), 8 + server.request_references("lib.py", 0, 5), timeout=8 ) - assert isinstance(references, list) - assert len(references) >= 1 + assert len(references) >= 2 + assert all(item["relativePath"] == "app.py" for item in references) + hover = await asyncio.wait_for( - lsp.request_hover("sample.py", 3, 12), 8 + server.request_hover("app.py", 2, 10), timeout=8 + ) + assert hover and "contents" in hover + + symbols, _ = await asyncio.wait_for( + server.request_document_symbols("lib.py"), timeout=8 + ) + assert "greet" in {entry["name"] for entry in symbols} + + workspace_symbols = [] + for _ in range(15): + workspace_symbols = await asyncio.wait_for( + server.request_workspace_symbol("greet"), timeout=8 + ) + if workspace_symbols: + break + await asyncio.sleep(0.1) + assert any(item["name"] == "greet" for item in workspace_symbols) + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + + +@pytest.mark.asyncio +async def test_real_pyright_high_level_completions_and_signature( + python_project, + create_pyright, +): + server = create_pyright() + + async def exercise(): + async with server.start_server(): + # Use the same high-level API as the existing Jedi/Rust tests. + suggestions = await asyncio.wait_for( + server.request_completions("worker.py", 5, len("result = worker.")), + timeout=8, ) - assert hover is not None - # A push diagnostic is asynchronous and can arrive after - # an earlier empty didClose diagnostic for the same URI. - while not lsp.diagnostics.empty(): - lsp.diagnostics.get_nowait() - with lsp.open_file("sample.py"): - observed = set() - for _ in range(10): - message = await lsp.next_diagnostics(timeout=2) - if message.get("uri") != source.as_uri(): + assert "process" in {item["completionText"] for item in suggestions} + + with server.open_file("app.py"): + signature = await asyncio.wait_for( + server.server.send.signature_help( + { + "textDocument": { + "uri": (python_project / "app.py").as_uri() + }, + "position": {"line": 2, "character": len("first = greet(")}, + } + ), + timeout=8, + ) + assert signature and signature["signatures"] + assert "name: str" in signature["signatures"][0]["label"] + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + + +@pytest.mark.asyncio +async def test_real_pyright_publishes_type_diagnostics_without_editing( + python_project, + create_pyright, +): + server = create_pyright() + source = python_project / "invalid.py" + before = source.read_bytes() + + async def exercise(): + async with server.start_server(): + with server.open_file("invalid.py"): + found = set() + # Allow delayed cold starts: a short timeout is not a failure. + loop = asyncio.get_running_loop() + deadline = loop.time() + 18 + while loop.time() < deadline: + try: + notification = await server.next_diagnostics( + timeout=min(2, max(0.01, deadline - loop.time())) + ) + except asyncio.TimeoutError: continue - observed.update( - item.get("code") - for item in message.get("diagnostics", []) - if isinstance(item, dict) + if notification.get("uri") != source.as_uri(): + continue + found.update( + entry.get("code") + for entry in notification.get("diagnostics", []) + if isinstance(entry, dict) ) - if "reportReturnType" in observed: + if "reportReturnType" in found: break - assert "reportReturnType" in observed - asyncio.run(asyncio.wait_for(exercise(), timeout=30)) - assert lsp.server.process is None - assert source.read_text() == original + assert "reportReturnType" in found + + await asyncio.wait_for(exercise(), timeout=30) + assert source.read_bytes() == before + assert server.server.process is None + + +def test_real_pyright_sync_api_works_and_closes_provider( + python_project, + pyright_binary, +): + sync = SyncLanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), + str(python_project), + timeout=15, + ) + with sync.start_server(): + definition = sync.request_definition("app.py", 2, 9) + assert len(definition) == 1 + assert definition[0]["relativePath"] == "lib.py" + completion = sync.request_completions("worker.py", 5, len("result = worker.")) + assert "process" in {item["completionText"] for item in completion} + assert sync.language_server.server.process is None + assert sync.loop.is_closed() + assert not sync.loop_thread.is_alive() diff --git a/tests/multilspy/test_pyright_adapter_notifications.py b/tests/multilspy/test_pyright_adapter_notifications.py new file mode 100644 index 00000000..61d8ffd6 --- /dev/null +++ b/tests/multilspy/test_pyright_adapter_notifications.py @@ -0,0 +1,269 @@ +"""Pyright adapter callbacks and startup behavior without a language-server process. + +Mirrors the mock-transport pattern from test_adapter_notifications.py. +""" + +import asyncio +import os +from unittest.mock import AsyncMock, Mock + +import pytest + +from multilspy.language_server import LanguageServer +from multilspy.language_servers.pyright_language_server.pyright_server import ( + PyrightServer, +) +from multilspy.lsp_protocol_handler.lsp_types import ErrorCodes +from multilspy.lsp_protocol_handler.server import Error +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + + +@pytest.fixture +def pyright(tmp_path): + server = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON, python_server="pyright"), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + assert isinstance(server, PyrightServer) + requests, notifications = {}, {} + transport = Mock() + transport.on_request.side_effect = lambda method, handler: requests.update( + {method: handler} + ) + transport.on_notification.side_effect = lambda method, handler: ( + notifications.update({method: handler}) + ) + transport.start = AsyncMock() + transport.shutdown = AsyncMock() + transport.stop = AsyncMock() + transport.send.initialize = AsyncMock( + return_value={ + "capabilities": { + "definitionProvider": True, + "referencesProvider": True, + "hoverProvider": True, + "textDocumentSync": 2, + } + } + ) + server.server = transport + return server, transport, requests, notifications + + +def test_pyright_initialize_params_are_loaded_from_profile(tmp_path): + server = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON, python_server="pyright"), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + params = server._get_initialize_params(str(tmp_path.resolve())) + assert "_description" not in params + assert params["processId"] == os.getpid() + assert params["rootUri"] == tmp_path.resolve().as_uri() + assert params["rootPath"] == str(tmp_path.resolve()) + assert params["workspaceFolders"] == [ + {"name": tmp_path.resolve().name, "uri": tmp_path.resolve().as_uri()} + ] + assert params["capabilities"]["general"]["positionEncodings"] == ["utf-16"] + assert params["capabilities"]["workspace"]["applyEdit"] is False + assert params["capabilities"]["workspace"]["configuration"] is True + assert params["capabilities"]["textDocument"]["completion"] + assert params["capabilities"]["textDocument"]["signatureHelp"] + + +@pytest.mark.asyncio +async def test_pyright_initializes_and_cleans_up_like_existing_adapters(pyright): + server, transport, requests, notifications = pyright + async with server.start_server(): + assert server.server_started + assert server.completions_available.is_set() + transport.send.initialize.assert_awaited_once() + transport.notify.initialized.assert_called_once_with({}) + assert "workspace/configuration" in requests + assert "workspace/applyEdit" in requests + assert "client/registerCapability" in requests + assert "textDocument/publishDiagnostics" in notifications + assert "window/logMessage" in notifications + assert "$/progress" in notifications + assert transport.start.await_count == 1 + assert not server.server_started + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_accepts_empty_capability_options(pyright): + server, transport, _, _ = pyright + transport.send.initialize.return_value = { + "capabilities": { + "definitionProvider": {}, + "referencesProvider": {}, + "hoverProvider": {}, + "positionEncoding": "utf-16", + } + } + async with server.start_server(): + assert server.server_started + assert server.completions_available.is_set() + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_configuration_is_explicit_and_bounded(pyright): + server, _, requests, _ = pyright + async with server.start_server(): + handler = requests["workspace/configuration"] + result = await handler( + { + "items": [ + {"section": "python"}, + {"section": "pyright"}, + {"section": "untrusted"}, + ] + } + ) + assert result[0] == {"analysis": {}} + assert result[1]["disableLanguageServices"] is False + assert result[2] is None + assert await handler({"items": []}) == [] + assert await handler({"items": "bad"}) == [] + assert await handler({"items": [{}] * 65}) == [] + assert await handler(None) == [] + + +@pytest.mark.asyncio +async def test_pyright_refuses_edit_and_unadvertised_registration(pyright): + server, _, requests, _ = pyright + async with server.start_server(): + result = await requests["workspace/applyEdit"]( + {"edit": {"changes": {"file:///tmp/example.py": []}}} + ) + assert result["applied"] is False + assert "read-only" in result["failureReason"] + with pytest.raises(Error) as caught: + await requests["client/registerCapability"]( + {"registrations": [{"method": "workspace/executeCommand"}]} + ) + assert caught.value.code == ErrorCodes.MethodNotFound + + +@pytest.mark.asyncio +async def test_pyright_diagnostics_are_queued_not_dropped_silently(pyright): + server, _, _, notifications = pyright + async with server.start_server(): + await notifications["textDocument/publishDiagnostics"](None) + await notifications["textDocument/publishDiagnostics"]({"uri": 12}) + assert server.diagnostics.empty() + for i in range(64): + await notifications["textDocument/publishDiagnostics"]( + { + "uri": "file:///tmp/example.py", + "diagnostics": [], + "version": i, + } + ) + assert server.diagnostics.full() + await notifications["textDocument/publishDiagnostics"]( + { + "uri": "file:///tmp/example.py", + "version": 65, + } + ) + assert server.diagnostics_dropped is True + assert (await server.next_diagnostics(timeout=1))["version"] == 0 + assert (await server.next_diagnostics(timeout=1))["version"] == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "capabilities, exception, error", + [ + (None, TypeError, "Invalid Pyright"), + ([], TypeError, "Invalid Pyright"), + ({}, ValueError, "Pyright missing required capability"), + ( + { + "definitionProvider": True, + "referencesProvider": True, + "hoverProvider": True, + "positionEncoding": "utf-8", + }, + ValueError, + "Unsupported Pyright position", + ), + ], +) +async def test_bad_initialize_rejected_and_process_stopped( + pyright, capabilities, exception, error +): + server, transport, _, _ = pyright + transport.send.initialize.return_value = {"capabilities": capabilities} + with pytest.raises(exception, match=error): + async with server.start_server(): + pytest.fail("Malformed capabilities cannot enable a server") + transport.stop.assert_awaited_once() + transport.shutdown.assert_not_awaited() + assert not server.server_started + + +@pytest.mark.asyncio +async def test_failed_initialize_request_still_stops_provider(pyright): + server, transport, _, _ = pyright + transport.send.initialize.side_effect = TimeoutError("synthetic") + with pytest.raises(TimeoutError): + async with server.start_server(): + pytest.fail("Initialize must fail") + transport.stop.assert_awaited_once() + transport.shutdown.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_failed_process_start_still_enters_stop_cleanup(pyright): + server, transport, _, _ = pyright + transport.start.side_effect = OSError("synthetic failed spawn") + with pytest.raises(OSError): + async with server.start_server(): + pytest.fail("Process start must fail") + transport.stop.assert_awaited_once() + transport.shutdown.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_shutdown_error_never_skips_process_stop(pyright): + server, transport, _, _ = pyright + transport.shutdown.side_effect = RuntimeError("synthetic shutdown failure") + with pytest.raises(RuntimeError, match="shutdown failure"): + async with server.start_server(): + assert server.server_started + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + assert not server.server_started + + +@pytest.mark.asyncio +async def test_cancelled_initialize_still_stops_process(pyright): + server, transport, _, _ = pyright + ready = asyncio.Event() + block = asyncio.Event() + + async def initialize(_params): + ready.set() + await block.wait() + + transport.send.initialize.side_effect = initialize + + async def enter_context(): + async with server.start_server(): + pytest.fail("Cancelled initialization cannot enter context") + + task = asyncio.create_task(enter_context()) + await asyncio.wait_for(ready.wait(), 2) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + transport.stop.assert_awaited_once() + transport.shutdown.assert_not_awaited() + assert not server.server_started diff --git a/tests/multilspy/test_pyright_process_lifecycle.py b/tests/multilspy/test_pyright_process_lifecycle.py new file mode 100644 index 00000000..810a0dae --- /dev/null +++ b/tests/multilspy/test_pyright_process_lifecycle.py @@ -0,0 +1,111 @@ +"""Pyright startup timeout/cancellation against a real but nonresponsive peer. + +These process-level tests mirror test_sync_startup.py: they launch only a +local disposable Python script, never install or discover Pyright. +""" + +import asyncio +import sys + +import pytest + +from multilspy.language_server import LanguageServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger + + +@pytest.fixture +def hung_stdio_server(tmp_path): + script = tmp_path / "silent_lsp.py" + script.write_text( + "import sys\n" + "for line in sys.stdin.buffer:\n" + " pass # Read incoming LSP frames; never answer initialize.\n" + ) + return script + + +@pytest.fixture +def pyright_with_fake_transport(tmp_path, hung_stdio_server): + server = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + ), + MultilspyLogger(), + str(tmp_path.resolve()), + ) + handler = server.server + handler.process_launch_info.cmd = [ + sys.executable, + "-u", + str(hung_stdio_server), + ] + started = asyncio.Event() + created = [] + native_start = handler.start + + async def capture_process(): + await native_start() + created.append(handler.process) + started.set() + + handler.start = capture_process + return server, handler, created, started + + +@pytest.mark.asyncio +async def test_real_initialize_timeout_stops_process_and_readers( + pyright_with_fake_transport, +): + server, handler, created, _started = pyright_with_fake_transport + server._initialize_timeout_seconds = 0.05 + + async def exercise(): + async with server.start_server(): + pytest.fail("No response from synthetic LSP server") + + try: + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(exercise(), timeout=5) + assert len(created) == 1 + assert created[0].returncode is not None + assert handler.process is None + assert handler.tasks == {} + assert not server.server_started + finally: + for process in created: + if process.returncode is None: + process.kill() + await process.wait() + + +@pytest.mark.asyncio +async def test_real_cancelled_initialize_stops_process_and_readers( + pyright_with_fake_transport, +): + server, handler, created, started = pyright_with_fake_transport + + async def exercise(): + async with server.start_server(): + pytest.fail("Cancelled startup must not enter the context") + + pending = asyncio.create_task(exercise()) + try: + await asyncio.wait_for(started.wait(), timeout=3) + assert len(created) == 1 + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(pending, timeout=5) + assert created[0].returncode is not None + assert handler.process is None + assert handler.tasks == {} + assert not server.server_started + finally: + if not pending.done(): + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + for process in created: + if process.returncode is None: + process.kill() + await process.wait() From 7bb01213eb7eaaa80ce08048af05052b63eb6b18 Mon Sep 17 00:00:00 2001 From: Grammy Jiang Date: Thu, 22 Oct 2026 00:30:16 +1100 Subject: [PATCH 3/8] test(pyright): assert Pyright 1.1.413 capability matrix and read-only request shapes Add a binary version check, an advertised-capability matrix test, one data-driven corpus of exact low-level payloads (declaration, type definition, highlights, prepare rename, signature help, call hierarchy, UTF-16 non-BMP columns, null results, code action, rename proposal, completion resolve, MethodNotFound for unadvertised requests), and push diagnostics for every typeCheckingMode. Document the capability matrix in the README. 74 passed on Linux ARM64 with real Pyright 1.1.413. Co-Authored-By: Claude Fable 5.1 --- README.md | 18 ++ tests/multilspy/test_multilspy_pyright.py | 306 ++++++++++++++++++++++ 2 files changed, 324 insertions(+) diff --git a/README.md b/README.md index 695acced..3d21246b 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,24 @@ argument and does not download/install Pyright. If server_binary is omitted, it uses pyright-langserver from PATH. The existing MultilspyConfig(code_language=Language.PYTHON) continues using Jedi. +Positions follow LSP: line and column are zero-based and the column counts +UTF-16 code units, so a non-BMP character such as an emoji occupies two columns. + +The adapter was validated against Pyright 1.1.413 (`pyright-langserver --stdio`). +The table lists what that release advertises to multilspy's read-only client +and how multilspy exposes it: + +| Pyright capability | multilspy access | Coverage | +| --- | --- | --- | +| definition, references, hover, document symbols, workspace symbols | `request_definition`, `request_references`, `request_hover`, `request_document_symbols`, `request_workspace_symbol` | tested against Pyright | +| completion, completionItem/resolve | `request_completions`; resolve through `server.send.resolve_completion_item` | tested against Pyright | +| declaration, typeDefinition, documentHighlight, signatureHelp, call hierarchy | `server.send.*` low-level requests | tested against Pyright | +| prepareRename, rename, codeAction | `server.send.*`; the response is a proposal, multilspy never applies edits | proposal shape tested; no quick-fix corpus | +| publishDiagnostics (off/basic/standard/strict) | `next_diagnostics()` bounded queue | tested against Pyright | +| workspace/configuration, workspace/applyEdit, client/registerCapability | answered by the adapter: fixed read-only settings, edits refused, registration refused | tested with fixtures | +| executeCommand | advertised with an empty command list | unsupported | +| implementation, pull diagnostics, semantic tokens, inlay hints, folding, selection ranges, document links, formatting, code lens | not advertised by Pyright 1.1.413; requests fail with MethodNotFound | unsupported | + Real Pyright integration tests require a preinstalled language server. Set MULTILSPY_PYRIGHT_TEST_BINARY to its absolute executable path before running pytest on tests/multilspy/test_multilspy_pyright.py. Without this variable diff --git a/tests/multilspy/test_multilspy_pyright.py b/tests/multilspy/test_multilspy_pyright.py index a0bb5a60..fed58a9b 100644 --- a/tests/multilspy/test_multilspy_pyright.py +++ b/tests/multilspy/test_multilspy_pyright.py @@ -6,7 +6,10 @@ """ import asyncio +import json import os +import re +import subprocess from pathlib import Path import pytest @@ -16,10 +19,54 @@ from multilspy.language_servers.pyright_language_server.pyright_server import ( PyrightServer, ) +from multilspy.lsp_protocol_handler.lsp_types import ErrorCodes +from multilspy.lsp_protocol_handler.server import Error from multilspy.multilspy_config import Language, MultilspyConfig from multilspy.multilspy_exceptions import MultilspyException from multilspy.multilspy_logger import MultilspyLogger +# The adapter and the expectations below were validated against this release. +TESTED_PYRIGHT_VERSION = (1, 1, 413) + +# Server capabilities that pyright-langserver 1.1.413 advertises to this +# read-only client, and well-known ones it does not advertise. +ADVERTISED_CAPABILITIES = { + "callHierarchyProvider", + "codeActionProvider", + "completionProvider", + "declarationProvider", + "definitionProvider", + "documentHighlightProvider", + "documentSymbolProvider", + "executeCommandProvider", + "hoverProvider", + "referencesProvider", + "renameProvider", + "signatureHelpProvider", + "textDocumentSync", + "typeDefinitionProvider", + "workspace", + "workspaceSymbolProvider", +} +UNADVERTISED_CAPABILITIES = { + "codeLensProvider", + "diagnosticProvider", + "documentFormattingProvider", + "documentLinkProvider", + "foldingRangeProvider", + "implementationProvider", + "inlayHintProvider", + "selectionRangeProvider", + "semanticTokensProvider", +} + + +def _range(start_line, start_character, end_line, end_character): + return { + "start": {"line": start_line, "character": start_character}, + "end": {"line": end_line, "character": end_character}, + } + @pytest.fixture def python_project(tmp_path): @@ -37,6 +84,9 @@ def python_project(tmp_path): "result = worker.process()\n" ), "invalid.py": ("def faulty(name: str) -> str:\n return 123\n"), + # The emoji is one code point but two UTF-16 code units; the second + # `x` is at UTF-16 column 14 (code-point column 13). + "emoji.py": ("x = '\U0001F600'; y = x\n"), } for name, contents in files.items(): (root / name).write_text(contents) @@ -294,3 +344,259 @@ def test_real_pyright_sync_api_works_and_closes_provider( assert sync.language_server.server.process is None assert sync.loop.is_closed() assert not sync.loop_thread.is_alive() + + +def test_real_pyright_binary_reports_tested_version(pyright_binary): + # pyright-langserver has no --version flag; the sibling pyright CLI + # installed by the same package reports the shared version. + reported = [] + for candidate in (pyright_binary, str(Path(pyright_binary).with_name("pyright"))): + if not Path(candidate).is_file(): + continue + completed = subprocess.run( + [candidate, "--version"], capture_output=True, text=True, timeout=30 + ) + match = re.search(r"pyright (\d+)\.(\d+)\.(\d+)", completed.stdout + completed.stderr) + if completed.returncode == 0 and match: + reported.append(tuple(int(part) for part in match.groups())) + assert reported, "No executable next to the language server reports a Pyright version" + assert all(version >= TESTED_PYRIGHT_VERSION for version in reported) + + +@pytest.mark.asyncio +async def test_real_pyright_advertised_capabilities_match_matrix(create_pyright): + server = create_pyright() + native_initialize = server.server.send.initialize + captured = {} + + async def initialize(params): + captured["result"] = await native_initialize(params) + return captured["result"] + + server.server.send.initialize = initialize + + async def exercise(): + async with server.start_server(): + pass + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + capabilities = captured["result"]["capabilities"] + assert ADVERTISED_CAPABILITIES <= set(capabilities) + assert UNADVERTISED_CAPABILITIES.isdisjoint(capabilities) + assert capabilities["textDocumentSync"] == 2 + assert capabilities["completionProvider"]["resolveProvider"] is True + assert capabilities["completionProvider"]["triggerCharacters"] == [".", "[", '"', "'"] + assert capabilities["signatureHelpProvider"]["triggerCharacters"] == ["(", ",", ")"] + assert capabilities["renameProvider"]["prepareProvider"] is True + assert capabilities["codeActionProvider"]["codeActionKinds"] == [ + "quickfix", + "source.organizeImports", + ] + # Pyright registers no server commands for a client without applyEdit. + assert capabilities["executeCommandProvider"]["commands"] == [] + + +@pytest.mark.asyncio +async def test_real_pyright_read_only_requests_return_exact_shapes( + python_project, + create_pyright, +): + """One server session covers the advertised read-only requests. + + Every expectation is the exact payload returned by Pyright 1.1.413 for the + temporary project. Rename and code actions are proposals only: the files + on disk are compared byte for byte afterwards. + """ + server = create_pyright() + before = {path: path.read_bytes() for path in python_project.glob("*.py")} + + def uri(name): + return (python_project / name).as_uri() + + def at(name, line, character): + return { + "textDocument": {"uri": uri(name)}, + "position": {"line": line, "character": character}, + } + + greet_call_sites = [_range(2, 8, 2, 13), _range(3, 9, 3, 14)] + corpus = [ + ("declaration", at("app.py", 2, 9), [{"uri": uri("lib.py"), "range": _range(0, 4, 0, 9)}]), + ("type_definition", at("worker.py", 4, 0), [{"uri": uri("worker.py"), "range": _range(0, 6, 0, 12)}]), + ( + "document_highlight", + at("app.py", 2, 9), + [ + {"kind": 3, "range": _range(0, 16, 0, 21)}, + {"kind": 2, "range": greet_call_sites[0]}, + {"kind": 2, "range": greet_call_sites[1]}, + ], + ), + ("prepare_rename", at("lib.py", 0, 5), _range(0, 4, 0, 9)), + ( + "signature_help", + at("app.py", 2, len("first = greet(")), + { + "activeParameter": 0, + "activeSignature": 0, + "signatures": [ + { + "activeParameter": 0, + "label": "(name: str) -> str", + "parameters": [ + {"documentation": {"kind": "plaintext", "value": ""}, "label": [1, 10]} + ], + } + ], + }, + ), + ( + "prepare_call_hierarchy", + at("lib.py", 0, 5), + [ + { + "kind": 12, + "name": "greet", + "uri": uri("lib.py"), + "range": _range(0, 4, 0, 9), + "selectionRange": _range(0, 4, 0, 9), + } + ], + ), + # UTF-16 column 14 is the second `x`; a code-point column would miss it. + ("definition", at("emoji.py", 0, 14), [{"uri": uri("emoji.py"), "range": _range(0, 0, 0, 1)}]), + # Blank line: Pyright answers null, never an error. + ("hover", at("app.py", 1, 0), None), + ("definition", at("app.py", 1, 0), None), + ("references", {**at("app.py", 1, 0), "context": {"includeDeclaration": True}}, None), + ( + "code_action", + { + "textDocument": {"uri": uri("app.py")}, + "range": _range(0, 0, 0, 20), + "context": {"diagnostics": []}, + }, + [], + ), + ] + + async def exercise(): + async with server.start_server(): + send = server.server.send + with server.open_file("app.py"), server.open_file("lib.py"), server.open_file( + "worker.py" + ), server.open_file("emoji.py"): + for method, params, expected in corpus: + result = await asyncio.wait_for(getattr(send, method)(params), timeout=8) + assert result == expected, method + + # The high-level API passes UTF-16 columns through unchanged. + definition = await asyncio.wait_for( + server.request_definition("emoji.py", 0, 14), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in definition] == [ + ("emoji.py", _range(0, 0, 0, 1)) + ] + assert await asyncio.wait_for( + server.request_hover("app.py", 1, 0), timeout=8 + ) is None + assert await asyncio.wait_for( + server.request_references("app.py", 1, 0), timeout=8 + ) == [] + + calls = await asyncio.wait_for( + send.incoming_calls( + {"item": (await send.prepare_call_hierarchy(at("lib.py", 0, 5)))[0]} + ), + timeout=8, + ) + assert [(call["from"]["name"], call["from"]["uri"], call["fromRanges"]) for call in calls] == [ + ("(module) app.py", uri("app.py"), greet_call_sites) + ] + + # Rename is a WorkspaceEdit proposal; nothing is applied. + proposal = await asyncio.wait_for( + send.rename({**at("lib.py", 0, 5), "newName": "salute"}), timeout=8 + ) + changes = sorted(proposal["documentChanges"], key=lambda change: change["textDocument"]["uri"]) + assert changes == [ + { + "textDocument": {"uri": uri("app.py"), "version": None}, + "edits": [ + {"range": _range(0, 16, 0, 21), "newText": "salute"}, + {"range": greet_call_sites[0], "newText": "salute"}, + {"range": greet_call_sites[1], "newText": "salute"}, + ], + }, + { + "textDocument": {"uri": uri("lib.py"), "version": None}, + "edits": [{"range": _range(0, 4, 0, 9), "newText": "salute"}], + }, + ] + + # completionItem/resolve adds documentation to a raw item. + completion = await asyncio.wait_for( + send.completion({**at("worker.py", 5, len("result = worker.")), "context": {"triggerKind": 1}}), + timeout=8, + ) + item = next(entry for entry in completion["items"] if entry["label"] == "process") + resolved = await asyncio.wait_for(send.resolve_completion_item(item), timeout=8) + assert resolved["documentation"] == {"kind": "plaintext", "value": "def process() -> int"} + assert resolved["kind"] == 2 + + # Unadvertised requests fail with MethodNotFound instead of hanging. + with pytest.raises(Error) as unsupported: + await asyncio.wait_for(send.implementation(at("lib.py", 0, 5)), timeout=8) + assert unsupported.value.code == ErrorCodes.MethodNotFound + with pytest.raises(Error): + await asyncio.wait_for( + send.execute_command({"command": "pyright.doesNotExist", "arguments": []}), + timeout=8, + ) + + await asyncio.wait_for(exercise(), timeout=60) + assert server.server.process is None + assert {path: path.read_bytes() for path in python_project.glob("*.py")} == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "mode, expected_codes", + [ + ("off", set()), + ("basic", {"reportReturnType"}), + ("standard", {"reportReturnType"}), + ("strict", {"reportReturnType"}), + ], +) +async def test_real_pyright_type_checking_mode_controls_push_diagnostics( + python_project, + create_pyright, + mode, + expected_codes, +): + (python_project / "pyrightconfig.json").write_text( + json.dumps({"typeCheckingMode": mode, "include": ["."]}) + ) + server = create_pyright() + source = python_project / "invalid.py" + + async def exercise(): + async with server.start_server(): + with server.open_file("invalid.py"): + # Pyright publishes once per open file, also when the list is empty. + loop = asyncio.get_running_loop() + deadline = loop.time() + 18 + while True: + notification = await server.next_diagnostics( + timeout=max(0.01, deadline - loop.time()) + ) + if notification["uri"] == source.as_uri(): + return notification["diagnostics"] + + diagnostics = await asyncio.wait_for(exercise(), timeout=30) + assert {entry["code"] for entry in diagnostics} == expected_codes + assert all(entry["severity"] == 1 for entry in diagnostics) + assert server.server.process is None + assert not server.diagnostics_dropped From 765957bd6d2d3afe5c1647d53b35d61b9d2a4f91 Mon Sep 17 00:00:00 2001 From: Grammy Jiang Date: Thu, 22 Oct 2026 01:17:18 +1100 Subject: [PATCH 4/8] fix(pyright): finish advertised LSP coverage and cross-platform tests --- README.md | 15 +- .../initialize_params.json | 7 + .../pyright_language_server/pyright_server.py | 180 +++-- tests/multilspy/test_multilspy_pyright.py | 717 +++++++++++++----- .../test_pyright_adapter_notifications.py | 19 +- 5 files changed, 643 insertions(+), 295 deletions(-) diff --git a/README.md b/README.md index 3d21246b..8f4ab183 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,8 @@ MultilspyConfig(code_language=Language.PYTHON) continues using Jedi. Positions follow LSP: line and column are zero-based and the column counts UTF-16 code units, so a non-BMP character such as an emoji occupies two columns. +Type checking is configured by the project (pyrightconfig.json or pyproject.toml); +the adapter does not override `typeCheckingMode`. The adapter was validated against Pyright 1.1.413 (`pyright-langserver --stdio`). The table lists what that release advertises to multilspy's read-only client @@ -87,12 +89,13 @@ and how multilspy exposes it: | Pyright capability | multilspy access | Coverage | | --- | --- | --- | | definition, references, hover, document symbols, workspace symbols | `request_definition`, `request_references`, `request_hover`, `request_document_symbols`, `request_workspace_symbol` | tested against Pyright | -| completion, completionItem/resolve | `request_completions`; resolve through `server.send.resolve_completion_item` | tested against Pyright | -| declaration, typeDefinition, documentHighlight, signatureHelp, call hierarchy | `server.send.*` low-level requests | tested against Pyright | -| prepareRename, rename, codeAction | `server.send.*`; the response is a proposal, multilspy never applies edits | proposal shape tested; no quick-fix corpus | -| publishDiagnostics (off/basic/standard/strict) | `next_diagnostics()` bounded queue | tested against Pyright | -| workspace/configuration, workspace/applyEdit, client/registerCapability | answered by the adapter: fixed read-only settings, edits refused, registration refused | tested with fixtures | -| executeCommand | advertised with an empty command list | unsupported | +| completion (`isIncomplete` retries), completionItem/resolve | `request_completions`; resolve through `server.send.resolve_completion_item` | tested against Pyright | +| declaration, typeDefinition, documentHighlight, signatureHelp, call hierarchy (incoming and outgoing) | `server.send.*` low-level requests | tested against Pyright | +| prepareRename, rename | `server.send.*`; the response is a WorkspaceEdit proposal, multilspy never applies it | proposal shape tested | +| codeAction (quickfix, source.organizeImports) | `server.send.code_action`; the only quick fix in 1.1.413 is "create type stub" for third-party packages without stubs, and organize imports is a command, not a code action | empty result tested; no quick-fix corpus | +| publishDiagnostics (typeCheckingMode off/basic/standard/strict) | `next_diagnostics()` bounded queue | tested against Pyright | +| workspace/configuration, workspace/applyEdit, client/registerCapability | answered by the adapter: fixed read-only settings, edits refused, registration acknowledged and ignored | tested with fixtures and against Pyright | +| executeCommand | advertised with an empty command list; `pyright.organizeimports` is disabled by the adapter settings, `pyright.createtypestub` writes files and is not supported | refusal of the server's applyEdit tested | | implementation, pull diagnostics, semantic tokens, inlay hints, folding, selection ranges, document links, formatting, code lens | not advertised by Pyright 1.1.413; requests fail with MethodNotFound | unsupported | Real Pyright integration tests require a preinstalled language server. Set diff --git a/src/multilspy/language_servers/pyright_language_server/initialize_params.json b/src/multilspy/language_servers/pyright_language_server/initialize_params.json index 47aa89ec..935c3aa0 100644 --- a/src/multilspy/language_servers/pyright_language_server/initialize_params.json +++ b/src/multilspy/language_servers/pyright_language_server/initialize_params.json @@ -39,6 +39,13 @@ } }, "rename": {"dynamicRegistration": false, "prepareSupport": true}, + "codeAction": { + "dynamicRegistration": false, + "codeActionLiteralSupport": { + "codeActionKind": {"valueSet": ["quickfix", "source.organizeImports"]} + } + }, + "callHierarchy": {"dynamicRegistration": false}, "documentHighlight": {"dynamicRegistration": false}, "documentSymbol": {"hierarchicalDocumentSymbolSupport": true}, "publishDiagnostics": {"relatedInformation": true} diff --git a/src/multilspy/language_servers/pyright_language_server/pyright_server.py b/src/multilspy/language_servers/pyright_language_server/pyright_server.py index 091e57ca..1cfe2966 100644 --- a/src/multilspy/language_servers/pyright_language_server/pyright_server.py +++ b/src/multilspy/language_servers/pyright_language_server/pyright_server.py @@ -1,7 +1,6 @@ -"""Pyright Python language server adapter for multilspy. - -Uses the existing language server protocol handler and a preinstalled -pyright-langserver executable. No automatic provider install is performed. +""" +Provides Python specific instantiation of the LanguageServer class using Pyright. +Contains various configurations and settings specific to Pyright. """ import asyncio @@ -9,91 +8,113 @@ import logging import os import pathlib -from collections.abc import AsyncIterator from contextlib import asynccontextmanager -from typing import Any +from typing import AsyncIterator +from multilspy.multilspy_logger import MultilspyLogger from multilspy.language_server import LanguageServer -from multilspy.lsp_protocol_handler.lsp_types import ErrorCodes, InitializeParams -from multilspy.lsp_protocol_handler.server import Error, ProcessLaunchInfo +from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo +from multilspy.lsp_protocol_handler.lsp_types import InitializeParams from multilspy.multilspy_config import MultilspyConfig -from multilspy.multilspy_logger import MultilspyLogger class PyrightServer(LanguageServer): - """Python semantic requests using pyright-langserver --stdio.""" - - def __init__( - self, - config: MultilspyConfig, - logger: MultilspyLogger, - repository_root_path: str, - ): - root = str(pathlib.Path(repository_root_path).resolve()) + """ + Provides Python specific instantiation of the LanguageServer class using pyright-langserver. + Pyright is opt-in: select it with MultilspyConfig(python_server="pyright"). + The executable must be preinstalled; multilspy does not download it. + """ + + def __init__(self, config: MultilspyConfig, logger: MultilspyLogger, repository_root_path: str): + """ + Creates a PyrightServer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. + """ super().__init__( config, logger, - root, - ProcessLaunchInfo( - cmd=[config.server_binary or "pyright-langserver", "--stdio"], - cwd=root, - ), + repository_root_path, + ProcessLaunchInfo(cmd=[config.server_binary or "pyright-langserver", "--stdio"], cwd=repository_root_path), "python", ) self._initialize_timeout_seconds = 30 - self.diagnostics: asyncio.Queue[dict] = asyncio.Queue(maxsize=64) + # Pyright pushes textDocument/publishDiagnostics asynchronously. Keep a + # bounded queue so callers can read them without unbounded growth. + self.diagnostics: asyncio.Queue = asyncio.Queue(maxsize=64) self.diagnostics_dropped = False def _get_initialize_params(self, repository_absolute_path: str) -> InitializeParams: - """Load Pyright's read-only client capabilities, like other adapters.""" - config_file = pathlib.Path(__file__).with_name("initialize_params.json") - with config_file.open(encoding="utf-8") as reader: - params = json.load(reader) - del params["_description"] - root = pathlib.Path(repository_absolute_path).resolve() - params["processId"] = os.getpid() - params["rootPath"] = str(root) - params["rootUri"] = root.as_uri() - params["workspaceFolders"][0]["name"] = root.name - params["workspaceFolders"][0]["uri"] = root.as_uri() - return params + """ + Returns the initialize params for the Pyright Language Server. + """ + with open(os.path.join(os.path.dirname(__file__), "initialize_params.json"), "r") as f: + d = json.load(f) + + del d["_description"] + + d["processId"] = os.getpid() + assert d["rootPath"] == "$rootPath" + d["rootPath"] = repository_absolute_path + + assert d["rootUri"] == "$rootUri" + d["rootUri"] = pathlib.Path(repository_absolute_path).as_uri() + + assert d["workspaceFolders"][0]["uri"] == "$uri" + d["workspaceFolders"][0]["uri"] = pathlib.Path(repository_absolute_path).as_uri() + + assert d["workspaceFolders"][0]["name"] == "$name" + d["workspaceFolders"][0]["name"] = os.path.basename(repository_absolute_path) + + return d async def next_diagnostics(self, timeout: float = 5.0) -> dict: - """Read one asynchronous publishDiagnostics notification.""" + """ + Returns the next queued textDocument/publishDiagnostics notification, waiting at most `timeout` seconds. + """ return await asyncio.wait_for(self.diagnostics.get(), timeout) @asynccontextmanager async def start_server(self) -> AsyncIterator["PyrightServer"]: - async def configuration(params: Any) -> list: + """ + Starts the Pyright Language Server, waits for the server to be ready and yields the LanguageServer instance. + + Usage: + ``` + async with lsp.start_server(): + # LanguageServer has been initialized and ready to serve requests + await lsp.request_definition(...) + await lsp.request_references(...) + # Shutdown the LanguageServer on exit from scope + # LanguageServer has been shutdown + ``` + """ + + async def workspace_configuration(params): + # Pyright asks for the "python", "python.analysis" and "pyright" + # sections. Answer with fixed, read-only settings; project settings + # come from pyrightconfig.json / pyproject.toml in the workspace. if not isinstance(params, dict): return [] items = params.get("items") if not isinstance(items, list) or len(items) > 64: return [] - defaults = { + settings = { "python": {"analysis": {}}, "pyright": { "disableLanguageServices": False, "disableOrganizeImports": True, }, } - return [ - defaults.get(item.get("section")) - if isinstance(item, dict) and isinstance(item.get("section"), str) - else None - for item in items - ] - - async def refuse_edit(_params: Any) -> dict: - return { - "applied": False, - "failureReason": "multilspy Pyright client is read-only", - } + answers = [] + for item in items: + section = item.get("section") if isinstance(item, dict) else None + answers.append(settings.get(section) if isinstance(section, str) else None) + return answers - async def refuse_registration(_params: Any) -> None: - raise Error(ErrorCodes.MethodNotFound, "Dynamic registration disabled") + async def workspace_apply_edit(params): + # multilspy never applies server-initiated edits. + return {"applied": False, "failureReason": "multilspy Pyright client is read-only"} - async def diagnostics(params: Any) -> None: + async def publish_diagnostics(params): if not isinstance(params, dict) or not isinstance(params.get("uri"), str): return if self.diagnostics.full(): @@ -101,45 +122,44 @@ async def diagnostics(params: Any) -> None: return self.diagnostics.put_nowait(params) - async def ignore_notification(_params: Any) -> None: - return None + async def do_nothing(params): + return + + async def window_log_message(msg): + self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO) - self.server.on_request("workspace/configuration", configuration) - self.server.on_request("workspace/applyEdit", refuse_edit) - self.server.on_request("client/registerCapability", refuse_registration) - self.server.on_notification("textDocument/publishDiagnostics", diagnostics) - self.server.on_notification("window/logMessage", ignore_notification) - self.server.on_notification("$/progress", ignore_notification) + self.server.on_request("client/registerCapability", do_nothing) + self.server.on_request("workspace/configuration", workspace_configuration) + self.server.on_request("workspace/applyEdit", workspace_apply_edit) + self.server.on_notification("window/logMessage", window_log_message) + self.server.on_notification("$/progress", do_nothing) + self.server.on_notification("textDocument/publishDiagnostics", publish_diagnostics) async with super().start_server(): - self.logger.log("Starting Pyright language server process", logging.INFO) + self.logger.log("Starting pyright-langserver server process", logging.INFO) initialized = False try: await self.server.start() - self.logger.log("Initializing Pyright language server", logging.INFO) - result = await asyncio.wait_for( - self.server.send.initialize( - self._get_initialize_params(self.repository_root_path) - ), - timeout=self._initialize_timeout_seconds, + initialize_params = self._get_initialize_params(self.repository_root_path) + + self.logger.log( + "Sending initialize request from LSP client to LSP server and awaiting response", + logging.INFO, ) - capabilities = ( - result.get("capabilities") if isinstance(result, dict) else None + init_response = await asyncio.wait_for( + self.server.send.initialize(initialize_params), + timeout=self._initialize_timeout_seconds, ) + capabilities = init_response.get("capabilities") if isinstance(init_response, dict) else None if not isinstance(capabilities, dict): raise TypeError("Invalid Pyright initialization capabilities") + # multilspy sends UTF-16 positions, the LSP default. if capabilities.get("positionEncoding", "utf-16") != "utf-16": raise ValueError("Unsupported Pyright position encoding") - for required in ( - "definitionProvider", - "referencesProvider", - "hoverProvider", - ): + for required in ("definitionProvider", "referencesProvider", "hoverProvider"): capability = capabilities.get(required) if capability is not True and not isinstance(capability, dict): - raise ValueError( - f"Pyright missing required capability: {required}" - ) + raise ValueError(f"Pyright missing required capability: {required}") self.server.notify.initialized({}) self.completions_available.set() @@ -148,6 +168,6 @@ async def ignore_notification(_params: Any) -> None: yield self finally: if initialized: - await asyncio.wait_for(self.server.shutdown(), timeout=8) + await self.server.shutdown() finally: await self.server.stop() diff --git a/tests/multilspy/test_multilspy_pyright.py b/tests/multilspy/test_multilspy_pyright.py index fed58a9b..ce4cfcef 100644 --- a/tests/multilspy/test_multilspy_pyright.py +++ b/tests/multilspy/test_multilspy_pyright.py @@ -3,6 +3,10 @@ Use a disposable local workspace instead of cloning a remote repository. The integration tests require an explicit, preinstalled Pyright executable; they skip rather than download/install when it is unavailable. + +Every expected payload below is the exact response of pyright-langserver +1.1.413 for the temporary project. Rename, code actions and commands are +proposals only: the workspace files are compared byte for byte afterwards. """ import asyncio @@ -25,11 +29,14 @@ from multilspy.multilspy_exceptions import MultilspyException from multilspy.multilspy_logger import MultilspyLogger -# The adapter and the expectations below were validated against this release. +# The adapter, the capability matrix and every exact payload in this module +# were captured against this Pyright release. TESTED_PYRIGHT_VERSION = (1, 1, 413) -# Server capabilities that pyright-langserver 1.1.413 advertises to this -# read-only client, and well-known ones it does not advertise. +# Server capabilities that pyright-langserver 1.1.413 advertises to multilspy's +# read-only client. Everything else (implementationProvider, diagnosticProvider +# for pull diagnostics, semantic tokens, inlay hints, folding, formatting, ...) +# is not advertised and such requests fail with MethodNotFound. ADVERTISED_CAPABILITIES = { "callHierarchyProvider", "codeActionProvider", @@ -48,17 +55,47 @@ "workspace", "workspaceSymbolProvider", } -UNADVERTISED_CAPABILITIES = { - "codeLensProvider", - "diagnosticProvider", - "documentFormattingProvider", - "documentLinkProvider", - "foldingRangeProvider", - "implementationProvider", - "inlayHintProvider", - "selectionRangeProvider", - "semanticTokensProvider", -} + +SHAPES_SOURCE = ( + "from dataclasses import dataclass\n" + "\n" + "\n" + "@dataclass\n" + "class Point:\n" + " x: float\n" + " y: float\n" + "\n" + "\n" + "class Shape:\n" + " def area(self) -> float:\n" + " raise NotImplementedError\n" + "\n" + " def describe(self) -> str:\n" + " return f\"{type(self).__name__}: {self.area():.1f}\"\n" + "\n" + "\n" + "class Square(Shape):\n" + " def __init__(self, side: float) -> None:\n" + " self.side = side\n" + "\n" + " def area(self) -> float:\n" + " return self.side * self.side\n" + "\n" + "\n" + "def total_area(shapes: list[Shape]) -> float:\n" + " return sum(shape.area() for shape in shapes)\n" +) + +REPORT_SOURCE = ( + "import sys\n" + "import os\n" + "from shapes import Point, Square, total_area\n" + "\n" + "origin = Point(0.0, 0.0)\n" + "squares = [Square(2.0), Square(side=3.0)]\n" + "summary = total_area(squares)\n" + "label = squares[0].describe()\n" +) def _range(start_line, start_character, end_line, end_character): @@ -68,6 +105,31 @@ def _range(start_line, start_character, end_line, end_character): } +def _pyright_version(language_server_binary): + """Return the Pyright version tuple for a pyright-langserver executable. + + pyright-langserver has no --version flag. The npm and PyPI packages install + a sibling `pyright` CLI that reports the shared version; the npm package + also carries the version in its package.json next to the resolved script. + """ + binary = Path(language_server_binary) + sibling = binary.with_name("pyright") + if sibling.is_file(): + completed = subprocess.run( + [str(sibling), "--version"], capture_output=True, text=True, timeout=60 + ) + match = re.search(r"pyright (\d+)\.(\d+)\.(\d+)", completed.stdout + completed.stderr) + if completed.returncode == 0 and match: + return tuple(int(part) for part in match.groups()) + package_json = binary.resolve().parent / "package.json" + if package_json.is_file(): + version = json.loads(package_json.read_text(encoding="utf-8")).get("version", "") + match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version) + if match: + return tuple(int(part) for part in match.groups()) + return None + + @pytest.fixture def python_project(tmp_path): root = tmp_path.resolve() @@ -87,9 +149,11 @@ def python_project(tmp_path): # The emoji is one code point but two UTF-16 code units; the second # `x` is at UTF-16 column 14 (code-point column 13). "emoji.py": ("x = '\U0001F600'; y = x\n"), + "shapes.py": SHAPES_SOURCE, + "report.py": REPORT_SOURCE, } for name, contents in files.items(): - (root / name).write_text(contents) + (root / name).write_text(contents, encoding="utf-8") (root / "pyrightconfig.json").write_text( '{"typeCheckingMode":"standard","include":["."]}\n' ) @@ -201,6 +265,56 @@ def test_invalid_python_backend_cannot_fall_back_to_jedi(tmp_path): LanguageServer.create(config, MultilspyLogger(), str(tmp_path.resolve())) +def test_real_pyright_binary_is_the_tested_version(pyright_binary): + version = _pyright_version(pyright_binary) + assert version is not None, "Cannot determine the Pyright version next to the language server" + # The exact payloads in this module belong to one release. To validate a + # newer Pyright, re-capture the expectations and bump TESTED_PYRIGHT_VERSION. + assert version == TESTED_PYRIGHT_VERSION + + +@pytest.mark.asyncio +async def test_real_pyright_advertised_capabilities_match_matrix(create_pyright): + server = create_pyright() + native_initialize = server.server.send.initialize + captured = {} + + async def initialize(params): + captured["result"] = await native_initialize(params) + return captured["result"] + + server.server.send.initialize = initialize + + async def exercise(): + async with server.start_server(): + pass + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + capabilities = captured["result"]["capabilities"] + assert set(capabilities) == ADVERTISED_CAPABILITIES + assert capabilities["textDocumentSync"] == 2 + assert capabilities["completionProvider"] == { + "triggerCharacters": [".", "[", '"', "'"], + "resolveProvider": True, + "completionItem": {"labelDetailsSupport": True}, + "workDoneProgress": True, + } + assert capabilities["signatureHelpProvider"]["triggerCharacters"] == ["(", ",", ")"] + assert capabilities["renameProvider"]["prepareProvider"] is True + assert capabilities["codeActionProvider"]["codeActionKinds"] == [ + "quickfix", + "source.organizeImports", + ] + # Pyright registers no server commands for this client; its commands still + # execute by name (see test_real_pyright_commands_cannot_edit_the_workspace). + assert capabilities["executeCommandProvider"]["commands"] == [] + assert capabilities["callHierarchyProvider"] is True + assert capabilities["workspace"] == { + "workspaceFolders": {"supported": True, "changeNotifications": True} + } + + @pytest.mark.asyncio async def test_real_pyright_definition_references_hover_and_symbols( python_project, @@ -215,23 +329,36 @@ async def exercise(): ) assert len(definition) == 1 assert definition[0]["relativePath"] == "lib.py" - assert definition[0]["range"]["start"] == {"line": 0, "character": 4} + assert definition[0]["range"] == _range(0, 4, 0, 9) references = await asyncio.wait_for( server.request_references("lib.py", 0, 5), timeout=8 ) - assert len(references) >= 2 - assert all(item["relativePath"] == "app.py" for item in references) + assert [(item["relativePath"], item["range"]) for item in references] == [ + ("app.py", _range(0, 16, 0, 21)), + ("app.py", _range(2, 8, 2, 13)), + ("app.py", _range(3, 9, 3, 14)), + ] hover = await asyncio.wait_for( server.request_hover("app.py", 2, 10), timeout=8 ) - assert hover and "contents" in hover - - symbols, _ = await asyncio.wait_for( + assert hover == { + "contents": { + "kind": "markdown", + "value": "```python\n(function) def greet(name: str) -> str\n```", + }, + "range": _range(2, 8, 2, 13), + } + + symbols, tree = await asyncio.wait_for( server.request_document_symbols("lib.py"), timeout=8 ) - assert "greet" in {entry["name"] for entry in symbols} + assert tree is None + assert [(entry["name"], entry["kind"]) for entry in symbols] == [ + ("greet", 12), + ("name", 13), + ] workspace_symbols = [] for _ in range(15): @@ -241,7 +368,110 @@ async def exercise(): if workspace_symbols: break await asyncio.sleep(0.1) - assert any(item["name"] == "greet" for item in workspace_symbols) + assert workspace_symbols == [ + { + "name": "greet", + "kind": 12, + "location": { + "uri": (python_project / "lib.py").as_uri(), + "range": _range(0, 4, 0, 9), + }, + } + ] + + await asyncio.wait_for(exercise(), timeout=30) + assert server.server.process is None + + +@pytest.mark.asyncio +async def test_real_pyright_high_level_api_on_classes_across_files( + python_project, + create_pyright, +): + """Inheritance, overrides, keyword arguments and cross-file references.""" + server = create_pyright() + + async def exercise(): + async with server.start_server(): + # shape.area() inside total_area resolves to the base method. + definition = await asyncio.wait_for( + server.request_definition("shapes.py", 26, 22), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in definition] == [ + ("shapes.py", _range(10, 8, 10, 12)) + ] + + # Square used through a keyword-argument constructor call. + definition = await asyncio.wait_for( + server.request_definition("report.py", 5, 26), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in definition] == [ + ("shapes.py", _range(17, 6, 17, 12)) + ] + + # References exclude the declaration (multilspy sends includeDeclaration=false). + references = await asyncio.wait_for( + server.request_references("shapes.py", 17, 6), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in references] == [ + ("report.py", _range(2, 26, 2, 32)), + ("report.py", _range(5, 11, 5, 17)), + ("report.py", _range(5, 24, 5, 30)), + ] + # References to the base method do not include the override. + references = await asyncio.wait_for( + server.request_references("shapes.py", 10, 8), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in references] == [ + ("shapes.py", _range(14, 46, 14, 50)), + ("shapes.py", _range(26, 21, 26, 25)), + ] + + hover = await asyncio.wait_for( + server.request_hover("report.py", 6, 10), timeout=8 + ) + assert hover == { + "contents": { + "kind": "markdown", + "value": "```python\n(function) def total_area(shapes: list[Shape]) -> float\n```", + }, + "range": _range(6, 10, 6, 20), + } + hover = await asyncio.wait_for( + server.request_hover("report.py", 5, 12), timeout=8 + ) + assert hover["contents"]["value"] == "```python\nclass Square(side: float)\n```" + + symbols, _ = await asyncio.wait_for( + server.request_document_symbols("shapes.py"), timeout=8 + ) + assert [(entry["name"], entry["kind"]) for entry in symbols] == [ + ("Point", 5), + ("x", 13), + ("y", 13), + ("Shape", 5), + ("area", 6), + ("describe", 6), + ("Square", 5), + ("__init__", 6), + ("side", 13), + ("area", 6), + ("side", 13), + ("total_area", 12), + ("shapes", 13), + ] + + workspace_symbols = await asyncio.wait_for( + server.request_workspace_symbol("Square"), timeout=8 + ) + assert { + "name": "Square", + "kind": 5, + "location": { + "uri": (python_project / "shapes.py").as_uri(), + "range": _range(17, 6, 17, 12), + }, + } in workspace_symbols await asyncio.wait_for(exercise(), timeout=30) assert server.server.process is None @@ -263,6 +493,17 @@ async def exercise(): ) assert "process" in {item["completionText"] for item in suggestions} + # Pyright answers member completions with isIncomplete=true first; + # the high-level API retries with TriggerForIncompleteCompletions. + suggestions = await asyncio.wait_for( + server.request_completions("report.py", 7, len("label = squares[0].")), + timeout=8, + ) + by_name = {item["completionText"]: item["kind"] for item in suggestions} + assert by_name["describe"] == 2 + assert by_name["area"] == 2 + assert by_name["side"] == 6 + with server.open_file("app.py"): signature = await asyncio.wait_for( server.server.send.signature_help( @@ -275,126 +516,22 @@ async def exercise(): ), timeout=8, ) - assert signature and signature["signatures"] - assert "name: str" in signature["signatures"][0]["label"] - - await asyncio.wait_for(exercise(), timeout=30) - assert server.server.process is None - - -@pytest.mark.asyncio -async def test_real_pyright_publishes_type_diagnostics_without_editing( - python_project, - create_pyright, -): - server = create_pyright() - source = python_project / "invalid.py" - before = source.read_bytes() - - async def exercise(): - async with server.start_server(): - with server.open_file("invalid.py"): - found = set() - # Allow delayed cold starts: a short timeout is not a failure. - loop = asyncio.get_running_loop() - deadline = loop.time() + 18 - while loop.time() < deadline: - try: - notification = await server.next_diagnostics( - timeout=min(2, max(0.01, deadline - loop.time())) - ) - except asyncio.TimeoutError: - continue - if notification.get("uri") != source.as_uri(): - continue - found.update( - entry.get("code") - for entry in notification.get("diagnostics", []) - if isinstance(entry, dict) - ) - if "reportReturnType" in found: - break - assert "reportReturnType" in found - - await asyncio.wait_for(exercise(), timeout=30) - assert source.read_bytes() == before - assert server.server.process is None - - -def test_real_pyright_sync_api_works_and_closes_provider( - python_project, - pyright_binary, -): - sync = SyncLanguageServer.create( - MultilspyConfig( - code_language=Language.PYTHON, - python_server="pyright", - server_binary=pyright_binary, - ), - MultilspyLogger(), - str(python_project), - timeout=15, - ) - with sync.start_server(): - definition = sync.request_definition("app.py", 2, 9) - assert len(definition) == 1 - assert definition[0]["relativePath"] == "lib.py" - completion = sync.request_completions("worker.py", 5, len("result = worker.")) - assert "process" in {item["completionText"] for item in completion} - assert sync.language_server.server.process is None - assert sync.loop.is_closed() - assert not sync.loop_thread.is_alive() - - -def test_real_pyright_binary_reports_tested_version(pyright_binary): - # pyright-langserver has no --version flag; the sibling pyright CLI - # installed by the same package reports the shared version. - reported = [] - for candidate in (pyright_binary, str(Path(pyright_binary).with_name("pyright"))): - if not Path(candidate).is_file(): - continue - completed = subprocess.run( - [candidate, "--version"], capture_output=True, text=True, timeout=30 - ) - match = re.search(r"pyright (\d+)\.(\d+)\.(\d+)", completed.stdout + completed.stderr) - if completed.returncode == 0 and match: - reported.append(tuple(int(part) for part in match.groups())) - assert reported, "No executable next to the language server reports a Pyright version" - assert all(version >= TESTED_PYRIGHT_VERSION for version in reported) - - -@pytest.mark.asyncio -async def test_real_pyright_advertised_capabilities_match_matrix(create_pyright): - server = create_pyright() - native_initialize = server.server.send.initialize - captured = {} - - async def initialize(params): - captured["result"] = await native_initialize(params) - return captured["result"] - - server.server.send.initialize = initialize - - async def exercise(): - async with server.start_server(): - pass + assert signature == { + "activeParameter": 0, + "activeSignature": 0, + "signatures": [ + { + "activeParameter": 0, + "label": "(name: str) -> str", + "parameters": [ + {"documentation": {"kind": "plaintext", "value": ""}, "label": [1, 10]} + ], + } + ], + } await asyncio.wait_for(exercise(), timeout=30) assert server.server.process is None - capabilities = captured["result"]["capabilities"] - assert ADVERTISED_CAPABILITIES <= set(capabilities) - assert UNADVERTISED_CAPABILITIES.isdisjoint(capabilities) - assert capabilities["textDocumentSync"] == 2 - assert capabilities["completionProvider"]["resolveProvider"] is True - assert capabilities["completionProvider"]["triggerCharacters"] == [".", "[", '"', "'"] - assert capabilities["signatureHelpProvider"]["triggerCharacters"] == ["(", ",", ")"] - assert capabilities["renameProvider"]["prepareProvider"] is True - assert capabilities["codeActionProvider"]["codeActionKinds"] == [ - "quickfix", - "source.organizeImports", - ] - # Pyright registers no server commands for a client without applyEdit. - assert capabilities["executeCommandProvider"]["commands"] == [] @pytest.mark.asyncio @@ -402,12 +539,7 @@ async def test_real_pyright_read_only_requests_return_exact_shapes( python_project, create_pyright, ): - """One server session covers the advertised read-only requests. - - Every expectation is the exact payload returned by Pyright 1.1.413 for the - temporary project. Rename and code actions are proposals only: the files - on disk are compared byte for byte afterwards. - """ + """One server session covers the advertised requests without a high-level API.""" server = create_pyright() before = {path: path.read_bytes() for path in python_project.glob("*.py")} @@ -420,32 +552,32 @@ def at(name, line, character): "position": {"line": line, "character": character}, } - greet_call_sites = [_range(2, 8, 2, 13), _range(3, 9, 3, 14)] + square_uses = [_range(2, 26, 2, 32), _range(5, 11, 5, 17), _range(5, 24, 5, 30)] corpus = [ - ("declaration", at("app.py", 2, 9), [{"uri": uri("lib.py"), "range": _range(0, 4, 0, 9)}]), - ("type_definition", at("worker.py", 4, 0), [{"uri": uri("worker.py"), "range": _range(0, 6, 0, 12)}]), + ("declaration", at("report.py", 2, 26), [{"uri": uri("shapes.py"), "range": _range(17, 6, 17, 12)}]), + ("type_definition", at("report.py", 4, 0), [{"uri": uri("shapes.py"), "range": _range(4, 6, 4, 11)}]), ( "document_highlight", - at("app.py", 2, 9), + at("shapes.py", 19, 13), [ - {"kind": 3, "range": _range(0, 16, 0, 21)}, - {"kind": 2, "range": greet_call_sites[0]}, - {"kind": 2, "range": greet_call_sites[1]}, + {"kind": 3, "range": _range(19, 13, 19, 17)}, + {"kind": 2, "range": _range(22, 20, 22, 24)}, + {"kind": 2, "range": _range(22, 32, 22, 36)}, ], ), - ("prepare_rename", at("lib.py", 0, 5), _range(0, 4, 0, 9)), + ("prepare_rename", at("shapes.py", 17, 6), _range(17, 6, 17, 12)), ( "signature_help", - at("app.py", 2, len("first = greet(")), + at("report.py", 5, len("squares = [Square(2.0), Square(")), { "activeParameter": 0, "activeSignature": 0, "signatures": [ { "activeParameter": 0, - "label": "(name: str) -> str", + "label": "(side: float) -> Square", "parameters": [ - {"documentation": {"kind": "plaintext", "value": ""}, "label": [1, 10]} + {"documentation": {"kind": "plaintext", "value": ""}, "label": [1, 12]} ], } ], @@ -453,43 +585,58 @@ def at(name, line, character): ), ( "prepare_call_hierarchy", - at("lib.py", 0, 5), + at("shapes.py", 25, 4), [ { "kind": 12, - "name": "greet", - "uri": uri("lib.py"), - "range": _range(0, 4, 0, 9), - "selectionRange": _range(0, 4, 0, 9), + "name": "total_area", + "uri": uri("shapes.py"), + "range": _range(25, 4, 25, 14), + "selectionRange": _range(25, 4, 25, 14), } ], ), # UTF-16 column 14 is the second `x`; a code-point column would miss it. ("definition", at("emoji.py", 0, 14), [{"uri": uri("emoji.py"), "range": _range(0, 0, 0, 1)}]), - # Blank line: Pyright answers null, never an error. + ("hover", at("emoji.py", 0, 10), { + "contents": {"kind": "markdown", "value": "```python\n(variable) y: Literal['\U0001F600']\n```"}, + "range": _range(0, 10, 0, 11), + }), + # Blank line and unknown file: Pyright answers null, never an error. ("hover", at("app.py", 1, 0), None), ("definition", at("app.py", 1, 0), None), ("references", {**at("app.py", 1, 0), "context": {"includeDeclaration": True}}, None), + ("hover", at("missing.py", 0, 0), None), + ("definition", at("missing.py", 0, 0), None), ( "code_action", { - "textDocument": {"uri": uri("app.py")}, - "range": _range(0, 0, 0, 20), + "textDocument": {"uri": uri("report.py")}, + "range": _range(0, 0, 2, 44), "context": {"diagnostics": []}, }, [], ), + ( + "code_action", + { + "textDocument": {"uri": uri("report.py")}, + "range": _range(0, 0, 2, 44), + "context": {"diagnostics": [], "only": ["source.organizeImports"]}, + }, + [], + ), ] async def exercise(): async with server.start_server(): send = server.server.send - with server.open_file("app.py"), server.open_file("lib.py"), server.open_file( - "worker.py" - ), server.open_file("emoji.py"): + with server.open_file("app.py"), server.open_file("emoji.py"), server.open_file( + "shapes.py" + ), server.open_file("report.py"): for method, params, expected in corpus: result = await asyncio.wait_for(getattr(send, method)(params), timeout=8) - assert result == expected, method + assert result == expected, (method, params["position"] if "position" in params else params) # The high-level API passes UTF-16 columns through unchanged. definition = await asyncio.wait_for( @@ -498,66 +645,201 @@ async def exercise(): assert [(item["relativePath"], item["range"]) for item in definition] == [ ("emoji.py", _range(0, 0, 0, 1)) ] - assert await asyncio.wait_for( - server.request_hover("app.py", 1, 0), timeout=8 - ) is None - assert await asyncio.wait_for( - server.request_references("app.py", 1, 0), timeout=8 - ) == [] - - calls = await asyncio.wait_for( - send.incoming_calls( - {"item": (await send.prepare_call_hierarchy(at("lib.py", 0, 5)))[0]} - ), - timeout=8, - ) - assert [(call["from"]["name"], call["from"]["uri"], call["fromRanges"]) for call in calls] == [ - ("(module) app.py", uri("app.py"), greet_call_sites) + assert await asyncio.wait_for(server.request_hover("app.py", 1, 0), timeout=8) is None + assert await asyncio.wait_for(server.request_references("app.py", 1, 0), timeout=8) == [] + + # Call hierarchy: incoming from the report module, outgoing to + # Shape.area in the workspace and to typeshed's sum overloads. + item = (await asyncio.wait_for(send.prepare_call_hierarchy(at("shapes.py", 25, 4)), timeout=8))[0] + incoming = await asyncio.wait_for(send.incoming_calls({"item": item}), timeout=8) + assert incoming == [ + { + "from": { + "kind": 2, + "name": "(module) report.py", + "uri": uri("report.py"), + "range": _range(0, 0, 0, 0), + "selectionRange": _range(0, 0, 0, 0), + }, + "fromRanges": [_range(6, 10, 6, 20)], + } ] + outgoing = await asyncio.wait_for(send.outgoing_calls({"item": item}), timeout=8) + workspace_calls = [call for call in outgoing if call["to"]["uri"] == uri("shapes.py")] + assert workspace_calls == [ + { + "to": { + "kind": 6, + "name": "area", + "uri": uri("shapes.py"), + "range": _range(10, 8, 10, 12), + "selectionRange": _range(10, 8, 10, 12), + }, + "fromRanges": [_range(26, 21, 26, 25)], + } + ] + builtin_calls = [call for call in outgoing if call not in workspace_calls] + assert builtin_calls + for call in builtin_calls: + assert call["to"]["name"] == "sum" + assert call["to"]["uri"].endswith("/stdlib/builtins.pyi") + assert call["fromRanges"] == [_range(26, 11, 26, 14)] # Rename is a WorkspaceEdit proposal; nothing is applied. proposal = await asyncio.wait_for( - send.rename({**at("lib.py", 0, 5), "newName": "salute"}), timeout=8 + send.rename({**at("shapes.py", 17, 6), "newName": "Box"}), timeout=8 ) changes = sorted(proposal["documentChanges"], key=lambda change: change["textDocument"]["uri"]) assert changes == [ { - "textDocument": {"uri": uri("app.py"), "version": None}, - "edits": [ - {"range": _range(0, 16, 0, 21), "newText": "salute"}, - {"range": greet_call_sites[0], "newText": "salute"}, - {"range": greet_call_sites[1], "newText": "salute"}, - ], + "textDocument": {"uri": uri("report.py"), "version": None}, + "edits": [{"range": span, "newText": "Box"} for span in square_uses], }, { - "textDocument": {"uri": uri("lib.py"), "version": None}, - "edits": [{"range": _range(0, 4, 0, 9), "newText": "salute"}], + "textDocument": {"uri": uri("shapes.py"), "version": None}, + "edits": [{"range": _range(17, 6, 17, 12), "newText": "Box"}], }, ] # completionItem/resolve adds documentation to a raw item. completion = await asyncio.wait_for( - send.completion({**at("worker.py", 5, len("result = worker.")), "context": {"triggerKind": 1}}), + send.completion({**at("report.py", 7, len("label = squares[0].")), "context": {"triggerKind": 1}}), timeout=8, ) - item = next(entry for entry in completion["items"] if entry["label"] == "process") - resolved = await asyncio.wait_for(send.resolve_completion_item(item), timeout=8) - assert resolved["documentation"] == {"kind": "plaintext", "value": "def process() -> int"} + raw = next(entry for entry in completion["items"] if entry["label"] == "describe") + resolved = await asyncio.wait_for(send.resolve_completion_item(raw), timeout=8) + assert resolved["documentation"] == {"kind": "plaintext", "value": "def describe() -> str"} assert resolved["kind"] == 2 + assert resolved["label"] == "describe" # Unadvertised requests fail with MethodNotFound instead of hanging. with pytest.raises(Error) as unsupported: - await asyncio.wait_for(send.implementation(at("lib.py", 0, 5)), timeout=8) + await asyncio.wait_for(send.implementation(at("shapes.py", 10, 8)), timeout=8) assert unsupported.value.code == ErrorCodes.MethodNotFound + + await asyncio.wait_for(exercise(), timeout=60) + assert server.server.process is None + assert {path: path.read_bytes() for path in python_project.glob("*.py")} == before + + +@pytest.mark.asyncio +async def test_real_pyright_commands_cannot_edit_the_workspace( + python_project, + create_pyright, +): + """workspace/executeCommand is reachable but never changes files. + + Pyright's organize-imports command is disabled by the adapter configuration + and returns an empty result. When a client enables it, Pyright answers with + a WorkspaceEdit proposal and asks the client to apply it; the adapter + refuses that reverse request, so the workspace stays unchanged. + """ + server = create_pyright() + report = python_project / "report.py" + before = report.read_bytes() + apply_requests = [] + + async def exercise(): + async with server.start_server(): + send = server.server.send + handlers = server.server.on_request_handlers + refuse_edit = handlers["workspace/applyEdit"] + + async def record_apply_edit(params): + result = await refuse_edit(params) + apply_requests.append((params, result)) + return result + + handlers["workspace/applyEdit"] = record_apply_edit + command = {"command": "pyright.organizeimports", "arguments": [report.as_uri()]} + + with server.open_file("report.py"): + assert await asyncio.wait_for(send.execute_command(command), timeout=8) == [] with pytest.raises(Error): await asyncio.wait_for( send.execute_command({"command": "pyright.doesNotExist", "arguments": []}), timeout=8, ) + # Opt in to organize imports and let Pyright re-read its settings. + adapter_configuration = handlers["workspace/configuration"] + + async def permissive_configuration(params): + answers = await adapter_configuration(params) + for item, answer in zip(params["items"], answers): + if item.get("section") == "pyright": + answer["disableOrganizeImports"] = False + return answers + + handlers["workspace/configuration"] = permissive_configuration + server.server.notify.workspace_did_change_configuration({"settings": {}}) + loop = asyncio.get_running_loop() + deadline = loop.time() + 10 + proposal = [] + while not proposal and loop.time() < deadline: + await asyncio.sleep(0.1) + proposal = await asyncio.wait_for(send.execute_command(command), timeout=8) + assert proposal == { + "changes": { + report.as_uri(): [ + { + "range": _range(0, 0, 2, 44), + "newText": "import os\nimport sys\n\nfrom shapes import Point, Square, total_area", + } + ] + } + } + for _ in range(50): + if apply_requests: + break + await asyncio.sleep(0.1) + assert [result for _, result in apply_requests] == [ + {"applied": False, "failureReason": "multilspy Pyright client is read-only"} + ] + assert apply_requests[0][0]["edit"] == proposal + await asyncio.wait_for(exercise(), timeout=60) assert server.server.process is None - assert {path: path.read_bytes() for path in python_project.glob("*.py")} == before + assert report.read_bytes() == before + + +@pytest.mark.asyncio +async def test_real_pyright_publishes_type_diagnostics_without_editing( + python_project, + create_pyright, +): + server = create_pyright() + source = python_project / "invalid.py" + before = source.read_bytes() + + async def exercise(): + async with server.start_server(): + with server.open_file("invalid.py"): + found = set() + # Allow delayed cold starts: a short timeout is not a failure. + loop = asyncio.get_running_loop() + deadline = loop.time() + 18 + while loop.time() < deadline: + try: + notification = await server.next_diagnostics( + timeout=min(2, max(0.01, deadline - loop.time())) + ) + except asyncio.TimeoutError: + continue + if notification.get("uri") != source.as_uri(): + continue + found.update( + entry.get("code") + for entry in notification.get("diagnostics", []) + if isinstance(entry, dict) + ) + if "reportReturnType" in found: + break + assert "reportReturnType" in found + + await asyncio.wait_for(exercise(), timeout=30) + assert source.read_bytes() == before + assert server.server.process is None @pytest.mark.asyncio @@ -598,5 +880,42 @@ async def exercise(): diagnostics = await asyncio.wait_for(exercise(), timeout=30) assert {entry["code"] for entry in diagnostics} == expected_codes assert all(entry["severity"] == 1 for entry in diagnostics) + assert all(entry["range"] == _range(1, 11, 1, 14) for entry in diagnostics) assert server.server.process is None assert not server.diagnostics_dropped + + +def test_real_pyright_sync_api_works_and_closes_provider( + python_project, + pyright_binary, +): + sync = SyncLanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), + str(python_project), + timeout=15, + ) + with sync.start_server(): + definition = sync.request_definition("app.py", 2, 9) + assert len(definition) == 1 + assert definition[0]["relativePath"] == "lib.py" + completion = sync.request_completions("worker.py", 5, len("result = worker.")) + assert "process" in {item["completionText"] for item in completion} + # Cross-file references require the target module to be indexed. + # Keep both files open instead of relying on OS-dependent background + # workspace discovery timing. + with sync.open_file("shapes.py"), sync.open_file("report.py"): + references = sync.request_references("shapes.py", 17, 6) + assert [item["relativePath"] for item in references] == ["report.py"] * 3 + hover = sync.request_hover("report.py", 6, 10) + assert hover["range"] == _range(6, 10, 6, 20) + symbols, _ = sync.request_document_symbols("shapes.py") + assert "total_area" in {entry["name"] for entry in symbols} + assert sync.request_hover("app.py", 1, 0) is None + assert sync.language_server.server.process is None + assert sync.loop.is_closed() + assert not sync.loop_thread.is_alive() diff --git a/tests/multilspy/test_pyright_adapter_notifications.py b/tests/multilspy/test_pyright_adapter_notifications.py index 61d8ffd6..44eaef84 100644 --- a/tests/multilspy/test_pyright_adapter_notifications.py +++ b/tests/multilspy/test_pyright_adapter_notifications.py @@ -13,8 +13,6 @@ from multilspy.language_servers.pyright_language_server.pyright_server import ( PyrightServer, ) -from multilspy.lsp_protocol_handler.lsp_types import ErrorCodes -from multilspy.lsp_protocol_handler.server import Error from multilspy.multilspy_config import Language, MultilspyConfig from multilspy.multilspy_logger import MultilspyLogger @@ -135,19 +133,20 @@ async def test_pyright_configuration_is_explicit_and_bounded(pyright): @pytest.mark.asyncio -async def test_pyright_refuses_edit_and_unadvertised_registration(pyright): +async def test_pyright_refuses_edit_and_ignores_registration(pyright): server, _, requests, _ = pyright async with server.start_server(): result = await requests["workspace/applyEdit"]( {"edit": {"changes": {"file:///tmp/example.py": []}}} ) - assert result["applied"] is False - assert "read-only" in result["failureReason"] - with pytest.raises(Error) as caught: - await requests["client/registerCapability"]( - {"registrations": [{"method": "workspace/executeCommand"}]} - ) - assert caught.value.code == ErrorCodes.MethodNotFound + assert result == { + "applied": False, + "failureReason": "multilspy Pyright client is read-only", + } + # Like the other adapters, registration requests are acknowledged and ignored. + assert await requests["client/registerCapability"]( + {"registrations": [{"method": "workspace/executeCommand"}]} + ) is None @pytest.mark.asyncio From 7ff6e926e7fab6083ffe7233d62f9ed8d1595c09 Mon Sep 17 00:00:00 2001 From: Grammy Jiang Date: Thu, 22 Oct 2026 01:40:43 +1100 Subject: [PATCH 5/8] style(pyright): finalize reviewed adapter and test lint --- .../pyright_language_server/pyright_server.py | 6 +++--- tests/multilspy/test_multilspy_pyright.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/multilspy/language_servers/pyright_language_server/pyright_server.py b/src/multilspy/language_servers/pyright_language_server/pyright_server.py index 1cfe2966..d2beab57 100644 --- a/src/multilspy/language_servers/pyright_language_server/pyright_server.py +++ b/src/multilspy/language_servers/pyright_language_server/pyright_server.py @@ -8,14 +8,14 @@ import logging import os import pathlib +from collections.abc import AsyncIterator from contextlib import asynccontextmanager -from typing import AsyncIterator -from multilspy.multilspy_logger import MultilspyLogger from multilspy.language_server import LanguageServer -from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo from multilspy.lsp_protocol_handler.lsp_types import InitializeParams +from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo from multilspy.multilspy_config import MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger class PyrightServer(LanguageServer): diff --git a/tests/multilspy/test_multilspy_pyright.py b/tests/multilspy/test_multilspy_pyright.py index ce4cfcef..70524701 100644 --- a/tests/multilspy/test_multilspy_pyright.py +++ b/tests/multilspy/test_multilspy_pyright.py @@ -116,7 +116,7 @@ def _pyright_version(language_server_binary): sibling = binary.with_name("pyright") if sibling.is_file(): completed = subprocess.run( - [str(sibling), "--version"], capture_output=True, text=True, timeout=60 + [str(sibling), "--version"], capture_output=True, text=True, timeout=60, check=False ) match = re.search(r"pyright (\d+)\.(\d+)\.(\d+)", completed.stdout + completed.stderr) if completed.returncode == 0 and match: @@ -636,7 +636,7 @@ async def exercise(): ), server.open_file("report.py"): for method, params, expected in corpus: result = await asyncio.wait_for(getattr(send, method)(params), timeout=8) - assert result == expected, (method, params["position"] if "position" in params else params) + assert result == expected, (method, params.get("position", params)) # The high-level API passes UTF-16 columns through unchanged. definition = await asyncio.wait_for( From f0b39b5ab5c4d4dff16af37edd07b241145e3a34 Mon Sep 17 00:00:00 2001 From: Grammy Jiang Date: Thu, 22 Oct 2026 05:38:54 +1100 Subject: [PATCH 6/8] fix(pyright): harden LSP lifecycle and cross-platform regression coverage Run pinned real Pyright in CI, preserve latest diagnostics across queue overflow, reset stale state on restart, validate advertised capabilities and bound shutdown. Correct shared UTF-16 document edits and stable completion ranking; add Pyright/Jedi protocol, Unicode, Windows CLI and lifecycle regressions across Python 3.10-3.14. --- .github/workflows/test-workflow.yaml | 7 + README.md | 22 ++- src/multilspy/language_server.py | 6 +- .../initialize_params.json | 1 + .../pyright_language_server/pyright_server.py | 41 +++- src/multilspy/multilspy_utils.py | 66 ++++--- tests/multilspy/test_completion_responses.py | 17 ++ tests/multilspy/test_multilspy_pyright.py | 180 +++++++++++++++--- .../test_pyright_adapter_notifications.py | 90 ++++++++- .../multilspy/test_utf16_buffer_positions.py | 60 ++++++ 10 files changed, 422 insertions(+), 68 deletions(-) create mode 100644 tests/multilspy/test_utf16_buffer_positions.py diff --git a/.github/workflows/test-workflow.yaml b/.github/workflows/test-workflow.yaml index d9f26ab8..663e46f5 100644 --- a/.github/workflows/test-workflow.yaml +++ b/.github/workflows/test-workflow.yaml @@ -89,5 +89,12 @@ jobs: pip install -r requirements.txt pip install -e . + - name: Install pinned Pyright for real integration tests + run: | + npm install --prefix "$RUNNER_TEMP/multilspy-pyright" --no-save --no-package-lock --ignore-scripts --no-audit --no-fund pyright@1.1.413 + PYRIGHT_BIN="$RUNNER_TEMP/multilspy-pyright/node_modules/.bin/pyright-langserver" + test -x "$PYRIGHT_BIN" + echo "MULTILSPY_PYRIGHT_TEST_BINARY=$PYRIGHT_BIN" >> "$GITHUB_ENV" + - name: Run tests run: pytest tests/multilspy -v --tb=short diff --git a/README.md b/README.md index 8f4ab183..a6ebd3a6 100644 --- a/README.md +++ b/README.md @@ -92,17 +92,29 @@ and how multilspy exposes it: | completion (`isIncomplete` retries), completionItem/resolve | `request_completions`; resolve through `server.send.resolve_completion_item` | tested against Pyright | | declaration, typeDefinition, documentHighlight, signatureHelp, call hierarchy (incoming and outgoing) | `server.send.*` low-level requests | tested against Pyright | | prepareRename, rename | `server.send.*`; the response is a WorkspaceEdit proposal, multilspy never applies it | proposal shape tested | -| codeAction (quickfix, source.organizeImports) | `server.send.code_action`; the only quick fix in 1.1.413 is "create type stub" for third-party packages without stubs, and organize imports is a command, not a code action | empty result tested; no quick-fix corpus | -| publishDiagnostics (typeCheckingMode off/basic/standard/strict) | `next_diagnostics()` bounded queue | tested against Pyright | +| codeAction (quickfix, source.organizeImports) | `server.send.code_action`; available fixes depend on project diagnostics and may propose file edits, including type-stub generation or renames; organize imports uses a command | empty-response fixture tested; no writable quick-fix corpus | +| publishDiagnostics (typeCheckingMode off/basic/standard/strict) | asynchronous `PyrightServer.next_diagnostics()` bounded queue (not exposed by `SyncLanguageServer`) | tested against Pyright | | workspace/configuration, workspace/applyEdit, client/registerCapability | answered by the adapter: fixed read-only settings, edits refused, registration acknowledged and ignored | tested with fixtures and against Pyright | | executeCommand | advertised with an empty command list; `pyright.organizeimports` is disabled by the adapter settings, `pyright.createtypestub` writes files and is not supported | refusal of the server's applyEdit tested | -| implementation, pull diagnostics, semantic tokens, inlay hints, folding, selection ranges, document links, formatting, code lens | not advertised by Pyright 1.1.413; requests fail with MethodNotFound | unsupported | +| implementation, pull diagnostics, semantic tokens, inlay hints, folding, selection ranges, document links, formatting, code lens | not advertised to the current client capability profile by Pyright 1.1.413; requests fail with MethodNotFound | unsupported in this profile | Real Pyright integration tests require a preinstalled language server. Set MULTILSPY_PYRIGHT_TEST_BINARY to its absolute executable path before running pytest on tests/multilspy/test_multilspy_pyright.py. Without this variable -the real-server tests skip; mock/fixture coverage still runs offline. -This keeps the normal test suite independent of automatic Pyright downloads. +the real-server tests skip; if it is set to a missing/non-executable binary, +the tests fail. The GitHub Actions test workflow installs pinned Pyright +1.1.413 and exercises the real provider on every Python test matrix entry. +Other local unit/fixture tests still run without installing Pyright. +Exact-protocol fixtures and capabilities are version-pinned; when upgrading +Pyright, update and revalidate the expected responses rather than silently +skipping mismatched versions. For third-party import resolution, configure the +project through `pyrightconfig.json` or `[tool.pyright]` in `pyproject.toml`. + +The adapter rejects server-initiated workspace edits, but this is not an OS +sandbox. The low-level `server.send` API permits raw executeCommand requests, +including commands that may write files directly; clients should not expose +those requests to untrusted callers. Enforce workspace and subprocess +permissions outside multilspy when building an agent-facing integration. ## Usage Example usage: diff --git a/src/multilspy/language_server.py b/src/multilspy/language_server.py index 423838a2..4663d52f 100644 --- a/src/multilspy/language_server.py +++ b/src/multilspy/language_server.py @@ -608,9 +608,13 @@ async def request_completions( completion_item = multilspy_types.CompletionItem(**completion_item) completions_list.append(completion_item) + # Preserve the server's completion ranking while deduplicating. + # Iterating over a set makes suggestions reorder across processes. return [ json.loads(json_repr) - for json_repr in set([json.dumps(item, sort_keys=True) for item in completions_list]) + for json_repr in dict.fromkeys( + json.dumps(item, sort_keys=True) for item in completions_list + ) ] async def request_document_symbols(self, relative_file_path: str) -> Tuple[List[multilspy_types.UnifiedSymbolInformation], Union[List[multilspy_types.TreeRepr], None]]: diff --git a/src/multilspy/language_servers/pyright_language_server/initialize_params.json b/src/multilspy/language_servers/pyright_language_server/initialize_params.json index 935c3aa0..561d68f6 100644 --- a/src/multilspy/language_servers/pyright_language_server/initialize_params.json +++ b/src/multilspy/language_servers/pyright_language_server/initialize_params.json @@ -26,6 +26,7 @@ "hover": {"contentFormat": ["markdown", "plaintext"]}, "completion": { "dynamicRegistration": false, + "contextSupport": true, "completionItem": { "snippetSupport": false, "documentationFormat": ["plaintext"] diff --git a/src/multilspy/language_servers/pyright_language_server/pyright_server.py b/src/multilspy/language_servers/pyright_language_server/pyright_server.py index d2beab57..319e026d 100644 --- a/src/multilspy/language_servers/pyright_language_server/pyright_server.py +++ b/src/multilspy/language_servers/pyright_language_server/pyright_server.py @@ -8,12 +8,14 @@ import logging import os import pathlib +import shutil from collections.abc import AsyncIterator from contextlib import asynccontextmanager from multilspy.language_server import LanguageServer from multilspy.lsp_protocol_handler.lsp_types import InitializeParams from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo +from multilspy.multilspy_exceptions import MultilspyException from multilspy.multilspy_config import MultilspyConfig from multilspy.multilspy_logger import MultilspyLogger @@ -29,14 +31,20 @@ def __init__(self, config: MultilspyConfig, logger: MultilspyLogger, repository_ """ Creates a PyrightServer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ + executable = config.server_binary or "pyright-langserver" + # npm exposes .cmd shims on Windows; resolve through PATHEXT before + # passing the executable to subprocess (which runs without a shell). + if os.name == "nt": + executable = shutil.which(executable) or executable super().__init__( config, logger, repository_root_path, - ProcessLaunchInfo(cmd=[config.server_binary or "pyright-langserver", "--stdio"], cwd=repository_root_path), + ProcessLaunchInfo(cmd=[executable, "--stdio"], cwd=repository_root_path), "python", ) self._initialize_timeout_seconds = 30 + self._shutdown_timeout_seconds = 10 # Pyright pushes textDocument/publishDiagnostics asynchronously. Keep a # bounded queue so callers can read them without unbounded growth. self.diagnostics: asyncio.Queue = asyncio.Queue(maxsize=64) @@ -87,6 +95,8 @@ async def start_server(self) -> AsyncIterator["PyrightServer"]: # LanguageServer has been shutdown ``` """ + if self.server_started: + raise MultilspyException("Pyright language server is already started") async def workspace_configuration(params): # Pyright asks for the "python", "python.analysis" and "pyright" @@ -95,10 +105,14 @@ async def workspace_configuration(params): if not isinstance(params, dict): return [] items = params.get("items") - if not isinstance(items, list) or len(items) > 64: + if not isinstance(items, list): return [] + if len(items) > 64: + # LSP requires one response per requested configuration item. + return [None] * len(items) settings = { "python": {"analysis": {}}, + "python.analysis": {}, "pyright": { "disableLanguageServices": False, "disableOrganizeImports": True, @@ -118,8 +132,10 @@ async def publish_diagnostics(params): if not isinstance(params, dict) or not isinstance(params.get("uri"), str): return if self.diagnostics.full(): + # Keep the newest diagnostic state rather than permanently + # losing updates when the consumer falls behind. self.diagnostics_dropped = True - return + self.diagnostics.get_nowait() self.diagnostics.put_nowait(params) async def do_nothing(params): @@ -135,6 +151,12 @@ async def window_log_message(msg): self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", publish_diagnostics) + # A LanguageServer instance may be started more than once. Old progress + # and diagnostics must never be delivered to the next server session. + self.completions_available.clear() + self.diagnostics = asyncio.Queue(maxsize=64) + self.diagnostics_dropped = False + async with super().start_server(): self.logger.log("Starting pyright-langserver server process", logging.INFO) initialized = False @@ -156,7 +178,14 @@ async def window_log_message(msg): # multilspy sends UTF-16 positions, the LSP default. if capabilities.get("positionEncoding", "utf-16") != "utf-16": raise ValueError("Unsupported Pyright position encoding") - for required in ("definitionProvider", "referencesProvider", "hoverProvider"): + for required in ( + "definitionProvider", + "referencesProvider", + "hoverProvider", + "completionProvider", + "documentSymbolProvider", + "workspaceSymbolProvider", + ): capability = capabilities.get(required) if capability is not True and not isinstance(capability, dict): raise ValueError(f"Pyright missing required capability: {required}") @@ -168,6 +197,8 @@ async def window_log_message(msg): yield self finally: if initialized: - await self.server.shutdown() + await asyncio.wait_for( + self.server.shutdown(), timeout=self._shutdown_timeout_seconds + ) finally: await self.server.stop() diff --git a/src/multilspy/multilspy_utils.py b/src/multilspy/multilspy_utils.py index e13ea922..0ad3dbb1 100644 --- a/src/multilspy/multilspy_utils.py +++ b/src/multilspy/multilspy_utils.py @@ -22,50 +22,58 @@ class TextUtils: """ Utilities for text operations. """ + @staticmethod + def _utf16_length(text: str) -> int: + """LSP positions count UTF-16 code units, not Python code points.""" + return sum(2 if ord(character) > 0xFFFF else 1 for character in text) + @staticmethod def get_line_col_from_index(text: str, index: int) -> Tuple[int, int]: - """ - Returns the zero-indexed line and column number of the given index in the given text - """ - l = 0 - c = 0 - idx = 0 - while idx < index: - if text[idx] == '\n': - l += 1 - c = 0 + """Return a zero-based line and UTF-16 column for a Python text index.""" + line = 0 + column = 0 + for character in text[:index]: + if character == "\n": + line += 1 + column = 0 else: - c += 1 - idx += 1 + column += 2 if ord(character) > 0xFFFF else 1 + return line, column - return l, c - @staticmethod def get_index_from_line_col(text: str, line: int, col: int) -> int: - """ - Returns the index of the given zero-indexed line and column number in the given text - """ + """Translate a zero-based LSP UTF-16 position into a Python text index.""" + if line < 0 or col < 0: + raise ValueError("LSP line and column must be non-negative") idx = 0 while line > 0: - assert idx < len(text), (idx, len(text), text) + if idx >= len(text): + raise ValueError("LSP line is outside the document") if text[idx] == "\n": line -= 1 idx += 1 - idx += col + while col > 0: + if idx >= len(text) or text[idx] == "\n": + raise ValueError("LSP column is outside the line") + units = 2 if ord(text[idx]) > 0xFFFF else 1 + if col < units: + raise ValueError("LSP column splits a UTF-16 surrogate pair") + idx += 1 + col -= units return idx - + @staticmethod - def get_updated_position_from_line_and_column_and_edit(l: int, c: int, text_to_be_inserted: str) -> Tuple[int, int]: - """ - Utility function to get the position of the cursor after inserting text at a given line and column. - """ - num_newlines_in_gen_text = text_to_be_inserted.count('\n') + def get_updated_position_from_line_and_column_and_edit(l: int, c: int, text_to_be_inserted: str) -> Tuple[int, int]: # noqa: E741 + """Return the LSP UTF-16 cursor position after inserting text.""" + # Preserve existing named arguments `l` and `c` for API compatibility. + line, column = l, c + num_newlines_in_gen_text = text_to_be_inserted.count("\n") if num_newlines_in_gen_text > 0: - l += num_newlines_in_gen_text - c = len(text_to_be_inserted.split('\n')[-1]) + line += num_newlines_in_gen_text + column = TextUtils._utf16_length(text_to_be_inserted.split("\n")[-1]) else: - c += len(text_to_be_inserted) - return (l, c) + column += TextUtils._utf16_length(text_to_be_inserted) + return line, column class PathUtils: """ diff --git a/tests/multilspy/test_completion_responses.py b/tests/multilspy/test_completion_responses.py index 9bd52fc8..4d86e570 100644 --- a/tests/multilspy/test_completion_responses.py +++ b/tests/multilspy/test_completion_responses.py @@ -74,3 +74,20 @@ async def completion(params): assert result == EXPECTED assert seen == [1, 3, 3] assert not server.open_file_buffers + + +@pytest.mark.asyncio +async def test_completion_deduplication_preserves_server_ranking(server): + # Duplicates must not scramble server ordering (e.g. with randomized hash + # seeds); rank order is meaningful for editors and coding agents. + candidates = [ + {"label": "zeta", "kind": 6}, + {"label": "alpha", "kind": 6}, + {"label": "zeta", "kind": 6}, + {"label": "beta", "kind": 6}, + ] + server.server.send.completion = AsyncMock(return_value=candidates) + suggestions = await server.request_completions("example.py", 0, 0) + assert [item["completionText"] for item in suggestions] == ["zeta", "alpha", "beta"] + assert server.server.send.completion.await_count == 1 + assert not server.open_file_buffers diff --git a/tests/multilspy/test_multilspy_pyright.py b/tests/multilspy/test_multilspy_pyright.py index 70524701..003b7390 100644 --- a/tests/multilspy/test_multilspy_pyright.py +++ b/tests/multilspy/test_multilspy_pyright.py @@ -113,14 +113,15 @@ def _pyright_version(language_server_binary): also carries the version in its package.json next to the resolved script. """ binary = Path(language_server_binary) - sibling = binary.with_name("pyright") - if sibling.is_file(): - completed = subprocess.run( - [str(sibling), "--version"], capture_output=True, text=True, timeout=60, check=False - ) - match = re.search(r"pyright (\d+)\.(\d+)\.(\d+)", completed.stdout + completed.stderr) - if completed.returncode == 0 and match: - return tuple(int(part) for part in match.groups()) + for name in ("pyright", "pyright.cmd", "pyright.exe"): + sibling = binary.with_name(name) + if sibling.is_file(): + completed = subprocess.run( + [str(sibling), "--version"], capture_output=True, text=True, timeout=60, check=False + ) + match = re.search(r"pyright (\d+)\.(\d+)\.(\d+)", completed.stdout + completed.stderr) + if completed.returncode == 0 and match: + return tuple(int(part) for part in match.groups()) package_json = binary.resolve().parent / "package.json" if package_json.is_file(): version = json.loads(package_json.read_text(encoding="utf-8")).get("version", "") @@ -167,7 +168,9 @@ def pyright_binary(): pytest.skip("Set MULTILSPY_PYRIGHT_TEST_BINARY to a preinstalled executable") binary = Path(provided) if not binary.is_absolute() or not binary.is_file(): - pytest.skip("The explicit Pyright executable is unavailable") + pytest.fail("MULTILSPY_PYRIGHT_TEST_BINARY must be an existing absolute file") + if os.name != "nt" and not os.access(binary, os.X_OK): + pytest.fail("MULTILSPY_PYRIGHT_TEST_BINARY must be executable") return str(binary) @@ -331,9 +334,12 @@ async def exercise(): assert definition[0]["relativePath"] == "lib.py" assert definition[0]["range"] == _range(0, 4, 0, 9) - references = await asyncio.wait_for( - server.request_references("lib.py", 0, 5), timeout=8 - ) + # Keep the import and definition open to avoid relying on when + # background workspace indexing completes on a cold runner. + with server.open_file("app.py"), server.open_file("lib.py"): + references = await asyncio.wait_for( + server.request_references("lib.py", 0, 5), timeout=8 + ) assert [(item["relativePath"], item["range"]) for item in references] == [ ("app.py", _range(0, 16, 0, 21)), ("app.py", _range(2, 8, 2, 13)), @@ -410,9 +416,10 @@ async def exercise(): ] # References exclude the declaration (multilspy sends includeDeclaration=false). - references = await asyncio.wait_for( - server.request_references("shapes.py", 17, 6), timeout=8 - ) + with server.open_file("shapes.py"), server.open_file("report.py"): + references = await asyncio.wait_for( + server.request_references("shapes.py", 17, 6), timeout=8 + ) assert [(item["relativePath"], item["range"]) for item in references] == [ ("report.py", _range(2, 26, 2, 32)), ("report.py", _range(5, 11, 5, 17)), @@ -867,15 +874,25 @@ async def test_real_pyright_type_checking_mode_controls_push_diagnostics( async def exercise(): async with server.start_server(): with server.open_file("invalid.py"): - # Pyright publishes once per open file, also when the list is empty. + # Pyright can publish an initial empty snapshot and then a + # complete analysis. Observe until the expected diagnostic + # state appears, with an explicit finite deadline. loop = asyncio.get_running_loop() deadline = loop.time() + 18 - while True: - notification = await server.next_diagnostics( - timeout=max(0.01, deadline - loop.time()) - ) - if notification["uri"] == source.as_uri(): - return notification["diagnostics"] + observed = None + while loop.time() < deadline: + try: + notification = await server.next_diagnostics( + timeout=min(2, max(0.01, deadline - loop.time())) + ) + except asyncio.TimeoutError: + continue + if notification.get("uri") != source.as_uri(): + continue + observed = notification.get("diagnostics", []) + if {item.get("code") for item in observed} == expected_codes: + return observed + pytest.fail(f"Expected diagnostics {expected_codes!r}; last received: {observed!r}") diagnostics = await asyncio.wait_for(exercise(), timeout=30) assert {entry["code"] for entry in diagnostics} == expected_codes @@ -919,3 +936,122 @@ def test_real_pyright_sync_api_works_and_closes_provider( assert sync.language_server.server.process is None assert sync.loop.is_closed() assert not sync.loop_thread.is_alive() + + +def test_invalid_explicit_pyright_binary_fails_instead_of_skipping( + request, monkeypatch, tmp_path +): + # A broken CI installation or an incorrectly set env var must fail visibly, + # not turn all real Pyright tests green by skipping them. + monkeypatch.setenv("MULTILSPY_PYRIGHT_TEST_BINARY", str(tmp_path / "not-installed")) + with pytest.raises(pytest.fail.Exception, match="existing absolute file"): + request.getfixturevalue("pyright_binary") + + +@pytest.mark.asyncio +async def test_real_pyright_unicode_workspace_and_restart(tmp_path, pyright_binary): + # Spaces, non-ASCII names and non-BMP characters must survive URI encoding + # and reuse of a LanguageServer instance must not replay old notifications. + root = tmp_path / "Python project 中文 🐍" + root.mkdir() + (root / "functions.py").write_text( + "def greet(name: str) -> str:\n return name.upper()\n", encoding="utf-8" + ) + (root / "caller.py").write_text( + "from functions import greet\nresult = greet('Ada')\n", encoding="utf-8" + ) + server = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), + str(root), + ) + params = server._get_initialize_params(str(root)) + assert params["rootUri"] == root.as_uri() + assert params["workspaceFolders"][0]["uri"] == root.as_uri() + + for attempt in range(2): + previous_queue = server.diagnostics + if attempt: + previous_queue.put_nowait({"uri": "file:///old-session.py"}) + server.diagnostics_dropped = True + async with server.start_server(): + assert server.diagnostics is not previous_queue + assert not server.diagnostics_dropped + definition = await asyncio.wait_for( + server.request_definition("caller.py", 1, 10), timeout=8 + ) + assert [(item["relativePath"], item["range"]) for item in definition] == [ + ("functions.py", _range(0, 4, 0, 9)) + ] + assert server.server.process is None + assert not server.server_started + + +@pytest.mark.asyncio +async def test_real_pyright_incremental_edits_use_utf16_columns( + python_project, create_pyright +): + """Local buffer and Pyright must agree on didChange after an astral symbol.""" + source = python_project / "emoji.py" + original = source.read_bytes() + server = create_pyright() + async with server.start_server(): + with server.open_file("emoji.py"): + before = await asyncio.wait_for(server.request_definition("emoji.py", 0, 14), 8) + assert [(item["relativePath"], item["range"]) for item in before] == [ + ("emoji.py", _range(0, 0, 0, 1)) + ] + # `x` after the emoji starts at UTF-16 column 14, not codepoint 13. + cursor = server.insert_text_at_position("emoji.py", 0, 14, "missing_") + assert cursor == {"line": 0, "character": 22} + assert server.get_open_file_text("emoji.py") == "x = '😀'; y = missing_x\n" + for _ in range(20): + changed = await asyncio.wait_for( + server.request_definition("emoji.py", 0, 18), timeout=8 + ) + if not changed: + break + await asyncio.sleep(0.1) + assert changed == [] + + assert server.delete_text_between_positions( + "emoji.py", {"line": 0, "character": 14}, + {"line": 0, "character": 22}, + ) == "missing_" + assert server.get_open_file_text("emoji.py").encode("utf-8") == original + for _ in range(20): + restored = await asyncio.wait_for( + server.request_definition("emoji.py", 0, 14), timeout=8 + ) + if restored: + break + await asyncio.sleep(0.1) + assert [(item["relativePath"], item["range"]) for item in restored] == [ + ("emoji.py", _range(0, 0, 0, 1)) + ] + assert source.read_bytes() == original + assert server.server.process is None + + +@pytest.mark.parametrize("extension", ["", ".cmd", ".exe"]) +def test_pyright_version_resolves_platform_specific_cli_wrappers( + tmp_path, monkeypatch, extension +): + binary = tmp_path / "pyright-langserver" + binary.write_text("fake", encoding="utf-8") + sibling = tmp_path / ("pyright" + extension) + sibling.write_text("fake", encoding="utf-8") + calls = [] + + def fake_run(argv, **kwargs): + calls.append((argv, kwargs)) + return subprocess.CompletedProcess(argv, 0, stdout="pyright 1.1.413\n", stderr="") + + monkeypatch.setattr(subprocess, "run", fake_run) + assert _pyright_version(binary) == TESTED_PYRIGHT_VERSION + assert calls[0][0] == [str(sibling), "--version"] + assert calls[0][1]["timeout"] == 60 diff --git a/tests/multilspy/test_pyright_adapter_notifications.py b/tests/multilspy/test_pyright_adapter_notifications.py index 44eaef84..f213948e 100644 --- a/tests/multilspy/test_pyright_adapter_notifications.py +++ b/tests/multilspy/test_pyright_adapter_notifications.py @@ -14,6 +14,7 @@ PyrightServer, ) from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_exceptions import MultilspyException from multilspy.multilspy_logger import MultilspyLogger @@ -42,6 +43,9 @@ def pyright(tmp_path): "definitionProvider": True, "referencesProvider": True, "hoverProvider": True, + "completionProvider": True, + "documentSymbolProvider": True, + "workspaceSymbolProvider": True, "textDocumentSync": 2, } } @@ -67,7 +71,7 @@ def test_pyright_initialize_params_are_loaded_from_profile(tmp_path): assert params["capabilities"]["general"]["positionEncodings"] == ["utf-16"] assert params["capabilities"]["workspace"]["applyEdit"] is False assert params["capabilities"]["workspace"]["configuration"] is True - assert params["capabilities"]["textDocument"]["completion"] + assert params["capabilities"]["textDocument"]["completion"]["contextSupport"] is True assert params["capabilities"]["textDocument"]["signatureHelp"] @@ -99,6 +103,9 @@ async def test_pyright_accepts_empty_capability_options(pyright): "definitionProvider": {}, "referencesProvider": {}, "hoverProvider": {}, + "completionProvider": {}, + "documentSymbolProvider": {}, + "workspaceSymbolProvider": {}, "positionEncoding": "utf-16", } } @@ -118,17 +125,19 @@ async def test_pyright_configuration_is_explicit_and_bounded(pyright): { "items": [ {"section": "python"}, + {"section": "python.analysis"}, {"section": "pyright"}, {"section": "untrusted"}, ] } ) assert result[0] == {"analysis": {}} - assert result[1]["disableLanguageServices"] is False - assert result[2] is None + assert result[1] == {} + assert result[2]["disableLanguageServices"] is False + assert result[3] is None assert await handler({"items": []}) == [] assert await handler({"items": "bad"}) == [] - assert await handler({"items": [{}] * 65}) == [] + assert await handler({"items": [{}] * 65}) == [None] * 65 assert await handler(None) == [] @@ -172,8 +181,8 @@ async def test_pyright_diagnostics_are_queued_not_dropped_silently(pyright): } ) assert server.diagnostics_dropped is True - assert (await server.next_diagnostics(timeout=1))["version"] == 0 - assert (await server.next_diagnostics(timeout=1))["version"] == 1 + updates = [await server.next_diagnostics(timeout=1) for _ in range(64)] + assert [item["version"] for item in updates] == list(range(1, 64)) + [65] @pytest.mark.asyncio @@ -183,11 +192,18 @@ async def test_pyright_diagnostics_are_queued_not_dropped_silently(pyright): (None, TypeError, "Invalid Pyright"), ([], TypeError, "Invalid Pyright"), ({}, ValueError, "Pyright missing required capability"), + ( + {"definitionProvider": True, "referencesProvider": True, "hoverProvider": True}, + ValueError, "Pyright missing required capability: completionProvider", + ), ( { "definitionProvider": True, "referencesProvider": True, "hoverProvider": True, + "completionProvider": True, + "documentSymbolProvider": True, + "workspaceSymbolProvider": True, "positionEncoding": "utf-8", }, ValueError, @@ -266,3 +282,65 @@ async def enter_context(): transport.stop.assert_awaited_once() transport.shutdown.assert_not_awaited() assert not server.server_started + + +@pytest.mark.asyncio +async def test_pyright_restarting_instance_resets_session_state(pyright): + server, transport, _, notifications = pyright + async with server.start_server(): + await notifications["textDocument/publishDiagnostics"]( + {"uri": "file:///old-session.py", "diagnostics": [{"message": "stale"}]} + ) + server.diagnostics_dropped = True + assert server.diagnostics.qsize() == 1 + assert server.completions_available.is_set() + + async def initialize_again(_params): + # Completion readiness and the diagnostics queue belong to this run. + assert not server.completions_available.is_set() + assert server.diagnostics.empty() + assert not server.diagnostics_dropped + return {"capabilities": { + "definitionProvider": True, + "referencesProvider": True, + "hoverProvider": True, + "completionProvider": True, + "documentSymbolProvider": True, + "workspaceSymbolProvider": True, + }} + + transport.send.initialize.side_effect = initialize_again + async with server.start_server(): + assert server.diagnostics.empty() + assert server.completions_available.is_set() + assert not server.diagnostics_dropped + assert transport.start.await_count == 2 + assert transport.stop.await_count == 2 + assert transport.shutdown.await_count == 2 + + +@pytest.mark.asyncio +async def test_pyright_does_not_allow_nested_server_lifetimes(pyright): + server, transport, _, _ = pyright + async with server.start_server(): + with pytest.raises(MultilspyException, match="already started"): + async with server.start_server(): + pytest.fail("Nested start must fail before altering the running server") + assert server.server_started + assert transport.stop.await_count == 0 + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_unresponsive_shutdown_cannot_block_pyright_cleanup(pyright): + server, transport, _, _ = pyright + server._shutdown_timeout_seconds = 0.05 + waiting_forever = asyncio.Event() + transport.shutdown.side_effect = waiting_forever.wait + with pytest.raises(asyncio.TimeoutError): + async with server.start_server(): + assert server.server_started + transport.shutdown.assert_awaited_once() + transport.stop.assert_awaited_once() + assert not server.server_started diff --git a/tests/multilspy/test_utf16_buffer_positions.py b/tests/multilspy/test_utf16_buffer_positions.py new file mode 100644 index 00000000..cd6d8209 --- /dev/null +++ b/tests/multilspy/test_utf16_buffer_positions.py @@ -0,0 +1,60 @@ +"""Regression tests for UTF-16 LSP positions in in-memory file buffers. + +Other language servers share this code, so use both Python adapters with a +mocked transport and no external binary or network access. +""" + +from unittest.mock import Mock + +import pytest + +from multilspy import LanguageServer +from multilspy.multilspy_config import Language, MultilspyConfig +from multilspy.multilspy_logger import MultilspyLogger +from multilspy.multilspy_utils import TextUtils + + +@pytest.mark.parametrize("backend", ["jedi", "pyright"]) +def test_utf16_insert_and_delete_do_not_desynchronize_file_buffer(tmp_path, backend): + source = "value = '🐍'; target = 1\n" + filename = tmp_path / "example.py" + filename.write_text(source, encoding="utf-8") + server = LanguageServer.create( + MultilspyConfig(code_language=Language.PYTHON, python_server=backend), + MultilspyLogger(), str(tmp_path.resolve()) + ) + server.server = Mock() + server.server_started = True + before_target = source.index("target") + column = TextUtils._utf16_length(source[:before_target]) + assert column == before_target + 1 # Python index excludes surrogate pair length. + + with server.open_file("example.py"): + position = server.insert_text_at_position("example.py", 0, column, "🦊_") + assert position == {"line": 0, "character": column + 3} + assert server.get_open_file_text("example.py") == "value = '🐍'; 🦊_target = 1\n" + assert server.delete_text_between_positions( + "example.py", {"line": 0, "character": column}, + {"line": 0, "character": column + 3}, + ) == "🦊_" + assert server.get_open_file_text("example.py") == source + changes = [call.args[0] for call in server.server.notify.did_change_text_document.call_args_list] + assert [event["textDocument"]["version"] for event in changes] == [1, 2] + assert [event["contentChanges"][0]["range"]["start"]["character"] for event in changes] == [column, column] + assert filename.read_text(encoding="utf-8") == source + assert not server.open_file_buffers + + +def test_utf16_positions_round_trip_and_reject_half_surrogate(): + text = "a🐍b\n🦊x\n" + for idx in range(len(text) + 1): + line, col = TextUtils.get_line_col_from_index(text, idx) + assert TextUtils.get_index_from_line_col(text, line, col) == idx + with pytest.raises(ValueError, match="surrogate"): + TextUtils.get_index_from_line_col(text, 0, 2) + with pytest.raises(ValueError, match="outside the line"): + TextUtils.get_index_from_line_col(text, 0, 8) + with pytest.raises(ValueError, match="non-negative"): + TextUtils.get_index_from_line_col(text, -1, 0) + assert TextUtils.get_updated_position_from_line_and_column_and_edit(0, 0, "🐍") == (0, 2) + assert TextUtils.get_updated_position_from_line_and_column_and_edit(0, 9, "🐍\n🦊x") == (1, 3) From b5325f19c7b77317bd4ab7c1ff3c6bb8fa5b8f1b Mon Sep 17 00:00:00 2001 From: Grammy Jiang Date: Thu, 22 Oct 2026 06:32:30 +1100 Subject: [PATCH 7/8] feat(pyright): complete writable LSP workflows and native Windows QA Support explicit, bounded workspace/applyEdit authorization with fail-closed LSP response validation. Cover genuine organize-import edits, create-type-stub direct writes, and documented process/workspace isolation boundaries. Fix Python 3.14 Windows file URI drive casing and strengthen portable LSP tests. Verify pinned Pyright 1.1.413 across Windows 3.10/3.12/3.13/3.14, Ubuntu full suite 3.10/3.12/3.14, and native macOS/Linux regression suites. --- .github/workflows/test-workflow.yaml | 54 ++++ README.md | 38 ++- .../pyright_language_server/pyright_server.py | 81 +++++- src/multilspy/multilspy_utils.py | 7 +- tests/multilspy/test_multilspy_pyright.py | 257 ++++++++++++++++-- .../multilspy/test_path_utils_portability.py | 28 ++ .../test_pyright_adapter_notifications.py | 116 +++++++- 7 files changed, 540 insertions(+), 41 deletions(-) create mode 100644 tests/multilspy/test_path_utils_portability.py diff --git a/.github/workflows/test-workflow.yaml b/.github/workflows/test-workflow.yaml index 663e46f5..836a1427 100644 --- a/.github/workflows/test-workflow.yaml +++ b/.github/workflows/test-workflow.yaml @@ -98,3 +98,57 @@ jobs: - name: Run tests run: pytest tests/multilspy -v --tb=short + + pyright-windows: + name: Pyright native Windows (Python ${{ matrix.python-version }}) + runs-on: windows-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.12", "3.13", "3.14"] + env: + PYTHONUTF8: "1" + + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: ${{ matrix.python-version }} + + - name: Set up Node.js + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: "20" + + - name: Install Python dependencies + run: | + python -m pip install -r requirements.txt + python -m pip install -e . + + - name: Install pinned Pyright for Windows + shell: pwsh + run: | + $root = Join-Path $env:RUNNER_TEMP "multilspy-pyright" + npm install --prefix $root --no-save --no-package-lock --ignore-scripts --no-audit --no-fund pyright@1.1.413 + if ($LASTEXITCODE -ne 0) { throw "npm installation failed" } + $binary = Join-Path $root "node_modules/.bin/pyright-langserver.cmd" + if (-not (Test-Path -LiteralPath $binary -PathType Leaf)) { throw "Pinned Pyright not installed" } + "MULTILSPY_PYRIGHT_TEST_BINARY=$binary" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8 + + - name: Test real Pyright, protocol, Unicode and lifecycle on Windows + run: >- + python -m pytest -q + tests/multilspy/test_multilspy_pyright.py + tests/multilspy/test_pyright_adapter_notifications.py + tests/multilspy/test_pyright_process_lifecycle.py + tests/multilspy/test_lsp_result_shapes.py + tests/multilspy/test_path_utils_portability.py + tests/multilspy/test_completion_responses.py + tests/multilspy/test_utf16_buffer_positions.py + tests/multilspy/test_python_completions.py + tests/multilspy/test_sync_startup.py + tests/multilspy/test_sync_file_thread.py + --tb=short diff --git a/README.md b/README.md index a6ebd3a6..cdf407bf 100644 --- a/README.md +++ b/README.md @@ -110,11 +110,39 @@ Pyright, update and revalidate the expected responses rather than silently skipping mismatched versions. For third-party import resolution, configure the project through `pyrightconfig.json` or `[tool.pyright]` in `pyproject.toml`. -The adapter rejects server-initiated workspace edits, but this is not an OS -sandbox. The low-level `server.send` API permits raw executeCommand requests, -including commands that may write files directly; clients should not expose -those requests to untrusted callers. Enforce workspace and subprocess -permissions outside multilspy when building an agent-facing integration. +By default, Pyright's `workspace/applyEdit` requests are refused and organize +imports is disabled. To support editor-controlled writes, the embedding client +can register an **async** handler before starting the server: + +```python +# `lsp` is a PyrightServer returned by LanguageServer.create(...). +async def apply_workspace_edit(params): + # Validate affected URIs, ranges, document versions and user permission. + # Handle BOTH `changes` and `documentChanges` (including file operations) + # and apply the edit atomically in YOUR editor/workspace layer. + return {"applied": False, "failureReason": "Not approved"} + +lsp.set_workspace_edit_handler(apply_workspace_edit, timeout_seconds=60) +``` + +When a handler is installed, the adapter advertises workspace `applyEdit` +support and enables Pyright organize-imports commands. The handler's LSP +response reports whether **the client actually applied the edit**. A successful +rename request by itself returns an edit *proposal*; multilspy does not apply +that proposal. It is the caller's responsibility to preview, approve, and +apply the WorkspaceEdit, including document versions and file operations. +If documents are already open, update both the editor's in-memory buffers +and the language server's `didChange` state; writing the disk copy alone leaves +the LSP document snapshot stale. Handler exceptions and timeouts are reported +as unsuccessful edits and never treated as authorization to write. + +**Security boundary:** this opt-in callback is NOT a subprocess sandbox. +In Pyright 1.1.413, `pyright.createtypestub` directly writes `.pyi` files on +the language-server side without calling `workspace/applyEdit`. Other raw +`server.send.execute_command` calls may have similar side effects. Never expose +arbitrary commands to untrusted callers; use OS-level filesystem restrictions +and isolated workspaces for untrusted projects. An embedding application must enforce its own workspace authorization and +process confinement independently of multilspy's generic LSP integration. ## Usage Example usage: diff --git a/src/multilspy/language_servers/pyright_language_server/pyright_server.py b/src/multilspy/language_servers/pyright_language_server/pyright_server.py index 319e026d..f683aff6 100644 --- a/src/multilspy/language_servers/pyright_language_server/pyright_server.py +++ b/src/multilspy/language_servers/pyright_language_server/pyright_server.py @@ -4,12 +4,14 @@ """ import asyncio +import inspect import json import logging +import math import os import pathlib import shutil -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Awaitable, Callable from contextlib import asynccontextmanager from multilspy.language_server import LanguageServer @@ -49,6 +51,32 @@ def __init__(self, config: MultilspyConfig, logger: MultilspyLogger, repository_ # bounded queue so callers can read them without unbounded growth. self.diagnostics: asyncio.Queue = asyncio.Queue(maxsize=64) self.diagnostics_dropped = False + # Applying an LSP WorkspaceEdit belongs to the embedding client. A + # callback must be installed explicitly before starting the server. + self._workspace_edit_handler: Callable[[dict], Awaitable[dict]] | None = None + self._workspace_edit_timeout_seconds = 30.0 + + def set_workspace_edit_handler( + self, handler: Callable[[dict], Awaitable[dict]] | None, + *, timeout_seconds: float = 30.0, + ) -> None: + """Opt in to processing server-requested workspace edits. + + The callback receives the original ApplyWorkspaceEditParams and must + authorize and apply the proposed edit, returning an LSP response such + as ``{"applied": True}``. No filesystem changes are made by this + adapter. This does NOT restrict commands that write directly on the + Pyright server side; callers must sandbox untrusted server processes. + """ + if self.server_started: + raise MultilspyException("Cannot change workspace edit handler while running") + if handler is not None and not inspect.iscoroutinefunction(handler): + raise TypeError("Workspace edit handler must be an async function or None") + if (not isinstance(timeout_seconds, (int, float)) or + not math.isfinite(timeout_seconds) or timeout_seconds <= 0): + raise ValueError("Workspace edit timeout must be a positive finite number") + self._workspace_edit_handler = handler + self._workspace_edit_timeout_seconds = timeout_seconds def _get_initialize_params(self, repository_absolute_path: str) -> InitializeParams: """ @@ -72,6 +100,9 @@ def _get_initialize_params(self, repository_absolute_path: str) -> InitializePar assert d["workspaceFolders"][0]["name"] == "$name" d["workspaceFolders"][0]["name"] = os.path.basename(repository_absolute_path) + # Advertise application support only when an embedding client has + # explicitly supplied a handler that authorizes and applies edits. + d["capabilities"]["workspace"]["applyEdit"] = self._workspace_edit_handler is not None return d async def next_diagnostics(self, timeout: float = 5.0) -> dict: @@ -115,7 +146,7 @@ async def workspace_configuration(params): "python.analysis": {}, "pyright": { "disableLanguageServices": False, - "disableOrganizeImports": True, + "disableOrganizeImports": self._workspace_edit_handler is None, }, } answers = [] @@ -125,8 +156,38 @@ async def workspace_configuration(params): return answers async def workspace_apply_edit(params): - # multilspy never applies server-initiated edits. - return {"applied": False, "failureReason": "multilspy Pyright client is read-only"} + if self._workspace_edit_handler is None: + return {"applied": False, "failureReason": "multilspy Pyright client is read-only"} + try: + response = await asyncio.wait_for( + self._workspace_edit_handler(params), + timeout=self._workspace_edit_timeout_seconds, + ) + if not isinstance(response, dict) or type(response.get("applied")) is not bool: + raise ValueError("Invalid LSP workspace edit result") + result = {"applied": response["applied"]} + if not result["applied"]: + if "failureReason" in response: + reason = response["failureReason"] + if not isinstance(reason, str): + raise ValueError("Invalid workspace edit failureReason") + result["failureReason"] = reason[:256] + if "failedChange" in response: + number = response["failedChange"] + if type(number) is not int or number < 0: + raise ValueError("Invalid workspace edit failedChange") + result["failedChange"] = number + return result + except asyncio.TimeoutError: + self.logger.log("LSP: workspace edit handler timed out", logging.WARNING) + return {"applied": False, "failureReason": "Workspace edit handler timed out"} + except Exception as exc: + # Never report applied=true when a client edit failed, or + # echo untrusted exception messages that contain local paths. + self.logger.log( + f"LSP: workspace edit handler failed ({type(exc).__name__})", logging.WARNING + ) + return {"applied": False, "failureReason": "Workspace edit handler failed"} async def publish_diagnostics(params): if not isinstance(params, dict) or not isinstance(params.get("uri"), str): @@ -197,8 +258,14 @@ async def window_log_message(msg): yield self finally: if initialized: - await asyncio.wait_for( - self.server.shutdown(), timeout=self._shutdown_timeout_seconds - ) + try: + await asyncio.wait_for( + self.server.shutdown(), timeout=self._shutdown_timeout_seconds + ) + except asyncio.TimeoutError: + # A slow/blocked language server must not turn an + # otherwise successful operation into a failed + # context exit; stop() still terminates it. + self.logger.log("LSP: graceful Pyright shutdown timed out", logging.WARNING) finally: await self.server.stop() diff --git a/src/multilspy/multilspy_utils.py b/src/multilspy/multilspy_utils.py index 0ad3dbb1..781ddd86 100644 --- a/src/multilspy/multilspy_utils.py +++ b/src/multilspy/multilspy_utils.py @@ -103,7 +103,12 @@ def get_relative_path(path: str, base_path: str) -> Union[str, None]: Gets relative path if it's possible (paths should be on the same drive), returns `None` otherwise. """ - if PurePath(path).drive == PurePath(base_path).drive: + # Windows drive letters are case-insensitive. Python 3.14's + # urllib.request.url2pathname preserves the URL's drive casing, + # unlike older Python releases which uppercased it. Compare drives + # using the native filesystem rules so Pyright's file:///c%3A/... URI + # resolves relative to a workspace rooted at C:\... . + if os.path.normcase(PurePath(path).drive) == os.path.normcase(PurePath(base_path).drive): return str(PurePath(os.path.relpath(path, base_path))) return None diff --git a/tests/multilspy/test_multilspy_pyright.py b/tests/multilspy/test_multilspy_pyright.py index 003b7390..98f67277 100644 --- a/tests/multilspy/test_multilspy_pyright.py +++ b/tests/multilspy/test_multilspy_pyright.py @@ -14,6 +14,8 @@ import os import re import subprocess +import sys +import venv from pathlib import Path import pytest @@ -28,6 +30,7 @@ from multilspy.multilspy_config import Language, MultilspyConfig from multilspy.multilspy_exceptions import MultilspyException from multilspy.multilspy_logger import MultilspyLogger +from multilspy.multilspy_utils import PathUtils, TextUtils # The adapter, the capability matrix and every exact payload in this module # were captured against this Pyright release. @@ -105,6 +108,36 @@ def _range(start_line, start_character, end_line, end_character): } +def _same_file_uri(left, right): + """Compare file locations, not the OS-specific spelling of LSP URIs. + + Windows pathlib emits file:///C:/path, while Pyright's vscode-uri emits + file:///c%3A/path; both represent the same file on the same filesystem. + """ + return os.path.normcase(PathUtils.uri_to_path(left)) == os.path.normcase( + PathUtils.uri_to_path(right) + ) + + +def _portable_lsp_payload(value): + """Normalize only file-URI fields/keys in exact wire response assertions.""" + if isinstance(value, list): + return [_portable_lsp_payload(item) for item in value] + if isinstance(value, dict): + output = {} + for key, item in value.items(): + normalized_key = ( + os.path.normcase(PathUtils.uri_to_path(key)) + if isinstance(key, str) and key.startswith("file:") else key + ) + if key in ("uri", "targetUri") and isinstance(item, str) and item.startswith("file:"): + output[normalized_key] = os.path.normcase(PathUtils.uri_to_path(item)) + else: + output[normalized_key] = _portable_lsp_payload(item) + return output + return value + + def _pyright_version(language_server_binary): """Return the Pyright version tuple for a pyright-langserver executable. @@ -113,21 +146,32 @@ def _pyright_version(language_server_binary): also carries the version in its package.json next to the resolved script. """ binary = Path(language_server_binary) + # npm puts .cmd entry points in node_modules/.bin on Windows; they are + # not directly executable with subprocess(shell=False). Read the pinned + # package metadata instead (and avoid invoking wrapper bootstrap logic). + candidates = ( + binary.resolve().parent / "package.json", + binary.parent.parent / "pyright" / "package.json", + ) + for package_json in candidates: + if package_json.is_file(): + version = json.loads(package_json.read_text(encoding="utf-8")).get("version", "") + match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version) + if match: + return tuple(int(part) for part in match.groups()) + for name in ("pyright", "pyright.cmd", "pyright.exe"): sibling = binary.with_name(name) if sibling.is_file(): + command = [str(sibling), "--version"] + if os.name == "nt" and sibling.suffix.lower() == ".cmd": + command = ["cmd.exe", "/d", "/c", str(sibling), "--version"] completed = subprocess.run( - [str(sibling), "--version"], capture_output=True, text=True, timeout=60, check=False + command, capture_output=True, text=True, timeout=60, check=False ) match = re.search(r"pyright (\d+)\.(\d+)\.(\d+)", completed.stdout + completed.stderr) if completed.returncode == 0 and match: return tuple(int(part) for part in match.groups()) - package_json = binary.resolve().parent / "package.json" - if package_json.is_file(): - version = json.loads(package_json.read_text(encoding="utf-8")).get("version", "") - match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version) - if match: - return tuple(int(part) for part in match.groups()) return None @@ -374,7 +418,7 @@ async def exercise(): if workspace_symbols: break await asyncio.sleep(0.1) - assert workspace_symbols == [ + assert _portable_lsp_payload(workspace_symbols) == _portable_lsp_payload([ { "name": "greet", "kind": 12, @@ -383,7 +427,7 @@ async def exercise(): "range": _range(0, 4, 0, 9), }, } - ] + ]) await asyncio.wait_for(exercise(), timeout=30) assert server.server.process is None @@ -471,14 +515,14 @@ async def exercise(): workspace_symbols = await asyncio.wait_for( server.request_workspace_symbol("Square"), timeout=8 ) - assert { + assert _portable_lsp_payload({ "name": "Square", "kind": 5, "location": { "uri": (python_project / "shapes.py").as_uri(), "range": _range(17, 6, 17, 12), }, - } in workspace_symbols + }) in _portable_lsp_payload(workspace_symbols) await asyncio.wait_for(exercise(), timeout=30) assert server.server.process is None @@ -643,7 +687,9 @@ async def exercise(): ), server.open_file("report.py"): for method, params, expected in corpus: result = await asyncio.wait_for(getattr(send, method)(params), timeout=8) - assert result == expected, (method, params.get("position", params)) + assert _portable_lsp_payload(result) == _portable_lsp_payload(expected), ( + method, params.get("position", params) + ) # The high-level API passes UTF-16 columns through unchanged. definition = await asyncio.wait_for( @@ -659,7 +705,7 @@ async def exercise(): # Shape.area in the workspace and to typeshed's sum overloads. item = (await asyncio.wait_for(send.prepare_call_hierarchy(at("shapes.py", 25, 4)), timeout=8))[0] incoming = await asyncio.wait_for(send.incoming_calls({"item": item}), timeout=8) - assert incoming == [ + assert _portable_lsp_payload(incoming) == _portable_lsp_payload([ { "from": { "kind": 2, @@ -670,10 +716,12 @@ async def exercise(): }, "fromRanges": [_range(6, 10, 6, 20)], } - ] + ]) outgoing = await asyncio.wait_for(send.outgoing_calls({"item": item}), timeout=8) - workspace_calls = [call for call in outgoing if call["to"]["uri"] == uri("shapes.py")] - assert workspace_calls == [ + workspace_calls = [ + call for call in outgoing if _same_file_uri(call["to"]["uri"], uri("shapes.py")) + ] + assert _portable_lsp_payload(workspace_calls) == _portable_lsp_payload([ { "to": { "kind": 6, @@ -684,7 +732,7 @@ async def exercise(): }, "fromRanges": [_range(26, 21, 26, 25)], } - ] + ]) builtin_calls = [call for call in outgoing if call not in workspace_calls] assert builtin_calls for call in builtin_calls: @@ -697,7 +745,7 @@ async def exercise(): send.rename({**at("shapes.py", 17, 6), "newName": "Box"}), timeout=8 ) changes = sorted(proposal["documentChanges"], key=lambda change: change["textDocument"]["uri"]) - assert changes == [ + assert _portable_lsp_payload(changes) == _portable_lsp_payload([ { "textDocument": {"uri": uri("report.py"), "version": None}, "edits": [{"range": span, "newText": "Box"} for span in square_uses], @@ -706,7 +754,7 @@ async def exercise(): "textDocument": {"uri": uri("shapes.py"), "version": None}, "edits": [{"range": _range(17, 6, 17, 12), "newText": "Box"}], }, - ] + ]) # completionItem/resolve adds documentation to a raw item. completion = await asyncio.wait_for( @@ -786,7 +834,7 @@ async def permissive_configuration(params): while not proposal and loop.time() < deadline: await asyncio.sleep(0.1) proposal = await asyncio.wait_for(send.execute_command(command), timeout=8) - assert proposal == { + assert _portable_lsp_payload(proposal) == _portable_lsp_payload({ "changes": { report.as_uri(): [ { @@ -795,7 +843,7 @@ async def permissive_configuration(params): } ] } - } + }) for _ in range(50): if apply_requests: break @@ -833,7 +881,7 @@ async def exercise(): ) except asyncio.TimeoutError: continue - if notification.get("uri") != source.as_uri(): + if not _same_file_uri(notification.get("uri", ""), source.as_uri()): continue found.update( entry.get("code") @@ -887,7 +935,7 @@ async def exercise(): ) except asyncio.TimeoutError: continue - if notification.get("uri") != source.as_uri(): + if not _same_file_uri(notification.get("uri", ""), source.as_uri()): continue observed = notification.get("diagnostics", []) if {item.get("code") for item in observed} == expected_codes: @@ -1022,7 +1070,7 @@ async def test_real_pyright_incremental_edits_use_utf16_columns( "emoji.py", {"line": 0, "character": 14}, {"line": 0, "character": 22}, ) == "missing_" - assert server.get_open_file_text("emoji.py").encode("utf-8") == original + assert server.get_open_file_text("emoji.py") == source.read_text(encoding="utf-8") for _ in range(20): restored = await asyncio.wait_for( server.request_definition("emoji.py", 0, 14), timeout=8 @@ -1053,5 +1101,164 @@ def fake_run(argv, **kwargs): monkeypatch.setattr(subprocess, "run", fake_run) assert _pyright_version(binary) == TESTED_PYRIGHT_VERSION - assert calls[0][0] == [str(sibling), "--version"] + expected_command = [str(sibling), "--version"] + if os.name == "nt" and extension == ".cmd": + expected_command = ["cmd.exe", "/d", "/c", str(sibling), "--version"] + assert calls[0][0] == expected_command assert calls[0][1]["timeout"] == 60 + + +@pytest.mark.asyncio +async def test_real_pyright_opt_in_organize_imports_applies_via_authorized_client( + python_project, create_pyright +): + """An explicitly installed callback can apply an actual Pyright WorkspaceEdit. + + The library does not make file changes by itself. The callback simulates + the embedding editor's authorization, UTF-16 position handling and disk + persistence, restricted to a temporary fixture file. + """ + server = create_pyright() + report = python_project / "report.py" + before = {path: path.read_bytes() for path in python_project.iterdir() if path.is_file()} + done = asyncio.Event() + received = [] + + async def apply_authorized_edit(params): + received.append(params) + keys = list(params["edit"]["changes"]) + if len(keys) != 1 or not _same_file_uri(keys[0], report.as_uri()): + raise ValueError("Unexpected workspace edit target") + edits = params["edit"]["changes"][keys[0]] + content = report.read_text(encoding="utf-8") + translated = [] + for edit in edits: + start = edit["range"]["start"] + end = edit["range"]["end"] + translated.append(( + TextUtils.get_index_from_line_col(content, start["line"], start["character"]), + TextUtils.get_index_from_line_col(content, end["line"], end["character"]), + edit["newText"], + )) + for start, end, replacement in sorted(translated, reverse=True): + content = content[:start] + replacement + content[end:] + report.write_text(content, encoding="utf-8") + done.set() + return {"applied": True} + + server.set_workspace_edit_handler(apply_authorized_edit) + async def exercise(): + async with server.start_server(): + with server.open_file("report.py"): + command = {"command": "pyright.organizeimports", "arguments": [report.as_uri()]} + result = await asyncio.wait_for( + server.server.send.execute_command(command), timeout=8 + ) + assert isinstance(result, dict) + assert any(_same_file_uri(key, report.as_uri()) for key in result["changes"]) + await asyncio.wait_for(done.wait(), timeout=8) + + await asyncio.wait_for(exercise(), timeout=35) + assert len(received) == 1 + assert report.read_text(encoding="utf-8").startswith( + "import os\nimport sys\n\nfrom shapes import Point, Square, total_area" + ) + for path, contents in before.items(): + if path != report: + assert path.read_bytes() == contents + assert server.server.process is None + + +@pytest.mark.asyncio +async def test_real_pyright_create_type_stub_writes_without_workspace_apply_edit( + tmp_path, pyright_binary +): + """A Pyright command can write .pyi files directly, without asking applyEdit. + + Exercise only an isolated disposable virtualenv and project. This is an + explicit warning that merely denying workspace/applyEdit is not a sandbox. + """ + env_root = tmp_path / "venvs" + env = env_root / "isolated" + venv.create(env, with_pip=False) + if os.name == "nt": + site_packages = env / "Lib" / "site-packages" + else: + site_packages = env / "lib" / f"python{sys.version_info.major}.{sys.version_info.minor}" / "site-packages" + vendor = site_packages / "toy_untyped_package" + vendor.mkdir(parents=True) + (vendor / "__init__.py").write_text( + "def hello(x):\n return x * 2\n", encoding="utf-8" + ) + project = tmp_path / "project" + project.mkdir() + source = project / "app.py" + original = "import toy_untyped_package\nprint(toy_untyped_package.hello(3))\n" + source.write_text(original, encoding="utf-8") + (project / "pyrightconfig.json").write_text(json.dumps({ + "typeCheckingMode": "strict", + "reportMissingTypeStubs": "warning", + "venvPath": str(env_root), + "venv": "isolated", + "stubPath": "typings", + "include": ["app.py"], + }), encoding="utf-8") + server = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, python_server="pyright", + server_binary=pyright_binary, + ), + MultilspyLogger(), str(project) + ) + apply_requests = [] + # No edit callback is registered; prove the server still writes directly. + stub = project / "typings" / "toy_untyped_package" / "__init__.pyi" + + async def exercise(): + async with server.start_server(): + refuse_edit = server.server.on_request_handlers["workspace/applyEdit"] + + async def record_edit_request(params): + apply_requests.append(params) + return await refuse_edit(params) + + server.server.on_request_handlers["workspace/applyEdit"] = record_edit_request + with server.open_file("app.py"): + diagnostics = [] + loop = asyncio.get_running_loop() + deadline = loop.time() + 20 + while loop.time() < deadline: + try: + notification = await server.next_diagnostics(timeout=2) + except asyncio.TimeoutError: + continue + if _same_file_uri(notification.get("uri", ""), source.as_uri()): + diagnostics = notification.get("diagnostics", []) + if any(d.get("code") == "reportMissingTypeStubs" for d in diagnostics): + break + assert any(d.get("code") == "reportMissingTypeStubs" for d in diagnostics) + actions = await asyncio.wait_for(server.server.send.code_action({ + "textDocument": {"uri": source.as_uri()}, + "range": _range(0, 0, 0, len("import toy_untyped_package")), + "context": {"diagnostics": diagnostics}, + }), timeout=8) + action = next( + action for action in actions + if action.get("command", {}).get("command") == "pyright.createtypestub" + ) + assert not stub.exists() + await asyncio.wait_for( + server.server.send.execute_command(action["command"]), timeout=18 + ) + for _ in range(40): + if stub.is_file(): + break + await asyncio.sleep(0.1) + assert stub.is_file() + assert "def hello" in stub.read_text(encoding="utf-8") + + await asyncio.wait_for(exercise(), timeout=65) + assert source.read_text(encoding="utf-8") == original + assert server.server.process is None + assert not server.server_started + assert apply_requests == [] diff --git a/tests/multilspy/test_path_utils_portability.py b/tests/multilspy/test_path_utils_portability.py new file mode 100644 index 00000000..7ebfd6ac --- /dev/null +++ b/tests/multilspy/test_path_utils_portability.py @@ -0,0 +1,28 @@ +"""Cross-platform URI and Windows drive casing regressions. + +Exercise Windows semantics on Linux/macOS too, independent of running a +Windows interpreter; native Windows CI separately exercises real Pyright. +""" + +import ntpath +from pathlib import PureWindowsPath +from types import SimpleNamespace + +from multilspy.multilspy_utils import PathUtils +import multilspy.multilspy_utils as utils + + +def test_case_insensitive_windows_drives_are_same_drive(monkeypatch): + monkeypatch.setattr(utils, "PurePath", PureWindowsPath) + monkeypatch.setattr(utils, "os", SimpleNamespace(path=ntpath)) + # Pyright uses lowercase drive URI, pathlib workspace might uppercase it. + assert PathUtils.get_relative_path( + r"c:\Repo\src\module.py", r"C:\Repo" + ) == r"src\module.py" + assert PathUtils.get_relative_path( + r"D:\Repo\src\module.py", r"C:\Repo" + ) is None + # A differently cased but otherwise identical workspace is same location. + assert PathUtils.get_relative_path( + r"c:\REPO\module.py", r"C:\repo" + ) == "module.py" diff --git a/tests/multilspy/test_pyright_adapter_notifications.py b/tests/multilspy/test_pyright_adapter_notifications.py index f213948e..b8b12102 100644 --- a/tests/multilspy/test_pyright_adapter_notifications.py +++ b/tests/multilspy/test_pyright_adapter_notifications.py @@ -338,9 +338,119 @@ async def test_unresponsive_shutdown_cannot_block_pyright_cleanup(pyright): server._shutdown_timeout_seconds = 0.05 waiting_forever = asyncio.Event() transport.shutdown.side_effect = waiting_forever.wait - with pytest.raises(asyncio.TimeoutError): - async with server.start_server(): - assert server.server_started + async with server.start_server(): + assert server.server_started transport.shutdown.assert_awaited_once() transport.stop.assert_awaited_once() assert not server.server_started + + +@pytest.mark.asyncio +async def test_pyright_opt_in_workspace_edit_handler_is_explicit_and_bounded(pyright): + server, _, requests, _ = pyright + expected = {"edit": {"changes": {"file:///test.py": []}}, "label": "demo"} + callback = AsyncMock(return_value={"applied": True}) + with pytest.raises(TypeError, match="async function"): + server.set_workspace_edit_handler(42) + with pytest.raises(TypeError, match="async function"): + server.set_workspace_edit_handler(lambda _params: {"applied": True}) + with pytest.raises(ValueError, match="positive finite"): + server.set_workspace_edit_handler(callback, timeout_seconds=0) + with pytest.raises(ValueError, match="positive finite"): + server.set_workspace_edit_handler(callback, timeout_seconds=float("inf")) + server.set_workspace_edit_handler(callback) + assert server._get_initialize_params(server.repository_root_path)["capabilities"]["workspace"]["applyEdit"] is True + + async with server.start_server(): + configuration = await requests["workspace/configuration"]( + {"items": [{"section": "pyright"}]} + ) + assert configuration[0]["disableOrganizeImports"] is False + assert await requests["workspace/applyEdit"](expected) == {"applied": True} + callback.assert_awaited_once_with(expected) + with pytest.raises(MultilspyException, match="while running"): + server.set_workspace_edit_handler(None) + + # A caller can revert to safe/default behavior between sessions. + server.set_workspace_edit_handler(None) + assert server._get_initialize_params(server.repository_root_path)["capabilities"]["workspace"]["applyEdit"] is False + async with server.start_server(): + configuration = await requests["workspace/configuration"]( + {"items": [{"section": "pyright"}]} + ) + assert configuration[0]["disableOrganizeImports"] is True + assert await requests["workspace/applyEdit"](expected) == { + "applied": False, + "failureReason": "multilspy Pyright client is read-only", + } + callback.assert_awaited_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("bad_response", [None, {}, {"applied": "yes"}, []]) +async def test_pyright_invalid_workspace_edit_response_fails_closed(pyright, bad_response): + server, _, requests, _ = pyright + callback = AsyncMock(return_value=bad_response) + server.set_workspace_edit_handler(callback) + async with server.start_server(): + assert await requests["workspace/applyEdit"]({"edit": {"changes": {}}}) == { + "applied": False, + "failureReason": "Workspace edit handler failed", + } + callback.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_edit_handler_exception_fails_closed_without_leaking_paths(pyright): + server, transport, requests, _ = pyright + private_path = "/private/secret/fixture.py" + server.set_workspace_edit_handler(AsyncMock(side_effect=OSError(private_path))) + async with server.start_server(): + result = await requests["workspace/applyEdit"]({"edit": {"changes": {}}}) + assert result == {"applied": False, "failureReason": "Workspace edit handler failed"} + assert private_path not in repr(result) + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_workspace_edit_handler_times_out_and_stops(pyright): + server, transport, requests, _ = pyright + wait = asyncio.Event() + async def never_return(_params): + await wait.wait() + server.set_workspace_edit_handler(never_return, timeout_seconds=0.02) + async with server.start_server(): + assert await requests["workspace/applyEdit"]({"edit": {"changes": {}}}) == { + "applied": False, "failureReason": "Workspace edit handler timed out" + } + transport.stop.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_pyright_workspace_edit_response_is_normalized(pyright): + server, _, requests, _ = pyright + callback = AsyncMock(return_value={ + "applied": False, "failureReason": "Needs approval", "failedChange": 1, + "untrustedExtraField": "do not forward", + }) + server.set_workspace_edit_handler(callback) + async with server.start_server(): + assert await requests["workspace/applyEdit"]({"edit": {"documentChanges": []}}) == { + "applied": False, "failureReason": "Needs approval", "failedChange": 1 + } + callback.assert_awaited_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("bad", [ + {"applied": False, "failedChange": True}, + {"applied": False, "failedChange": -1}, + {"applied": False, "failureReason": 123}, +]) +async def test_pyright_workspace_edit_response_invalid_metadata_is_rejected(pyright, bad): + server, _, requests, _ = pyright + server.set_workspace_edit_handler(AsyncMock(return_value=bad)) + async with server.start_server(): + assert await requests["workspace/applyEdit"]({"edit": {"changes": {}}}) == { + "applied": False, "failureReason": "Workspace edit handler failed" + } From 9203732e4e5f65cc1374b109110f7b6354d3d43b Mon Sep 17 00:00:00 2001 From: Grammy Jiang Date: Thu, 22 Oct 2026 09:58:38 +1100 Subject: [PATCH 8/8] fix(lsp): release cancelled requests and serialize lifecycle IO Clear pending requests on cancellation, stop and EOF; ignore late, duplicate and malformed replies. Serialize concurrent stdin drains for Python 3.10/3.11, fence stale readers after restart, and reap finished dispatch tasks. Add concurrent, stalled-writer, late-response, malformed-JSON-RPC, interrupted-frame, process-crash and real Pyright restart regression tests across Mac and Linux. --- src/multilspy/lsp_protocol_handler/server.py | 174 ++++++--- tests/multilspy/test_lsp_request_lifecycle.py | 354 ++++++++++++++++++ .../test_pyright_process_lifecycle.py | 58 +++ 3 files changed, 542 insertions(+), 44 deletions(-) create mode 100644 tests/multilspy/test_lsp_request_lifecycle.py diff --git a/src/multilspy/lsp_protocol_handler/server.py b/src/multilspy/lsp_protocol_handler/server.py index 5c54ef8f..d07938c3 100644 --- a/src/multilspy/lsp_protocol_handler/server.py +++ b/src/multilspy/lsp_protocol_handler/server.py @@ -117,16 +117,23 @@ def __init__(self) -> None: self.cv = asyncio.Condition() self.result: Optional[PayloadLike] = None self.error: Optional[Error] = None + self.completed = False async def on_result(self, params: PayloadLike) -> None: - self.result = params async with self.cv: - self.cv.notify() + if self.completed: + return + self.result = params + self.completed = True + self.cv.notify_all() async def on_error(self, err: Error) -> None: - self.error = err async with self.cv: - self.cv.notify() + if self.completed: + return + self.error = err + self.completed = True + self.cv.notify_all() def content_length(line: bytes) -> Optional[int]: @@ -196,6 +203,8 @@ def __init__( self.process_launch_info = process_launch_info self.process = None self._received_shutdown = False + self._stopping = False + self._write_lock: Optional[asyncio.Lock] = None self.request_id = 1 self._response_handlers: Dict[Any, Request] = {} @@ -224,17 +233,22 @@ async def start(self) -> None: start_new_session=self.start_independent_lsp_process, ) + self._stopping = False + self._received_shutdown = False + # A SyncLanguageServer can restart this handler in a new event loop. + self._write_lock = asyncio.Lock() self.loop = asyncio.get_event_loop() - self.tasks[self.task_counter] = self.loop.create_task(self.run_forever()) - self.task_counter += 1 - self.tasks[self.task_counter] = self.loop.create_task(self.run_forever_stderr()) - self.task_counter += 1 + self._track_task(self.run_forever()) + self._track_task(self.run_forever_stderr()) async def stop(self) -> None: """ Sends the terminate signal to the language server process and waits for it to exit, with a timeout, killing it if necessary """ - # First cancel all tasks + # Stop admitting new requests and release callers waiting on the + # process, even when it exits without a shutdown response. + self._stopping = True + await self._fail_pending_requests("Language server process stopped") await self._cancel_pending_tasks() process = self.process @@ -246,6 +260,32 @@ async def stop(self) -> None: # Clean up the process await self._cleanup_process(process) + async def _fail_pending_requests(self, reason: str) -> None: + """Wake and forget every request whose response will never arrive.""" + pending = list(self._response_handlers.values()) + self._response_handlers.clear() + for request in pending: + await request.on_error(Error(ErrorCodes.InternalError, reason)) + + def _track_task(self, coroutine) -> None: + """Track only running reader/notification tasks, not completed ones.""" + identifier = self.task_counter + self.task_counter += 1 + task = asyncio.get_running_loop().create_task(coroutine) + self.tasks[identifier] = task + + def remove_completed(finished): + self.tasks.pop(identifier, None) + try: + finished.result() + except asyncio.CancelledError: + pass + except Exception as exc: + # Avoid retaining failed tasks or echoing untrusted wire data. + self._log(f"LSP background task failed: {type(exc).__name__}") + + task.add_done_callback(remove_completed) + async def _cancel_pending_tasks(self): """Cancel all pending tasks and wait for them to complete or timeout.""" pending_tasks = [] @@ -375,6 +415,9 @@ async def run_forever(self) -> bool: Continuously read from the language server process stdout and handle the messages invoking the registered response and notification handlers """ + # A delayed reader from an earlier lifespan must never abort pending + # requests belonging to a new process after restart. + reader_process = self.process try: while self.process and self.process.stdout and not self.process.stdout.at_eof(): line = await self.process.stdout.readline() @@ -392,10 +435,16 @@ async def run_forever(self) -> bool: continue body = await self.process.stdout.readexactly(num_bytes) - self.tasks[self.task_counter] = asyncio.get_event_loop().create_task(self._handle_body(body)) - self.task_counter += 1 - except (BrokenPipeError, ConnectionResetError, StopLoopException): + self._track_task(self._handle_body(body)) + except (BrokenPipeError, ConnectionResetError, StopLoopException, + asyncio.IncompleteReadError): pass + finally: + if self.process is reader_process and not self._received_shutdown: + # EOF/crash is as terminal as an explicit stop, but an old + # reader may not close a newly started session's requests. + self._stopping = True + await self._fail_pending_requests("Language server connection closed") return self._received_shutdown async def run_forever_stderr(self) -> None: @@ -450,37 +499,46 @@ def send_notification(self, method: str, params: Optional[dict] = None) -> None: self._send_payload_sync(make_notification(method, params)) def send_response(self, request_id: Any, params: PayloadLike) -> None: - """ - Send response to the given request id to the server with the given parameters - """ - self.tasks[self.task_counter] = asyncio.get_event_loop().create_task( - self._send_payload(make_response(request_id, params)) - ) - self.task_counter += 1 + """Send a response to a server-initiated request.""" + self._track_task(self._send_payload(make_response(request_id, params))) def send_error_response(self, request_id: Any, err: Error) -> None: - """ - Send error response to the given request id to the server with the given error - """ - self.tasks[self.task_counter] = asyncio.get_event_loop().create_task( - self._send_payload(make_error_response(request_id, err)) - ) - self.task_counter += 1 + """Send an error response to a server-initiated request.""" + self._track_task(self._send_payload(make_error_response(request_id, err))) async def send_request(self, method: str, params: Optional[dict] = None) -> None: """ Send request to the server, register the request id, and wait for the response """ + if self._stopping: + raise Error(ErrorCodes.InternalError, "Language server is stopped") request = Request() request_id = self.request_id self.request_id += 1 self._response_handlers[request_id] = request - async with request.cv: + try: + # Never hold the condition lock across stdin I/O: stop() must be + # able to wake abandoned requests even if pipe.drain() stalls. await self._send_payload(make_request(method, request_id, params)) - await request.cv.wait() - if isinstance(request.error, Error): - raise request.error - return request.result + async with request.cv: + await request.cv.wait_for(lambda: request.completed) + if isinstance(request.error, Error): + raise request.error + return request.result + except asyncio.CancelledError: + # Inform an active server that the request is no longer wanted; + # always preserve cancellation even if stdin is already closed. + if not self._stopping: + try: + self.notify.cancel_request({"id": request_id}) + except (OSError, RuntimeError, ValueError): + pass + raise + finally: + # A timed-out or cancelled request must never retain its response + # record. A late/duplicate reply will be discarded by the handler. + if self._response_handlers.get(request_id) is request: + self._response_handlers.pop(request_id, None) def _send_payload_sync(self, payload: StringDict) -> None: """ @@ -494,16 +552,21 @@ def _send_payload_sync(self, payload: StringDict) -> None: self.process.stdin.writelines(msg) async def _send_payload(self, payload: StringDict) -> None: - """ - Send the payload to the server by writing to its stdin asynchronously. - """ - if not self.process or not self.process.stdin: - return - msg = create_message(payload) - if self.logger: - self.logger("client", "server", payload) - self.process.stdin.writelines(msg) - await self.process.stdin.drain() + """Write a complete LSP frame, serializing concurrent drain calls.""" + lock = self._write_lock + if lock is None: + raise Error(ErrorCodes.InternalError, "Language server is not running") + async with lock: + if self._stopping: + raise Error(ErrorCodes.InternalError, "Language server is stopped") + process = self.process + if not process or not process.stdin: + raise Error(ErrorCodes.InternalError, "Language server is not running") + msg = create_message(payload) + if self.logger: + self.logger("client", "server", payload) + process.stdin.writelines(msg) + await process.stdin.drain() def on_request(self, method: str, cb) -> None: """ @@ -521,13 +584,36 @@ async def _response_handler(self, response: StringDict) -> None: """ Handle the response received from the server for a request, using the id to determine the request """ - request = self._response_handlers.pop(response["id"]) + request_id = response.get("id") + if type(request_id) not in (int, str): + self._log("Ignoring LSP response with unroutable id") + return + request = self._response_handlers.get(request_id) + if request is None or self._stopping: + # Timeout/cancellation and duplicate replies are legal races. + # Never fail another reader task for a completed request id. + self._log("Ignoring late or duplicate LSP response") + return if "result" in response and "error" not in response: await request.on_result(response["result"]) elif "result" not in response and "error" in response: - await request.on_error(Error.from_lsp(response["error"])) + try: + raw_error = response["error"] + if ( + not isinstance(raw_error, dict) + or not isinstance(raw_error.get("code"), int) + or isinstance(raw_error.get("code"), bool) + or not isinstance(raw_error.get("message"), str) + ): + raise ValueError("Invalid JSON-RPC error shape") + error = Error.from_lsp(raw_error) + except (KeyError, TypeError, ValueError): + # A malformed response still completes its waiting request; + # otherwise a corrupt peer could strand the caller forever. + error = Error(ErrorCodes.InvalidRequest, "Malformed LSP error response") + await request.on_error(error) else: - await request.on_error(Error(ErrorCodes.InvalidRequest, "")) + await request.on_error(Error(ErrorCodes.InvalidRequest, "Malformed LSP response")) async def _request_handler(self, response: StringDict) -> None: """ diff --git a/tests/multilspy/test_lsp_request_lifecycle.py b/tests/multilspy/test_lsp_request_lifecycle.py new file mode 100644 index 00000000..25218eff --- /dev/null +++ b/tests/multilspy/test_lsp_request_lifecycle.py @@ -0,0 +1,354 @@ +"""JSON-RPC pending request lifecycle across all language server adapters. + +This is shared multilspy behavior, not Pyright-specific. No external LSP +binary or network required for the unit cases; real subprocess EOF is tested. +""" + +import asyncio +import sys +from unittest.mock import AsyncMock, Mock + +import pytest + +from multilspy.lsp_protocol_handler.lsp_types import ErrorCodes +from multilspy.lsp_protocol_handler.server import Error, LanguageServerHandler, ProcessLaunchInfo + + +@pytest.fixture +def handler(tmp_path): + client = LanguageServerHandler(ProcessLaunchInfo(cmd=[sys.executable], cwd=str(tmp_path))) + client._send_payload = AsyncMock() + client._send_payload_sync = Mock() + return client + + +async def wait_for_pending(handler, n): + async def wait_for_count(): + while len(handler._response_handlers) != n: + await asyncio.sleep(0) + return list(handler._response_handlers) + + return await asyncio.wait_for(wait_for_count(), 2) + + +@pytest.mark.asyncio +async def test_response_race_before_wait_starts(handler): + async def fast_peer(payload): + # A response may be scheduled while request bytes are still draining. + asyncio.create_task(handler._response_handler({"id": payload["id"], "result": "ready"})) + await asyncio.sleep(0) + + handler._send_payload.side_effect = fast_peer + assert await asyncio.wait_for(handler.send_request("example", {"x": 1}), 2) == "ready" + assert handler._response_handlers == {} + + +@pytest.mark.asyncio +async def test_null_result_unblocks_waiter(handler): + task = asyncio.create_task(handler.send_request("textDocument/references", {})) + (identifier,) = await wait_for_pending(handler, 1) + await handler._response_handler({"id": identifier, "result": None}) + assert await asyncio.wait_for(task, 2) is None + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_lsp_error_unblocks_waiter_and_cleans_map(handler): + task = asyncio.create_task(handler.send_request("bad", {})) + (identifier,) = await wait_for_pending(handler, 1) + await handler._response_handler({"id": identifier, "error": { + "code": ErrorCodes.MethodNotFound, "message": "not here" + }}) + with pytest.raises(Error) as exc: + await asyncio.wait_for(task, 2) + assert exc.value.code == ErrorCodes.MethodNotFound + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_transport_send_exception_cleans_map(handler): + handler._send_payload.side_effect = OSError("pipe unavailable") + with pytest.raises(OSError, match="pipe unavailable"): + await handler.send_request("x", {}) + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_cancellation_cleans_map_and_sends_cancel_request(handler): + task = asyncio.create_task(handler.send_request("long", {})) + (identifier,) = await wait_for_pending(handler, 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert handler._response_handlers == {} + handler._send_payload_sync.assert_called_once() + payload = handler._send_payload_sync.call_args.args[0] + assert payload == { + "jsonrpc": "2.0", "method": "$/cancelRequest", "params": {"id": identifier} + } + await handler._response_handler({"id": identifier, "result": "late"}) + await handler._response_handler({"id": identifier, "result": "duplicate"}) + assert handler._response_handlers == {} + + +@pytest.mark.asyncio +async def test_concurrent_requests_resolve_out_of_order_without_leak(handler): + tasks = [asyncio.create_task(handler.send_request("request", {"ordinal": i})) for i in range(20)] + identifiers = await wait_for_pending(handler, 20) + assert len(set(identifiers)) == len(tasks) + for identifier in reversed(identifiers): + await handler._response_handler({"id": identifier, "result": identifier}) + assert await asyncio.wait_for(asyncio.gather(*tasks), 3) == identifiers + for identifier in identifiers: + await handler._response_handler({"id": identifier, "result": "duplicate"}) + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_stop_wakes_all_waiters_and_rejects_new_requests(handler): + tasks = [asyncio.create_task(handler.send_request("stalled", {})) for _ in range(10)] + old_ids = await wait_for_pending(handler, len(tasks)) + await asyncio.wait_for(handler.stop(), 3) + results = await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), 3) + assert len(results) == len(tasks) + assert all(isinstance(item, Error) and "stopped" in str(item) for item in results) + assert not handler._response_handlers + for identifier in old_ids: + await handler._response_handler({"id": identifier, "result": "late"}) + with pytest.raises(Error, match="stopped"): + await asyncio.wait_for(handler.send_request("new", {}), 1) + + +@pytest.mark.asyncio +async def test_stop_does_not_wait_for_stalled_stdin_drain(handler): + sending = asyncio.Event() + still_draining = asyncio.Event() + + async def blocked_send(_payload): + sending.set() + await still_draining.wait() + + handler._send_payload.side_effect = blocked_send + task = asyncio.create_task(handler.send_request("blocked", {})) + await asyncio.wait_for(sending.wait(), 2) + assert len(handler._response_handlers) == 1 + await asyncio.wait_for(handler.stop(), 1) + assert not handler._response_handlers + still_draining.set() + with pytest.raises(Error, match="stopped"): + await asyncio.wait_for(task, 2) + + +@pytest.mark.asyncio +async def test_restarted_session_never_reuses_old_request_id(handler): + task = asyncio.create_task(handler.send_request("old", {})) + (old_id,) = await wait_for_pending(handler, 1) + await handler.stop() + with pytest.raises(Error): + await task + # start() resets stopped state when a new child is successfully spawned; + # simulate only that lifecycle transition without launching a provider. + handler._stopping = False + next_request = asyncio.create_task(handler.send_request("new", {})) + (next_id,) = await wait_for_pending(handler, 1) + assert old_id != next_id + await handler._response_handler({"id": old_id, "result": "obsolete"}) + assert not next_request.done() + await handler._response_handler({"id": next_id, "result": "fresh"}) + assert await asyncio.wait_for(next_request, 2) == "fresh" + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_server_crash_and_eof_wake_outstanding_request(tmp_path): + script = tmp_path / "exit_on_input.py" + script.write_text("import sys\nsys.stdin.buffer.read(1)\n", encoding="utf-8") + handler = LanguageServerHandler(ProcessLaunchInfo(cmd=[sys.executable, "-u", str(script)], cwd=str(tmp_path))) + await handler.start() + try: + with pytest.raises(Error, match="connection closed"): + await asyncio.wait_for(handler.send_request("never-answered", {}), 5) + assert not handler._response_handlers + with pytest.raises(Error, match="stopped"): + await handler.send_request("after-eof", {}) + finally: + await handler.stop() + assert handler.process is None + assert handler.tasks == {} + + +@pytest.mark.asyncio +async def test_duplicate_response_before_waiter_finishes_is_ignored(handler): + task = asyncio.create_task(handler.send_request("repeat", {})) + (identifier,) = await wait_for_pending(handler, 1) + await handler._response_handler({"id": identifier, "result": "first"}) + await handler._response_handler({"id": identifier, "result": "second"}) + assert await asyncio.wait_for(task, 2) == "first" + assert handler._response_handlers == {} + + +@pytest.mark.asyncio +async def test_repeated_cancels_never_accumulate_pending_requests(handler): + for _ in range(100): + task = asyncio.create_task(handler.send_request("repeated", {})) + (identifier,) = await wait_for_pending(handler, 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await handler._response_handler({"id": identifier, "result": "obsolete"}) + assert not handler._response_handlers + assert handler.request_id == 101 + assert handler._send_payload_sync.call_count == 100 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("response", [ + {"error": None}, + {"error": {}}, + {"error": {"code": "wrong"}}, + {"error": {"code": "wrong", "message": "not an integer"}}, + {"error": {"code": True, "message": "boolean is not an error code"}}, + {"error": {"code": -32601, "message": 99}}, + {"result": 1, "error": {"code": -32000, "message": "bad"}}, +]) +async def test_malformed_reply_unblocks_and_fails_request(handler, response): + task = asyncio.create_task(handler.send_request("malformed", {})) + (identifier,) = await wait_for_pending(handler, 1) + await handler._response_handler({"id": identifier, **response}) + with pytest.raises(Error) as exc: + await asyncio.wait_for(task, 2) + assert exc.value.code == ErrorCodes.InvalidRequest + assert handler._response_handlers == {} + + +@pytest.mark.asyncio +async def test_partial_response_frame_then_eof_wakes_request(tmp_path): + script = tmp_path / "truncated_frame.py" + script.write_text( + "import sys\n" + "sys.stdin.buffer.read(1)\n" + "sys.stdout.buffer.write(b'Content-Length: 20\\r\\n\\r\\nshort')\n" + "sys.stdout.buffer.flush()\n", + encoding="utf-8", + ) + handler = LanguageServerHandler( + ProcessLaunchInfo(cmd=[sys.executable, "-u", str(script)], cwd=str(tmp_path)) + ) + await handler.start() + try: + with pytest.raises(Error, match="connection closed"): + await asyncio.wait_for(handler.send_request("partial", {}), 5) + assert handler._response_handlers == {} + finally: + await handler.stop() + assert handler.process is None + assert handler.tasks == {} + + +@pytest.mark.asyncio +async def test_concurrent_stdin_drain_is_serialized_even_on_stop(handler): + """Python 3.10/3.11 StreamWriter supports only one pending drain waiter.""" + from types import SimpleNamespace + + first_drain = asyncio.Event() + release = asyncio.Event() + + class Writer: + drain_calls = 0 + + def writelines(self, _segments): + pass + + async def drain(self): + self.drain_calls += 1 + if self.drain_calls == 1: + first_drain.set() + await release.wait() + + writer = Writer() + handler.process = SimpleNamespace(stdin=writer) + handler._write_lock = asyncio.Lock() + handler._cleanup_process = AsyncMock() + # Restore the real method; the basic fixture uses a mocked sender. + handler._send_payload = LanguageServerHandler._send_payload.__get__(handler) + tasks = [asyncio.create_task(handler.send_request("stress", {})) for _ in range(2)] + await asyncio.wait_for(first_drain.wait(), 2) + await asyncio.sleep(0) + assert writer.drain_calls == 1 + await asyncio.wait_for(handler.stop(), 2) + release.set() + outcomes = await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), 2) + assert all(isinstance(item, Error) for item in outcomes) + assert not handler._response_handlers + assert writer.drain_calls == 1 # queued write is never sent after stop + + +@pytest.mark.asyncio +async def test_old_reader_cannot_fail_requests_in_new_process(handler): + from types import SimpleNamespace + from multilspy.lsp_protocol_handler.server import Request + + entered = asyncio.Event() + hold = asyncio.Event() + + class Reader: + def at_eof(self): + return False + + async def readline(self): + entered.set() + await hold.wait() + return b"" + + old_process = SimpleNamespace(stdout=Reader()) + handler.process = old_process + old_reader = asyncio.create_task(handler.run_forever()) + await asyncio.wait_for(entered.wait(), 2) + handler.process = SimpleNamespace(stdout=None) + pending = Request() + handler._response_handlers[42] = pending + old_reader.cancel() + with pytest.raises(asyncio.CancelledError): + await old_reader + assert not handler._stopping + assert handler._response_handlers[42] is pending + await pending.on_error(Error(ErrorCodes.InternalError, "test done")) + handler._response_handlers.clear() + + +@pytest.mark.asyncio +async def test_background_task_tracking_reaps_completed_tasks(handler): + for _ in range(300): + handler._track_task(asyncio.sleep(0)) + # The loop schedules task completion callbacks one turn after the tasks + # themselves finish; wait for the bound rather than assuming tick count. + async def drained(): + while handler.tasks: + await asyncio.sleep(0) + + await asyncio.wait_for(drained(), 2) + assert handler.tasks == {} + + +@pytest.mark.asyncio +async def test_request_before_server_start_fails_instead_of_hanging(tmp_path): + handler = LanguageServerHandler(ProcessLaunchInfo(cmd=[sys.executable], cwd=str(tmp_path))) + with pytest.raises(Error, match="not running"): + await asyncio.wait_for(handler.send_request("premature", {}), 1) + assert not handler._response_handlers + + +@pytest.mark.asyncio +async def test_unroutable_and_duplicate_responses_leave_a_generic_log(tmp_path): + callback = Mock() + handler = LanguageServerHandler( + ProcessLaunchInfo(cmd=[sys.executable], cwd=str(tmp_path)), logger=callback + ) + await handler._response_handler({"id": None, "error": {"code": -32700, "message": "bad"}}) + await handler._response_handler({"id": 70000, "result": "late"}) + assert not handler._response_handlers + assert callback.call_count == 2 + logs = [call.args[2] for call in callback.call_args_list] + assert "unroutable" in logs[0] + assert "duplicate" in logs[1] + assert "70000" not in logs[1] # no echo of untrusted response content diff --git a/tests/multilspy/test_pyright_process_lifecycle.py b/tests/multilspy/test_pyright_process_lifecycle.py index 810a0dae..d4950fee 100644 --- a/tests/multilspy/test_pyright_process_lifecycle.py +++ b/tests/multilspy/test_pyright_process_lifecycle.py @@ -5,6 +5,7 @@ """ import asyncio +import os import sys import pytest @@ -72,6 +73,7 @@ async def exercise(): assert created[0].returncode is not None assert handler.process is None assert handler.tasks == {} + assert not handler._response_handlers assert not server.server_started finally: for process in created: @@ -100,6 +102,7 @@ async def exercise(): assert created[0].returncode is not None assert handler.process is None assert handler.tasks == {} + assert not handler._response_handlers assert not server.server_started finally: if not pending.done(): @@ -109,3 +112,58 @@ async def exercise(): if process.returncode is None: process.kill() await process.wait() + + +@pytest.mark.asyncio +async def test_real_pyright_restarts_after_abandoned_request(tmp_path): + binary = os.environ.get("MULTILSPY_PYRIGHT_TEST_BINARY") + if not binary: + pytest.skip("Real pinned Pyright is not configured") + + (tmp_path / "sample.py").write_text( + "value = 42\nresult = value\n", encoding="utf-8" + ) + server = LanguageServer.create( + MultilspyConfig( + code_language=Language.PYTHON, + python_server="pyright", server_binary=binary, + ), + MultilspyLogger(), str(tmp_path.resolve()), + ) + seen_ids = [] + for _ in range(2): + async with server.start_server(): + handler = server.server + original_send = handler._send_payload + + async def unanswered(payload): + # Pyright may concurrently send workspace/configuration + # requests. Their client responses must keep flowing; only + # silence this *one* outgoing definition request. + if payload.get("method") == "textDocument/definition": + return None + return await original_send(payload) + + handler._send_payload = unanswered + try: + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for( + handler.send_request("textDocument/definition", {}), 0.05 + ) + finally: + handler._send_payload = original_send + assert handler._response_handlers == {} + seen_ids.append(handler.request_id - 1) + with server.open_file("sample.py"): + definition = await asyncio.wait_for( + server.request_definition("sample.py", 1, 10), 8 + ) + assert len(definition) == 1 + assert definition[0]["relativePath"] == "sample.py" + assert definition[0]["range"]["start"] == { + "line": 0, "character": 0, + } + assert handler._response_handlers == {} + assert handler.process is None + assert handler.tasks == {} + assert seen_ids[1] > seen_ids[0]