Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion sqlmesh/lsp/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
45 changes: 45 additions & 0 deletions tests/lsp/test_stdio.py
Original file line number Diff line number Diff line change
@@ -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]