Skip to content

Commit e093613

Browse files
committed
feat(client): accept an argv sequence for the worker command
Splitting the command string is ambiguous on Windows: shlex.split needs posix=False there so backslashes in paths survive, and that leaves quotes attached to the token -- so `python -c "import sys; ..."` reaches the interpreter mangled. No single quoting convention works on both platforms, which is why the shell was papering over this before. Let server_path be a sequence and take it as argv verbatim, so an argument carrying spaces or quotes can be expressed exactly. The four worker-debug tests that embedded a quoted -c body now do that. One _worker_argv() on the mixin replaces the three copies of the shlex.split line.
1 parent 6b4fabc commit e093613

3 files changed

Lines changed: 42 additions & 25 deletions

File tree

‎tests/client/test_worker_debug.py‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from __future__ import annotations
66

77
import os
8+
import sys
89
from unittest.mock import patch
910

1011
import pyarrow as pa
@@ -14,6 +15,16 @@
1415
from vgi.client.client import Client, ClientError
1516

1617

18+
def _stderr_worker(*lines: str) -> list[str]:
19+
"""Argv for a worker that writes ``lines`` to stderr and exits non-zero.
20+
21+
An argv list rather than a command string: the ``-c`` body carries spaces and
22+
quotes, which no single quoting convention survives on both POSIX and Windows.
23+
"""
24+
body = "import sys; " + "".join(f"sys.stderr.write({line!r} + chr(10)); " for line in lines)
25+
return [sys.executable, "-c", body + "sys.stderr.flush(); sys.exit(1)"]
26+
27+
1728
class TestWorkerDebugEnvVar:
1829
"""Tests for VGI_WORKER_DEBUG environment variable behavior."""
1930

@@ -53,14 +64,7 @@ class TestStderrInErrorMessages:
5364

5465
def test_error_includes_stderr_on_worker_failure(self) -> None:
5566
"""Error messages should include stderr when worker fails (non-pooled)."""
56-
worker_script = (
57-
'python -c "'
58-
"import sys; "
59-
"sys.stderr.write('Debug: bind starting\\n'); "
60-
"sys.stderr.write('Error: function not found\\n'); "
61-
"sys.stderr.flush(); "
62-
'sys.exit(1)"'
63-
)
67+
worker_script = _stderr_worker("Debug: bind starting", "Error: function not found")
6468

6569
client = Client(worker_script, pool=None)
6670
with pytest.raises(ClientError) as exc_info:
@@ -80,7 +84,7 @@ def test_error_includes_stderr_on_worker_failure(self) -> None:
8084

8185
def test_error_no_stderr_section_when_passthrough(self) -> None:
8286
"""Error messages should NOT include 'Worker stderr:' when passthrough is enabled."""
83-
worker_script = "python -c \"import sys; sys.stderr.write('Debug info\\n'); sys.stderr.flush(); sys.exit(1)\""
87+
worker_script = _stderr_worker("Debug info")
8488

8589
client = Client(worker_script, passthrough_stderr=True, pool=None)
8690
with pytest.raises(ClientError) as exc_info:
@@ -99,9 +103,7 @@ def test_error_no_stderr_section_when_passthrough(self) -> None:
99103

100104
def test_stderr_enrichment_on_table_in_out_function(self) -> None:
101105
"""table_in_out_function errors should include stderr."""
102-
worker_script = (
103-
"python -c \"import sys; sys.stderr.write('worker log line\\n'); sys.stderr.flush(); sys.exit(1)\""
104-
)
106+
worker_script = _stderr_worker("worker log line")
105107

106108
batch = pa.RecordBatch.from_pydict({"x": [1, 2, 3]})
107109
client = Client(worker_script, pool=None)
@@ -120,7 +122,7 @@ def test_stderr_enrichment_on_table_in_out_function(self) -> None:
120122

121123
def test_stderr_enrichment_on_scalar_function(self) -> None:
122124
"""scalar_function errors should include stderr."""
123-
worker_script = "python -c \"import sys; sys.stderr.write('scalar debug\\n'); sys.stderr.flush(); sys.exit(1)\""
125+
worker_script = _stderr_worker("scalar debug")
124126

125127
batch = pa.RecordBatch.from_pydict({"x": [1, 2, 3]})
126128
client = Client(worker_script, pool=None)

