diff --git a/sqlmesh/lsp/main.py b/sqlmesh/lsp/main.py index b5623f3ff8..1ed40f52e2 100755 --- a/sqlmesh/lsp/main.py +++ b/sqlmesh/lsp/main.py @@ -3,6 +3,8 @@ from itertools import chain import logging +import os +import sys import typing as t from pathlib import Path import urllib.parse @@ -1184,7 +1186,14 @@ def _uri_to_path(uri: str) -> Path: def start(self) -> None: """Start the server with I/O transport.""" logging.basicConfig(level=logging.DEBUG) - self.server.start_io() + stdin, stdout = sys.stdin.buffer, sys.stdout.buffer + if sys.stderr is not None: + # Keep the JSON-RPC stream on a private copy of the real stdout and point fd 1 + # at stderr, so print(), subprocesses and C-level writes can't corrupt it. + stdout = os.fdopen(os.dup(sys.stdout.fileno()), "wb") + os.dup2(sys.stderr.fileno(), sys.stdout.fileno()) + sys.stdout.flush() # pending pre-start output now drains to stderr + self.server.start_io(stdin, stdout) # type: ignore[arg-type] def loaded_sqlmesh_message(ls: LanguageServer) -> None: diff --git a/tests/lsp/test_stdio.py b/tests/lsp/test_stdio.py new file mode 100644 index 0000000000..65898e64e5 --- /dev/null +++ b/tests/lsp/test_stdio.py @@ -0,0 +1,45 @@ +# SPDX-License-Identifier: Apache-2.0 + +import json +import subprocess +import sys + +import pytest + +pytestmark = pytest.mark.slow + + +@pytest.mark.parametrize( + "prelude, marker", + [ + ('print("hello from config", flush=True)', b"hello from config"), + ('import os; os.system("echo hello from subprocess")', b"hello from subprocess"), + ], + ids=["print", "subprocess"], +) +def test_project_stdout_does_not_corrupt_rpc_stream( + copy_to_temp_path, prelude: str, marker: bytes +) -> None: + project = copy_to_temp_path("examples/sushi")[0] + config = project / "config.py" + config.write_text(prelude + "\n" + config.read_text()) + + workspace = [{"uri": project.as_uri(), "name": "sushi"}] + params = {"processId": None, "rootUri": None, "capabilities": {}, "workspaceFolders": workspace} + body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": params}) + + # The server handles initialize, then exits when stdin closes. + result = subprocess.run( + [sys.executable, "-m", "sqlmesh.lsp.main"], + input=f"Content-Length: {len(body)}\r\n\r\n{body}".encode(), + capture_output=True, + timeout=60, + ) + + assert result.stdout.startswith(b"Content-Length:"), ( + result.stdout[:200], + result.stderr[-2000:], + ) + # The prelude must have run, and its output must reach stderr only. + assert marker in result.stderr, result.stderr[-2000:] + assert marker not in result.stdout, result.stdout[:2000]