sparkless-connect 4.19.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ """Lightweight client and owned-server lifecycle helpers for Sparkless."""
2
+
3
+ from .server import (
4
+ AsyncSparklessServer,
5
+ SparklessConnect,
6
+ SparklessServer,
7
+ SparklessServerError,
8
+ UnsupportedServerPlatformError,
9
+ UnsupportedSparkConnectError,
10
+ )
11
+
12
+ __all__ = [
13
+ "AsyncSparklessServer",
14
+ "SparklessConnect",
15
+ "SparklessServer",
16
+ "SparklessServerError",
17
+ "UnsupportedServerPlatformError",
18
+ "UnsupportedSparkConnectError",
19
+ ]
@@ -0,0 +1,310 @@
1
+ """Asynchronous owned-process launcher."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._common import (
6
+ Any,
7
+ Dict,
8
+ MAX_CONTROL_FRAME_BYTES,
9
+ Optional,
10
+ SparklessServerError,
11
+ UnsupportedSparkConnectError,
12
+ _ByteTail,
13
+ _await_cleanup,
14
+ _binary_lacks_spark_connect,
15
+ _command_with_connect,
16
+ _parse_record,
17
+ _product_package,
18
+ _resolve_executable,
19
+ _validate_ready,
20
+ _validate_timeouts,
21
+ asyncio,
22
+ os,
23
+ )
24
+
25
+
26
+ class AsyncSparklessServer:
27
+ """An asyncio owner for one ``sparkless-server`` child process."""
28
+
29
+ def __init__(
30
+ self,
31
+ host: str = "127.0.0.1",
32
+ port: int = 0,
33
+ executable_path: Optional[str] = None,
34
+ startup_timeout: float = 30.0,
35
+ shutdown_timeout: float = 10.0,
36
+ kill_timeout: float = 5.0,
37
+ env: Optional[Dict[str, str]] = None,
38
+ connect_host: str = "127.0.0.1",
39
+ connect_port: Optional[int] = 0,
40
+ product: str = "base",
41
+ ) -> None:
42
+ self.host = host
43
+ self.port = port
44
+ self._executable_path = executable_path
45
+ self.startup_timeout = startup_timeout
46
+ self.shutdown_timeout = shutdown_timeout
47
+ self.kill_timeout = kill_timeout
48
+ _validate_timeouts(startup_timeout, shutdown_timeout, kill_timeout)
49
+ self.env = None if env is None else dict(env)
50
+ self.connect_host = connect_host
51
+ self.connect_port = connect_port
52
+ _product_package(product)
53
+ self.product = product
54
+ self._process: Optional[asyncio.subprocess.Process] = None
55
+ self._records: Optional["asyncio.Queue[Any]"] = None
56
+ self._stderr_tail = _ByteTail()
57
+ self._stdout_task: Optional["asyncio.Task[None]"] = None
58
+ self._stderr_task: Optional["asyncio.Task[None]"] = None
59
+ self._owner_pid = os.getpid()
60
+ self._http_url: Optional[str] = None
61
+ self._connect_url: Optional[str] = None
62
+ self._instance_id: Optional[str] = None
63
+ self._ready_record: Optional[Dict[str, Any]] = None
64
+ self._entered = False
65
+
66
+ def _check_owner(self) -> None:
67
+ if os.getpid() != self._owner_pid:
68
+ raise SparklessServerError(
69
+ "server process ownership changed after fork; create a new launcher in the child"
70
+ )
71
+
72
+ @property
73
+ def is_running(self) -> bool:
74
+ self._check_owner()
75
+ return self._process is not None and self._process.returncode is None
76
+
77
+ @property
78
+ def http_url(self) -> str:
79
+ self._check_owner()
80
+ if not self.is_running or self._http_url is None:
81
+ raise SparklessServerError(
82
+ "HTTP endpoint is available only while the server is ready"
83
+ )
84
+ return self._http_url
85
+
86
+ @property
87
+ def server_instance_id(self) -> str:
88
+ self._check_owner()
89
+ if not self.is_running or self._instance_id is None:
90
+ raise SparklessServerError(
91
+ "server identity is available only while the server is ready"
92
+ )
93
+ return self._instance_id
94
+
95
+ @property
96
+ def spark_connect_url(self) -> str:
97
+ self._check_owner()
98
+ if not self.is_running:
99
+ raise SparklessServerError(
100
+ "Spark Connect endpoint is available only while the server is ready"
101
+ )
102
+ if self.connect_port is None or self._connect_url is None:
103
+ raise UnsupportedSparkConnectError(
104
+ "Spark Connect is disabled or unavailable in this server binary"
105
+ )
106
+ return self._connect_url
107
+
108
+ @property
109
+ def diagnostics(self) -> str:
110
+ return self._stderr_tail.text()
111
+
112
+ async def _read_stdout(self) -> None:
113
+ process = self._process
114
+ assert (
115
+ process is not None
116
+ and process.stdout is not None
117
+ and self._records is not None
118
+ )
119
+ while True:
120
+ try:
121
+ frame = await process.stdout.readline()
122
+ except (asyncio.LimitOverrunError, ValueError) as error:
123
+ await self._records.put(error)
124
+ return
125
+ if not frame:
126
+ await self._records.put(None)
127
+ return
128
+ if len(frame) > MAX_CONTROL_FRAME_BYTES or not frame.endswith(b"\n"):
129
+ await self._records.put(
130
+ SparklessServerError("server emitted an oversized control frame")
131
+ )
132
+ return
133
+ await self._records.put(frame.rstrip(b"\r\n"))
134
+
135
+ async def _read_stderr(self) -> None:
136
+ process = self._process
137
+ assert process is not None and process.stderr is not None
138
+ while True:
139
+ chunk = await process.stderr.read(4096)
140
+ if not chunk:
141
+ return
142
+ self._stderr_tail.append(chunk)
143
+
144
+ async def start(self) -> "AsyncSparklessServer":
145
+ self._check_owner()
146
+ if self.is_running and self._http_url is not None:
147
+ return self
148
+ if self._process is not None:
149
+ await self._stop_impl(force=False)
150
+ executable = _resolve_executable(self._executable_path, self.product)
151
+ command = _command_with_connect(
152
+ executable, self.host, self.port, self.connect_host, self.connect_port
153
+ )
154
+ spawn_task = asyncio.create_task(
155
+ asyncio.create_subprocess_exec(
156
+ *command,
157
+ stdin=asyncio.subprocess.PIPE,
158
+ stdout=asyncio.subprocess.PIPE,
159
+ stderr=asyncio.subprocess.PIPE,
160
+ env=self._child_env(),
161
+ limit=MAX_CONTROL_FRAME_BYTES + 1,
162
+ )
163
+ )
164
+ try:
165
+ self._process = await asyncio.shield(spawn_task)
166
+ except asyncio.CancelledError:
167
+ try:
168
+ self._process = await asyncio.shield(spawn_task)
169
+ except BaseException:
170
+ raise
171
+ cleanup = asyncio.create_task(self._stop_impl(force=True))
172
+ await _await_cleanup(cleanup)
173
+ raise
174
+ self._records = asyncio.Queue(maxsize=4)
175
+ self._stderr_tail = _ByteTail()
176
+ self._stdout_task = asyncio.create_task(self._read_stdout())
177
+ self._stderr_task = asyncio.create_task(self._read_stderr())
178
+ try:
179
+ frame = await asyncio.wait_for(self._records.get(), self.startup_timeout)
180
+ if frame is None:
181
+ raise SparklessServerError("server exited before readiness")
182
+ if isinstance(frame, BaseException):
183
+ raise frame
184
+ record = _parse_record(frame)
185
+ url, connect_url = _validate_ready(
186
+ record,
187
+ require_spark_connect=self.connect_port is not None,
188
+ expected_product=self.product,
189
+ )
190
+ except BaseException as error:
191
+ failed_start_cleanup = asyncio.create_task(self._cleanup_failed_start())
192
+ connect_unavailable = await _await_cleanup(failed_start_cleanup)
193
+ if connect_unavailable and isinstance(error, Exception):
194
+ raise UnsupportedSparkConnectError(
195
+ "server binary does not provide Spark Connect"
196
+ ) from error
197
+ raise
198
+ self._ready_record = record
199
+ self._http_url = url
200
+ self._connect_url = connect_url
201
+ self._instance_id = record["server_instance_id"]
202
+ return self
203
+
204
+ def _child_env(self) -> Optional[Dict[str, str]]:
205
+ if self.env is None:
206
+ return None
207
+ child_env = os.environ.copy()
208
+ child_env.update(self.env)
209
+ return child_env
210
+
211
+ async def _binary_lacks_spark_connect(self) -> bool:
212
+ if self.connect_port is None or self._process is None:
213
+ return False
214
+ process = self._process
215
+ if process.returncode is None:
216
+ try:
217
+ await asyncio.wait_for(process.wait(), 0.25)
218
+ except asyncio.TimeoutError:
219
+ return False
220
+ if self._stderr_task is not None and not self._stderr_task.done():
221
+ try:
222
+ await asyncio.wait_for(asyncio.shield(self._stderr_task), 0.5)
223
+ except asyncio.TimeoutError:
224
+ pass
225
+ return _binary_lacks_spark_connect(self.diagnostics)
226
+
227
+ async def _cleanup_failed_start(self) -> bool:
228
+ try:
229
+ return await self._binary_lacks_spark_connect()
230
+ finally:
231
+ await self._stop_impl(force=True)
232
+
233
+ async def stop(self) -> None:
234
+ self._check_owner()
235
+ task = asyncio.create_task(self._stop_impl(force=False))
236
+ try:
237
+ await asyncio.shield(task)
238
+ except asyncio.CancelledError:
239
+ await _await_cleanup(task)
240
+ raise
241
+
242
+ async def _stop_impl(self, force: bool) -> None:
243
+ process = self._process
244
+ if process is None:
245
+ return
246
+ if process.returncode is None and not force:
247
+ try:
248
+ if process.stdin is not None:
249
+ process.stdin.write(
250
+ b'{"control_protocol_version":2,"command":"shutdown"}\n'
251
+ )
252
+ await asyncio.wait_for(process.stdin.drain(), 1.0)
253
+ process.stdin.close()
254
+ except (BrokenPipeError, OSError, asyncio.TimeoutError):
255
+ pass
256
+ try:
257
+ await asyncio.wait_for(process.wait(), self.shutdown_timeout)
258
+ except asyncio.TimeoutError:
259
+ process.terminate()
260
+ try:
261
+ await asyncio.wait_for(process.wait(), self.kill_timeout)
262
+ except asyncio.TimeoutError:
263
+ process.kill()
264
+ await process.wait()
265
+ elif process.returncode is None:
266
+ process.kill()
267
+ try:
268
+ await asyncio.wait_for(process.wait(), self.kill_timeout)
269
+ except asyncio.TimeoutError:
270
+ process.kill()
271
+ await process.wait()
272
+ for task in (self._stdout_task, self._stderr_task):
273
+ if task is not None and not task.done():
274
+ task.cancel()
275
+ for task in (self._stdout_task, self._stderr_task):
276
+ if task is not None:
277
+ try:
278
+ await task
279
+ except BaseException:
280
+ pass
281
+ self._process = None
282
+ self._records = None
283
+ self._stdout_task = None
284
+ self._stderr_task = None
285
+ self._http_url = None
286
+ self._connect_url = None
287
+ self._instance_id = None
288
+ self._ready_record = None
289
+
290
+ async def restart(self) -> "AsyncSparklessServer":
291
+ await self.stop()
292
+ return await self.start()
293
+
294
+ async def __aenter__(self) -> "AsyncSparklessServer":
295
+ if self._entered:
296
+ raise SparklessServerError(
297
+ "nested entry of the same server owner is not supported"
298
+ )
299
+ self._entered = True
300
+ try:
301
+ return await self.start()
302
+ except BaseException:
303
+ self._entered = False
304
+ raise
305
+
306
+ async def __aexit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
307
+ try:
308
+ await self.stop()
309
+ finally:
310
+ self._entered = False
@@ -0,0 +1,119 @@
1
+ """Spark Connect client and server lifecycle composition."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from ._common import (
8
+ Any,
9
+ Mapping,
10
+ Optional,
11
+ SparklessServerError,
12
+ os,
13
+ )
14
+ from ._sync import SparklessServer
15
+
16
+
17
+ class SparklessConnect:
18
+ """Own a Spark Connect server and one real pyspark-client session."""
19
+
20
+ server_class = SparklessServer
21
+
22
+ def __init__(self, *, server_options: Optional[Mapping[str, Any]] = None) -> None:
23
+ if server_options is not None and not isinstance(server_options, Mapping):
24
+ raise TypeError(
25
+ "server_options must be a mapping of SparklessServer options"
26
+ )
27
+ self._options = {} if server_options is None else dict(server_options)
28
+ if self._options.get("connect_port", 0) is None:
29
+ raise ValueError("SparklessConnect requires the Spark Connect endpoint")
30
+ self._server: Optional[SparklessServer] = None
31
+ self._session: Optional[Any] = None
32
+ self._active = False
33
+ self._owner_pid = os.getpid()
34
+
35
+ @staticmethod
36
+ def _attach_cleanup_errors(
37
+ primary: BaseException, cleanup_errors: list[BaseException]
38
+ ) -> None:
39
+ for error in cleanup_errors:
40
+ primary.add_note(f"SparklessConnect cleanup also failed: {error!r}")
41
+
42
+ def _ensure_owner_process(self) -> None:
43
+ if os.getpid() != self._owner_pid:
44
+ raise SparklessServerError(
45
+ "SparklessConnect ownership changed after fork; create a new helper in the child"
46
+ )
47
+
48
+ def __enter__(self) -> Any:
49
+ self._ensure_owner_process()
50
+ if self._active:
51
+ raise SparklessServerError(
52
+ "nested entry of the same SparklessConnect is not supported"
53
+ )
54
+ # Fail before creating a child process when the optional client is missing.
55
+ try:
56
+ from pyspark.sql import SparkSession
57
+ except ImportError as error:
58
+ raise ImportError(
59
+ "SparklessConnect requires pyspark-client; install sparkless-connect[client]"
60
+ ) from error
61
+
62
+ self._active = True
63
+ try:
64
+ # Retain the launcher before start: it owns any child created before a
65
+ # readiness/startup error is raised, and the failure path must still
66
+ # attempt to stop it.
67
+ server = self.server_class(**self._options)
68
+ self._server = server
69
+ server.start()
70
+ self._session = SparkSession.builder.remote(
71
+ server.spark_connect_url
72
+ ).create()
73
+ return self._session
74
+ except BaseException as primary:
75
+ cleanup_errors: list[BaseException] = []
76
+ if self._session is not None:
77
+ try:
78
+ self._session.stop()
79
+ self._session = None
80
+ except BaseException as error:
81
+ cleanup_errors.append(error)
82
+ if self._server is not None:
83
+ try:
84
+ self._server.stop()
85
+ self._server = None
86
+ except BaseException as error:
87
+ cleanup_errors.append(error)
88
+ self._active = self._session is not None or self._server is not None
89
+ self._attach_cleanup_errors(primary, cleanup_errors)
90
+ raise
91
+
92
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> Literal[False]:
93
+ self._ensure_owner_process()
94
+ cleanup_errors: list[BaseException] = []
95
+ session, server = self._session, self._server
96
+ if session is not None:
97
+ try:
98
+ session.stop()
99
+ self._session = None
100
+ except BaseException as error:
101
+ cleanup_errors.append(error)
102
+ if server is not None:
103
+ try:
104
+ server.stop()
105
+ self._server = None
106
+ except BaseException as error:
107
+ cleanup_errors.append(error)
108
+ # Keep whichever resource failed cleanup so another __exit__ can retry;
109
+ # don't allow sequential reuse while this instance still owns either one.
110
+ self._active = self._session is not None or self._server is not None
111
+
112
+ if exc is not None:
113
+ self._attach_cleanup_errors(exc, cleanup_errors)
114
+ return False
115
+ if cleanup_errors:
116
+ primary = cleanup_errors[0]
117
+ self._attach_cleanup_errors(primary, cleanup_errors[1:])
118
+ raise primary
119
+ return False
@@ -0,0 +1,470 @@
1
+ """Shared process, control-protocol, and readiness primitives for the launcher."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import importlib
7
+ import ipaddress
8
+ import json
9
+ import math
10
+ import os
11
+ import queue
12
+ import subprocess
13
+ import threading
14
+ from collections import deque
15
+ from importlib.metadata import PackageNotFoundError, version as distribution_version
16
+ from typing import Any, Callable, Deque, Dict, Mapping, Optional, Tuple, cast
17
+ from urllib.parse import urlsplit
18
+
19
+ CONTROL_PROTOCOL_VERSION = 2
20
+ CAPABILITIES_PROTOCOL_VERSION = 1
21
+ SPARK_CONNECT_PROTOCOL_VERSION = "4.0.5"
22
+ MAX_CONTROL_FRAME_BYTES = 16 * 1024
23
+ MAX_DIAGNOSTIC_BYTES = 64 * 1024
24
+
25
+
26
+ class SparklessServerError(RuntimeError):
27
+ """Raised when the owned native service cannot satisfy its contract."""
28
+
29
+
30
+ class UnsupportedServerPlatformError(SparklessServerError):
31
+ """Raised when no packaged server executable exists for this platform."""
32
+
33
+
34
+ class UnsupportedSparkConnectError(SparklessServerError):
35
+ """Raised when Spark Connect is disabled or unavailable in the server binary."""
36
+
37
+
38
+ def _product_package(product: str) -> Tuple[str, str]:
39
+ if product == "base":
40
+ return "sparkless_server", "sparkless-server"
41
+ if product == "duckdb":
42
+ return "sparkless_server_duckdb", "sparkless-server-duckdb"
43
+ raise ValueError("product must be 'base' or 'duckdb'")
44
+
45
+
46
+ def _installed_product_version(product: str) -> Optional[str]:
47
+ _, distribution = _product_package(product)
48
+ try:
49
+ return distribution_version(distribution)
50
+ except PackageNotFoundError:
51
+ return None
52
+
53
+
54
+ def _resolve_executable(explicit: Optional[str], product: str = "base") -> str:
55
+ if explicit is not None:
56
+ path = os.path.abspath(os.fspath(explicit))
57
+ if not os.path.isfile(path) or not os.access(path, os.X_OK):
58
+ raise SparklessServerError(
59
+ "server executable path must name an existing executable file"
60
+ )
61
+ return path
62
+
63
+ module_name, distribution = _product_package(product)
64
+ install_hint = (
65
+ "sparkless-server" if product == "base" else "sparkless-server-duckdb"
66
+ )
67
+ try:
68
+ binary_package = importlib.import_module(module_name)
69
+ except ImportError as error:
70
+ raise UnsupportedServerPlatformError(
71
+ "the {} server binary is not installed; install {} "
72
+ "or pass executable_path explicitly".format(product, install_hint)
73
+ ) from error
74
+ binary_package_version = _installed_product_version(product)
75
+ if binary_package_version is None:
76
+ raise UnsupportedServerPlatformError(
77
+ "{} is not installed as a package".format(install_hint)
78
+ )
79
+ try:
80
+ executable_path = cast(
81
+ Callable[[], str], getattr(binary_package, "executable_path")
82
+ )
83
+ path = cast(str, os.fspath(executable_path()))
84
+ except (FileNotFoundError, OSError, UnsupportedServerPlatformError) as error:
85
+ raise UnsupportedServerPlatformError(str(error)) from error
86
+ if not os.path.isfile(path) or not os.access(path, os.X_OK):
87
+ raise UnsupportedServerPlatformError(
88
+ "the installed server binary package has no executable for this platform"
89
+ )
90
+ return path
91
+
92
+
93
+ def _command(executable: str, host: str, port: int) -> Tuple[str, ...]:
94
+ if not isinstance(host, str) or not host:
95
+ raise ValueError("host must be a non-empty IP address")
96
+ try:
97
+ ipaddress.ip_address(host)
98
+ except ValueError as error:
99
+ raise ValueError("host must be an IP address") from error
100
+ if type(port) is not int or not 0 <= port <= 65535:
101
+ raise ValueError("port must be an integer in 0..=65535")
102
+ return (executable, "control", "--host", host, "--port", str(port))
103
+
104
+
105
+ def _command_with_connect(
106
+ executable: str,
107
+ host: str,
108
+ port: int,
109
+ connect_host: str,
110
+ connect_port: Optional[int],
111
+ ) -> Tuple[str, ...]:
112
+ command = list(_command(executable, host, port))
113
+ if connect_port is None:
114
+ command.append("--disable-connect")
115
+ return tuple(command)
116
+ if not isinstance(connect_host, str) or not connect_host:
117
+ raise ValueError("connect_host must be a non-empty IP address")
118
+ try:
119
+ ipaddress.ip_address(connect_host)
120
+ except ValueError as error:
121
+ raise ValueError("connect_host must be an IP address") from error
122
+ if type(connect_port) is not int or not 0 <= connect_port <= 65535:
123
+ raise ValueError("connect_port must be an integer in 0..=65535 or None")
124
+ command.extend(
125
+ ("--connect-host", connect_host, "--connect-port", str(connect_port))
126
+ )
127
+ return tuple(command)
128
+
129
+
130
+ def _binary_lacks_spark_connect(diagnostics: str) -> bool:
131
+ return (
132
+ "--connect-host requires the server connect feature" in diagnostics
133
+ or "--connect-port requires the server connect feature" in diagnostics
134
+ )
135
+
136
+
137
+ def _validate_timeouts(startup: float, shutdown: float, kill: float) -> None:
138
+ for name, value in (
139
+ ("startup_timeout", startup),
140
+ ("shutdown_timeout", shutdown),
141
+ ("kill_timeout", kill),
142
+ ):
143
+ if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
144
+ raise ValueError("{} must be a positive number".format(name))
145
+
146
+
147
+ def _parse_record(frame: bytes) -> Dict[str, Any]:
148
+ if len(frame) > MAX_CONTROL_FRAME_BYTES:
149
+ raise SparklessServerError("server control record exceeds 16 KiB")
150
+ try:
151
+ value = json.loads(frame.decode("utf-8"))
152
+ except (UnicodeDecodeError, ValueError) as error:
153
+ raise SparklessServerError(
154
+ "server emitted an invalid control record"
155
+ ) from error
156
+ if not isinstance(value, dict):
157
+ raise SparklessServerError("server control record must be a JSON object")
158
+ return value
159
+
160
+
161
+ def _validate_ready(
162
+ record: Dict[str, Any],
163
+ require_spark_connect: bool = True,
164
+ expected_product: str = "base",
165
+ ) -> Tuple[str, Optional[str]]:
166
+ if record.get("type") != "ready":
167
+ raise SparklessServerError("server did not emit a readiness record")
168
+ protocol_version = record.get("control_protocol_version")
169
+ if (
170
+ type(protocol_version) is not int
171
+ or protocol_version != CONTROL_PROTOCOL_VERSION
172
+ ):
173
+ raise SparklessServerError("server control protocol version is unsupported")
174
+ capabilities_protocol_version = record.get("capabilities_protocol_version")
175
+ if (
176
+ type(capabilities_protocol_version) is not int
177
+ or capabilities_protocol_version != CAPABILITIES_PROTOCOL_VERSION
178
+ ):
179
+ raise SparklessServerError(
180
+ "server capabilities protocol version is unsupported"
181
+ )
182
+ server_version = record.get("server_version")
183
+ if not isinstance(server_version, str) or not server_version:
184
+ raise SparklessServerError("server readiness record has no server version")
185
+ expected_server_version = _installed_product_version(expected_product)
186
+ reported_product = record.get("server_product")
187
+ if reported_product != expected_product:
188
+ raise SparklessServerError(
189
+ "selected {} launcher received a '{}' server binary".format(
190
+ expected_product, reported_product or "legacy/unknown"
191
+ )
192
+ )
193
+ if record.get("execution_backend") != "polars":
194
+ raise SparklessServerError("server execution backend is not Polars")
195
+ if (
196
+ expected_server_version is not None
197
+ and server_version != expected_server_version
198
+ ):
199
+ raise SparklessServerError(
200
+ "server binary version {} does not match installed {} {}".format(
201
+ server_version,
202
+ _product_package(expected_product)[1],
203
+ expected_server_version,
204
+ )
205
+ )
206
+ instance_id = record.get("server_instance_id")
207
+ if not isinstance(instance_id, str) or not instance_id:
208
+ raise SparklessServerError("server readiness record has no instance identity")
209
+ capabilities = record.get("capabilities")
210
+ if not isinstance(capabilities, dict) or capabilities.get("transport") != "http":
211
+ raise SparklessServerError("server readiness record has invalid capabilities")
212
+ nested_capabilities_version = capabilities.get("capabilities_protocol_version")
213
+ if (
214
+ type(nested_capabilities_version) is not int
215
+ or nested_capabilities_version != CAPABILITIES_PROTOCOL_VERSION
216
+ ):
217
+ raise SparklessServerError("server readiness record has invalid capabilities")
218
+ if capabilities.get("server_instance_id") != instance_id:
219
+ raise SparklessServerError(
220
+ "server capability identity does not match readiness"
221
+ )
222
+ if capabilities.get("server_product") != expected_product:
223
+ raise SparklessServerError(
224
+ "server product differs between readiness and capabilities"
225
+ )
226
+ if capabilities.get("execution_backend") != "polars":
227
+ raise SparklessServerError(
228
+ "server capabilities do not identify Polars execution"
229
+ )
230
+ sources = capabilities.get("data_sources")
231
+ if not isinstance(sources, list) or any(
232
+ not isinstance(item, str) for item in sources
233
+ ):
234
+ raise SparklessServerError(
235
+ "server readiness record has invalid data-source capabilities"
236
+ )
237
+ owner_modes = capabilities.get("duckdb_owner_modes")
238
+ if not isinstance(owner_modes, list) or any(
239
+ not isinstance(item, str) for item in owner_modes
240
+ ):
241
+ raise SparklessServerError(
242
+ "server readiness record has invalid DuckDB owner capabilities"
243
+ )
244
+ if expected_product == "duckdb" and "duckdb" not in sources:
245
+ raise SparklessServerError(
246
+ "DuckDB server product does not advertise DuckDB sources"
247
+ )
248
+ if expected_product == "base" and ("duckdb" in sources or owner_modes):
249
+ raise SparklessServerError(
250
+ "base server product must not advertise DuckDB sources"
251
+ )
252
+ if expected_product == "duckdb" and not {
253
+ "standalone-read-only",
254
+ "shared-quack-owner",
255
+ }.issubset(owner_modes):
256
+ raise SparklessServerError(
257
+ "DuckDB server product has incomplete source-owner capabilities"
258
+ )
259
+ url = _validate_endpoint(record.get("http_url"), "http", "HTTP")
260
+ if capabilities.get("http_url") != url:
261
+ raise SparklessServerError(
262
+ "HTTP endpoint differs between readiness and capabilities"
263
+ )
264
+ transports = capabilities.get("transports")
265
+ if not isinstance(transports, list) or any(
266
+ not isinstance(item, str) for item in transports
267
+ ):
268
+ raise SparklessServerError("server readiness record has invalid transports")
269
+ connect_supported = capabilities.get("spark_connect_supported")
270
+ if type(connect_supported) is not bool:
271
+ raise SparklessServerError("server did not identify Spark Connect support")
272
+ connect_url_value = record.get("spark_connect_url")
273
+ capability_connect_url = capabilities.get("spark_connect_url")
274
+ if connect_supported:
275
+ if set(transports) != {"http", "spark_connect"} or len(transports) != 2:
276
+ raise SparklessServerError(
277
+ "server reported an unexpected Spark Connect transport set"
278
+ )
279
+ connect_url = _validate_endpoint(connect_url_value, "sc", "Spark Connect")
280
+ if capability_connect_url != connect_url:
281
+ raise SparklessServerError(
282
+ "Spark Connect endpoint differs between readiness and capabilities"
283
+ )
284
+ if (
285
+ capabilities.get("spark_connect_protocol_version")
286
+ != SPARK_CONNECT_PROTOCOL_VERSION
287
+ ):
288
+ raise SparklessServerError(
289
+ "server Spark Connect protocol version is unsupported"
290
+ )
291
+ else:
292
+ connect_url = None
293
+ if transports != ["http"]:
294
+ raise SparklessServerError(
295
+ "server reported an unexpected HTTP-only transport set"
296
+ )
297
+ if capabilities.get("spark_connect_protocol_version") is not None:
298
+ raise SparklessServerError(
299
+ "server reported a Spark Connect protocol without support"
300
+ )
301
+ if connect_url_value is not None or capability_connect_url is not None:
302
+ raise SparklessServerError(
303
+ "server advertised a Spark Connect endpoint without support"
304
+ )
305
+ if require_spark_connect and connect_url is None:
306
+ raise UnsupportedSparkConnectError(
307
+ "server binary does not provide a ready Spark Connect endpoint"
308
+ )
309
+ agent_version = record.get("agent_protocol_version")
310
+ if (
311
+ not isinstance(agent_version, str)
312
+ or not agent_version
313
+ or capabilities.get("agent_protocol_version") != agent_version
314
+ ):
315
+ raise SparklessServerError("server did not identify its agent protocol version")
316
+ if not isinstance(capabilities.get("mutation_protocol_version"), str):
317
+ raise SparklessServerError(
318
+ "server did not identify its mutation protocol version"
319
+ )
320
+ return url, connect_url
321
+
322
+
323
+ def _validate_endpoint(value: Any, scheme: str, label: str) -> str:
324
+ if not isinstance(value, str):
325
+ raise SparklessServerError(
326
+ "server readiness record has no {} endpoint".format(label)
327
+ )
328
+ parsed_url = urlsplit(value)
329
+ try:
330
+ endpoint_port = parsed_url.port
331
+ except ValueError as error:
332
+ raise SparklessServerError(
333
+ "server readiness record has an invalid {} endpoint".format(label)
334
+ ) from error
335
+ if (
336
+ parsed_url.scheme != scheme
337
+ or not parsed_url.hostname
338
+ or endpoint_port is None
339
+ or not 1 <= endpoint_port <= 65535
340
+ or parsed_url.username is not None
341
+ or parsed_url.password is not None
342
+ or parsed_url.path
343
+ or parsed_url.query
344
+ or parsed_url.fragment
345
+ ):
346
+ raise SparklessServerError(
347
+ "server readiness record has an invalid {} endpoint".format(label)
348
+ )
349
+ return value
350
+
351
+
352
+ class _ByteTail:
353
+ def __init__(self, limit: int = MAX_DIAGNOSTIC_BYTES) -> None:
354
+ self._limit = limit
355
+ self._parts: Deque[bytes] = deque()
356
+ self._size = 0
357
+ self._lock = threading.Lock()
358
+
359
+ def append(self, value: bytes) -> None:
360
+ with self._lock:
361
+ self._parts.append(value)
362
+ self._size += len(value)
363
+ while self._size > self._limit and self._parts:
364
+ excess = self._size - self._limit
365
+ first = self._parts[0]
366
+ if len(first) <= excess:
367
+ self._parts.popleft()
368
+ self._size -= len(first)
369
+ else:
370
+ self._parts[0] = first[excess:]
371
+ self._size -= excess
372
+
373
+ def text(self) -> str:
374
+ with self._lock:
375
+ value = b"".join(self._parts)
376
+ return value.decode("utf-8", "replace")
377
+
378
+
379
+ def _read_sync_frames(stream: Any, records: "queue.Queue[Any]") -> None:
380
+ while True:
381
+ try:
382
+ frame = stream.readline(MAX_CONTROL_FRAME_BYTES + 1)
383
+ except (OSError, ValueError) as error:
384
+ records.put(error)
385
+ return
386
+ if not frame:
387
+ records.put(None)
388
+ return
389
+ if len(frame) > MAX_CONTROL_FRAME_BYTES or not frame.endswith(b"\n"):
390
+ while frame and not frame.endswith(b"\n"):
391
+ frame = stream.readline(MAX_CONTROL_FRAME_BYTES + 1)
392
+ records.put(
393
+ SparklessServerError("server emitted an oversized control frame")
394
+ )
395
+ continue
396
+ records.put(frame.rstrip(b"\r\n"))
397
+
398
+
399
+ def _drain_sync_stderr(stream: Any, tail: _ByteTail) -> None:
400
+ while True:
401
+ try:
402
+ chunk = stream.read(4096)
403
+ except OSError:
404
+ return
405
+ if not chunk:
406
+ return
407
+ tail.append(chunk)
408
+
409
+
410
+ async def _await_cleanup(task: "asyncio.Task[Any]") -> Any:
411
+ """Finish and reap cleanup even if the caller receives another cancellation."""
412
+ while not task.done():
413
+ try:
414
+ await asyncio.shield(task)
415
+ except asyncio.CancelledError:
416
+ continue
417
+ except BaseException:
418
+ break
419
+ if task.done():
420
+ try:
421
+ return task.result()
422
+ except BaseException:
423
+ pass
424
+
425
+
426
+ __all__ = [
427
+ "Any",
428
+ "CAPABILITIES_PROTOCOL_VERSION",
429
+ "CONTROL_PROTOCOL_VERSION",
430
+ "Callable",
431
+ "Deque",
432
+ "Dict",
433
+ "MAX_CONTROL_FRAME_BYTES",
434
+ "MAX_DIAGNOSTIC_BYTES",
435
+ "Mapping",
436
+ "Optional",
437
+ "PackageNotFoundError",
438
+ "SPARK_CONNECT_PROTOCOL_VERSION",
439
+ "SparklessServerError",
440
+ "Tuple",
441
+ "UnsupportedServerPlatformError",
442
+ "UnsupportedSparkConnectError",
443
+ "_ByteTail",
444
+ "_await_cleanup",
445
+ "_binary_lacks_spark_connect",
446
+ "_command",
447
+ "_command_with_connect",
448
+ "_drain_sync_stderr",
449
+ "_installed_product_version",
450
+ "_parse_record",
451
+ "_product_package",
452
+ "_read_sync_frames",
453
+ "_resolve_executable",
454
+ "_validate_endpoint",
455
+ "_validate_ready",
456
+ "_validate_timeouts",
457
+ "asyncio",
458
+ "cast",
459
+ "deque",
460
+ "distribution_version",
461
+ "importlib",
462
+ "ipaddress",
463
+ "json",
464
+ "math",
465
+ "os",
466
+ "queue",
467
+ "subprocess",
468
+ "threading",
469
+ "urlsplit",
470
+ ]
@@ -0,0 +1,256 @@
1
+ """Synchronous owned-process launcher."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._common import (
6
+ Any,
7
+ Dict,
8
+ Optional,
9
+ SparklessServerError,
10
+ UnsupportedSparkConnectError,
11
+ _ByteTail,
12
+ _binary_lacks_spark_connect,
13
+ _command_with_connect,
14
+ _drain_sync_stderr,
15
+ _parse_record,
16
+ _product_package,
17
+ _read_sync_frames,
18
+ _resolve_executable,
19
+ _validate_ready,
20
+ _validate_timeouts,
21
+ os,
22
+ queue,
23
+ subprocess,
24
+ threading,
25
+ )
26
+
27
+
28
+ class SparklessServer:
29
+ """A synchronous owner for one ``sparkless-server`` child process."""
30
+
31
+ def __init__(
32
+ self,
33
+ host: str = "127.0.0.1",
34
+ port: int = 0,
35
+ executable_path: Optional[str] = None,
36
+ startup_timeout: float = 30.0,
37
+ shutdown_timeout: float = 10.0,
38
+ kill_timeout: float = 5.0,
39
+ env: Optional[Dict[str, str]] = None,
40
+ connect_host: str = "127.0.0.1",
41
+ connect_port: Optional[int] = 0,
42
+ product: str = "base",
43
+ ) -> None:
44
+ self.host = host
45
+ self.port = port
46
+ self._executable_path = executable_path
47
+ self.startup_timeout = startup_timeout
48
+ self.shutdown_timeout = shutdown_timeout
49
+ self.kill_timeout = kill_timeout
50
+ _validate_timeouts(startup_timeout, shutdown_timeout, kill_timeout)
51
+ self.env = None if env is None else dict(env)
52
+ self.connect_host = connect_host
53
+ self.connect_port = connect_port
54
+ _product_package(product)
55
+ self.product = product
56
+ self._process: Optional[subprocess.Popen] = None
57
+ self._records: Optional["queue.Queue[Any]"] = None
58
+ self._stderr_tail = _ByteTail()
59
+ self._threads = [] # type: list[threading.Thread]
60
+ self._owner_pid = os.getpid()
61
+ self._http_url: Optional[str] = None
62
+ self._connect_url: Optional[str] = None
63
+ self._instance_id: Optional[str] = None
64
+ self._ready_record: Optional[Dict[str, Any]] = None
65
+ self._entered = False
66
+
67
+ def _check_owner(self) -> None:
68
+ if os.getpid() != self._owner_pid:
69
+ raise SparklessServerError(
70
+ "server process ownership changed after fork; create a new launcher in the child"
71
+ )
72
+
73
+ @property
74
+ def is_running(self) -> bool:
75
+ self._check_owner()
76
+ return self._process is not None and self._process.poll() is None
77
+
78
+ @property
79
+ def http_url(self) -> str:
80
+ self._check_owner()
81
+ if not self.is_running or self._http_url is None:
82
+ raise SparklessServerError(
83
+ "HTTP endpoint is available only while the server is ready"
84
+ )
85
+ return self._http_url
86
+
87
+ @property
88
+ def server_instance_id(self) -> str:
89
+ self._check_owner()
90
+ if not self.is_running or self._instance_id is None:
91
+ raise SparklessServerError(
92
+ "server identity is available only while the server is ready"
93
+ )
94
+ return self._instance_id
95
+
96
+ @property
97
+ def spark_connect_url(self) -> str:
98
+ self._check_owner()
99
+ if not self.is_running:
100
+ raise SparklessServerError(
101
+ "Spark Connect endpoint is available only while the server is ready"
102
+ )
103
+ if self.connect_port is None or self._connect_url is None:
104
+ raise UnsupportedSparkConnectError(
105
+ "Spark Connect is disabled or unavailable in this server binary"
106
+ )
107
+ return self._connect_url
108
+
109
+ @property
110
+ def diagnostics(self) -> str:
111
+ return self._stderr_tail.text()
112
+
113
+ def start(self) -> "SparklessServer":
114
+ self._check_owner()
115
+ if self.is_running and self._http_url is not None:
116
+ return self
117
+ if self._process is not None:
118
+ self._stop_owned(force=False)
119
+ executable = _resolve_executable(self._executable_path, self.product)
120
+ command = _command_with_connect(
121
+ executable, self.host, self.port, self.connect_host, self.connect_port
122
+ )
123
+ child_env = None
124
+ if self.env is not None:
125
+ child_env = os.environ.copy()
126
+ child_env.update(self.env)
127
+ process = subprocess.Popen(
128
+ command,
129
+ stdin=subprocess.PIPE,
130
+ stdout=subprocess.PIPE,
131
+ stderr=subprocess.PIPE,
132
+ env=child_env,
133
+ bufsize=0,
134
+ )
135
+ self._process = process
136
+ self._records = queue.Queue(maxsize=4)
137
+ self._stderr_tail = _ByteTail()
138
+ stdout_thread = threading.Thread(
139
+ target=_read_sync_frames, args=(process.stdout, self._records), daemon=True
140
+ )
141
+ stderr_thread = threading.Thread(
142
+ target=_drain_sync_stderr,
143
+ args=(process.stderr, self._stderr_tail),
144
+ daemon=True,
145
+ )
146
+ self._threads = [stdout_thread, stderr_thread]
147
+ for thread in self._threads:
148
+ thread.start()
149
+ try:
150
+ frame = self._records.get(timeout=self.startup_timeout)
151
+ if frame is None:
152
+ raise SparklessServerError("server exited before readiness")
153
+ if isinstance(frame, BaseException):
154
+ raise frame
155
+ record = _parse_record(frame)
156
+ url, connect_url = _validate_ready(
157
+ record,
158
+ require_spark_connect=self.connect_port is not None,
159
+ expected_product=self.product,
160
+ )
161
+ except BaseException as error:
162
+ if self.connect_port is not None and self._process is not None:
163
+ try:
164
+ self._process.wait(timeout=0.25)
165
+ except subprocess.TimeoutExpired:
166
+ pass
167
+ for thread in self._threads:
168
+ thread.join(timeout=0.25)
169
+ connect_unavailable = (
170
+ self.connect_port is not None
171
+ and _binary_lacks_spark_connect(self.diagnostics)
172
+ )
173
+ self._stop_owned(force=True)
174
+ if connect_unavailable:
175
+ raise UnsupportedSparkConnectError(
176
+ "server binary does not provide Spark Connect"
177
+ ) from error
178
+ raise
179
+ self._ready_record = record
180
+ self._http_url = url
181
+ self._connect_url = connect_url
182
+ self._instance_id = record["server_instance_id"]
183
+ return self
184
+
185
+ def stop(self) -> None:
186
+ self._check_owner()
187
+ self._stop_owned(force=False)
188
+
189
+ def _stop_owned(self, force: bool) -> None:
190
+ process = self._process
191
+ if process is None:
192
+ return
193
+ if process.poll() is None and not force:
194
+ try:
195
+ if process.stdin is not None:
196
+ process.stdin.write(
197
+ b'{"control_protocol_version":2,"command":"shutdown"}\n'
198
+ )
199
+ process.stdin.flush()
200
+ process.stdin.close()
201
+ except (BrokenPipeError, OSError):
202
+ pass
203
+ try:
204
+ process.wait(timeout=self.shutdown_timeout)
205
+ except subprocess.TimeoutExpired:
206
+ process.terminate()
207
+ try:
208
+ process.wait(timeout=self.kill_timeout)
209
+ except subprocess.TimeoutExpired:
210
+ process.kill()
211
+ process.wait()
212
+ elif process.poll() is None:
213
+ process.kill()
214
+ try:
215
+ process.wait(timeout=self.kill_timeout)
216
+ except subprocess.TimeoutExpired:
217
+ process.kill()
218
+ process.wait()
219
+ if process.stdout is not None:
220
+ try:
221
+ process.stdout.close()
222
+ except OSError:
223
+ pass
224
+ if process.stderr is not None:
225
+ try:
226
+ process.stderr.close()
227
+ except OSError:
228
+ pass
229
+ self._process = None
230
+ self._records = None
231
+ self._http_url = None
232
+ self._connect_url = None
233
+ self._instance_id = None
234
+ self._ready_record = None
235
+
236
+ def restart(self) -> "SparklessServer":
237
+ self.stop()
238
+ return self.start()
239
+
240
+ def __enter__(self) -> "SparklessServer":
241
+ if self._entered:
242
+ raise SparklessServerError(
243
+ "nested entry of the same server owner is not supported"
244
+ )
245
+ self._entered = True
246
+ try:
247
+ return self.start()
248
+ except BaseException:
249
+ self._entered = False
250
+ raise
251
+
252
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
253
+ try:
254
+ self.stop()
255
+ finally:
256
+ self._entered = False
File without changes
@@ -0,0 +1,26 @@
1
+ """Owned native HTTP and Spark Connect server lifecycle helpers.
2
+
3
+ The launcher starts only the selected product's packaged executable or an
4
+ explicit executable path supplied by the caller. It never downloads, compiles,
5
+ or searches ``PATH`` for a server binary.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ._common import (
11
+ SparklessServerError,
12
+ UnsupportedServerPlatformError,
13
+ UnsupportedSparkConnectError,
14
+ )
15
+ from ._sync import SparklessServer
16
+ from ._async import AsyncSparklessServer
17
+ from ._client import SparklessConnect
18
+
19
+ __all__ = [
20
+ "AsyncSparklessServer",
21
+ "SparklessConnect",
22
+ "SparklessServer",
23
+ "SparklessServerError",
24
+ "UnsupportedServerPlatformError",
25
+ "UnsupportedSparkConnectError",
26
+ ]
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: sparkless-connect
3
+ Version: 4.19.0
4
+ Summary: Lightweight Sparkless server and Spark Connect client lifecycle helpers
5
+ License: MIT
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ Provides-Extra: client
9
+ Requires-Dist: pyspark-client==4.0.5; extra == "client"
10
+
11
+ # sparkless-connect
12
+
13
+ Shared Python launcher, lifecycle helpers, and optional Spark Connect client dependency.
14
+ Install `sparkless-connect[client]` to connect with the pinned `pyspark-client`. Install a
15
+ server product package to own a packaged local server process. For an existing endpoint:
16
+
17
+ ```python
18
+ from pyspark.sql import SparkSession
19
+
20
+ spark = SparkSession.builder.remote("sc://server:15002").getOrCreate()
21
+ ```
22
+
23
+ The common launcher also supports explicit executable paths and keeps product selection
24
+ stable when both server products are installed.
@@ -0,0 +1,11 @@
1
+ sparkless_connect/__init__.py,sha256=kSaQD7woCIlm5cUQfOKw1YTVg7z6ElWm9biG-uGLDGE,457
2
+ sparkless_connect/_async.py,sha256=tQJ3DQTjrxGRopUzZFmC_DtYtS5yaovceLmh7DZQ6fE,11234
3
+ sparkless_connect/_client.py,sha256=uIKz9OidicOQ2YSrHixTsZDM7MOi3PXXS3KgAqJ-50c,4539
4
+ sparkless_connect/_common.py,sha256=AtSfaBfmVtIXSU_YDVZTwiroLEOguVk3_ccDxqFjTb0,17286
5
+ sparkless_connect/_sync.py,sha256=pZsdVmZ5X1kNKg7tctRmx5jE4keAwNs8DPOpgXyJKsQ,8701
6
+ sparkless_connect/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ sparkless_connect/server.py,sha256=X4QWv3tnZKh-mL4ZVeHSwPNPRTmWUPUHXpdEch1bksw,729
8
+ sparkless_connect-4.19.0.dist-info/METADATA,sha256=WHHVJiTR9uSieP6c_mGO17HChHkajEB4eB-78nubK-8,851
9
+ sparkless_connect-4.19.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ sparkless_connect-4.19.0.dist-info/top_level.txt,sha256=PxqxanjcGIwM64hsdvFJybT4Wz894o1Esv2vIladj8Y,18
11
+ sparkless_connect-4.19.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ sparkless_connect