‎vgi/client/catalog_mixin.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,17 +102,30 @@ class CatalogClientMixin:
102102
factory).
103103
104104
Attributes:
105-
server_path: Worker shell command used for subprocess transport.
105+
server_path: Worker command used for subprocess transport — a string to
106+
be split, or an argv sequence taken as-is.
106107
"""
107108

108109
# Type hints for attributes expected from Client
109-
server_path: str
110+
server_path: str | Sequence[str]
110111
_transport: Literal["subprocess", "http", "tcp"]
111112
_base_url: str | None
112113
_tcp_host: str | None
113114
_tcp_port: int | None
114115
_external_location: Any | None
115116

117+
def _worker_argv(self) -> list[str]:
118+
"""The worker command as an argv list, however ``server_path`` was given.
119+
120+
A sequence is taken verbatim; a string is split. ``posix=False`` on Windows
121+
keeps backslashes in paths from being read as escapes — at the cost of
122+
leaving quotes attached to the token, which is why an argument carrying
123+
spaces or quotes should be passed as a sequence element instead.
124+
"""
125+
if isinstance(self.server_path, str):
126+
return shlex.split(self.server_path, posix=sys.platform != "win32")
127+
return list(self.server_path)
128+
116129
def _get_or_create_httpx_client(self) -> Any: # implemented by Client
117130
raise NotImplementedError
118131

@@ -158,7 +171,7 @@ def _catalog_connect(self) -> Iterator[VgiProtocol]:
158171
) as proxy:
159172
yield proxy
160173
else:
161-
cmd = shlex.split(self.server_path, posix=sys.platform != "win32")
174+
cmd = self._worker_argv()
162175
with _catalog_pool.connect(VgiProtocol, cmd) as proxy: # type: ignore[type-abstract]
163176
yield proxy
164177
except RpcError as e:

‎vgi/client/client.py‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,9 @@
7171
import itertools
7272
import logging
7373
import os
74-
import shlex
7574
import subprocess
76-
import sys
7775
import threading
78-
from collections.abc import Callable, Generator, Iterator
76+
from collections.abc import Callable, Generator, Iterator, Sequence
7977
from contextlib import AbstractContextManager
8078
from dataclasses import dataclass, field
8179
from queue import Queue
@@ -378,7 +376,7 @@ def _deserialize_pushdown_filters(filters_bytes: bytes | None) -> pa.RecordBatch
378376

379377
def __init__(
380378
self,
381-
server_path: str | None = None,
379+
server_path: str | Sequence[str] | None = None,
382380
passthrough_stderr: bool = False,
383381
worker_limit: int | None = None,
384382
attach_opaque_data: bytes | None = None,
@@ -405,8 +403,12 @@ def __init__(
405403
other-language clients mirror.
406404
407405
Args:
408-
server_path: Subprocess-only. Shell command or path to the VGI
409-
worker executable. Executed via shell=True.
406+
server_path: Subprocess-only. The VGI worker command. A string is
407+
split with ``shlex.split``; pass a sequence to give
408+
the argv exactly, which is what you want for arguments carrying
409+
spaces or quotes (``[sys.executable, "-c", script]``). No shell
410+
is involved either way, so shell syntax — pipes, redirection,
411+
``VAR=value`` prefixes, ``~`` expansion — is not interpreted.
410412
passthrough_stderr: Subprocess-only. If True, worker stderr is
411413
passed through to the parent process's stderr in real-time.
412414
worker_limit: Maximum number of parallel worker processes.
@@ -466,7 +468,7 @@ def __init__(
466468
else:
467469
raise ValueError(f"unknown transport {transport!r}")
468470

469-
self.server_path = server_path or ""
471+
self.server_path: str | Sequence[str] = server_path if server_path is not None else ""
470472
self._transport = transport
471473
self._base_url = base_url
472474
self._tcp_host = tcp_host
@@ -723,7 +725,7 @@ def _spawn_subprocess_connection(self, worker_index: int) -> WorkerConnection:
723725
"""
724726
if self._pool is not None:
725727
_logger.debug("borrowing_worker worker_index=%s", worker_index)
726-
cmd = shlex.split(self.server_path, posix=sys.platform != "win32")
728+
cmd = self._worker_argv()
727729
ctx = self._pool.connect(
728730
VgiProtocol, # type: ignore[type-abstract]
729731
cmd,
@@ -745,7 +747,7 @@ def _spawn_subprocess_connection(self, worker_index: int) -> WorkerConnection:
745747
# on every platform, and matches how the pooled and catalog paths have
746748
# always spawned it.
747749
proc = subprocess.Popen(
748-
shlex.split(self.server_path, posix=sys.platform != "win32"),
750+
self._worker_argv(),
749751
stdin=subprocess.PIPE,
750752
stdout=subprocess.PIPE,
751753
stderr=None if self.passthrough_stderr else subprocess.PIPE,

0 commit comments

Comments
 (0)