node-mantis 0.1.0__py3-none-win_amd64.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.
nodemantis/_host.py ADDED
@@ -0,0 +1,152 @@
1
+ """Shared runtime host: one runtime process, reference-counted leases.
2
+
3
+ Mirrors the TS SDK's runtime host: the first session to start spawns the
4
+ runtime child (its spawn environment wins — logging options apply only when
5
+ that call starts a fresh generation), later sessions share it, and the last
6
+ release shuts it down. A generation whose process exited is replaced on the
7
+ next acquire.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import atexit
13
+ import threading
14
+ from contextlib import contextmanager
15
+ from dataclasses import dataclass
16
+ from typing import Any, Callable, Iterator, Optional
17
+
18
+ from ._process import NativeRuntimeProcess
19
+
20
+
21
+ @dataclass
22
+ class _Generation:
23
+ process: NativeRuntimeProcess
24
+ references: int
25
+ dead: bool = False
26
+
27
+
28
+ ProcessFactory = Callable[..., NativeRuntimeProcess]
29
+
30
+
31
+ class RuntimeLease:
32
+ """One session's hold on the shared runtime process."""
33
+
34
+ def __init__(self, host: "RuntimeHost", generation: _Generation) -> None:
35
+ self._host = host
36
+ self._generation = generation
37
+ self._released = False
38
+
39
+ @property
40
+ def process(self) -> NativeRuntimeProcess:
41
+ return self._generation.process
42
+
43
+ @property
44
+ def client(self) -> Any:
45
+ return self._generation.process.client
46
+
47
+ def release(self) -> None:
48
+ if self._released:
49
+ return
50
+ self._released = True
51
+ self._host._release(self._generation)
52
+
53
+
54
+ class RuntimeHost:
55
+ def __init__(self, factory: Optional[ProcessFactory] = None) -> None:
56
+ self._factory: ProcessFactory = factory or NativeRuntimeProcess.start
57
+ self._lock = threading.Lock()
58
+ self._generation: Optional[_Generation] = None
59
+
60
+ def acquire(
61
+ self,
62
+ *,
63
+ env: Optional["dict[str, str]"] = None,
64
+ runtime_path: Optional[str] = None,
65
+ ) -> RuntimeLease:
66
+ while True:
67
+ with self._lock:
68
+ generation = self._generation
69
+ if (
70
+ generation is not None
71
+ and not generation.dead
72
+ and not generation.process.has_exited
73
+ ):
74
+ generation.references += 1
75
+ return RuntimeLease(self, generation)
76
+ # The previous generation (if any) is dead; replace it.
77
+ self._generation = None
78
+ process = self._factory(env=env, runtime_path=runtime_path)
79
+ with self._lock:
80
+ if self._generation is None:
81
+ generation = _Generation(process=process, references=1)
82
+ self._generation = generation
83
+ self._watch(generation)
84
+ return RuntimeLease(self, generation)
85
+ # Another thread won the spawn race; ours is redundant.
86
+ try:
87
+ process.close()
88
+ except Exception: # noqa: BLE001 - best-effort cleanup of the loser
89
+ pass
90
+
91
+ def _watch(self, generation: _Generation) -> None:
92
+ def wait_for_exit() -> None:
93
+ generation.process.wait_for_exit()
94
+ with self._lock:
95
+ generation.dead = True
96
+ if self._generation is generation:
97
+ self._generation = None
98
+
99
+ threading.Thread(
100
+ target=wait_for_exit, name="nodemantis-host-watch", daemon=True
101
+ ).start()
102
+
103
+ def _release(self, generation: _Generation) -> None:
104
+ with self._lock:
105
+ generation.references -= 1
106
+ should_close = generation.references <= 0 and not generation.dead
107
+ if should_close:
108
+ generation.dead = True
109
+ if self._generation is generation:
110
+ self._generation = None
111
+ if should_close:
112
+ generation.process.close()
113
+
114
+ def dispose(self) -> None:
115
+ with self._lock:
116
+ generation = self._generation
117
+ self._generation = None
118
+ if generation is not None and not generation.dead:
119
+ generation.dead = True
120
+ try:
121
+ generation.process.close()
122
+ except Exception: # noqa: BLE001 - interpreter-exit best effort
123
+ pass
124
+
125
+
126
+ _default_host = RuntimeHost()
127
+ _active_host = _default_host
128
+ _swap_lock = threading.Lock()
129
+
130
+
131
+ def get_runtime_host() -> RuntimeHost:
132
+ return _active_host
133
+
134
+
135
+ @contextmanager
136
+ def swap_runtime_host_for_testing(host: RuntimeHost) -> Iterator[RuntimeHost]:
137
+ """Internal seam: run a block against a fake/injected runtime host."""
138
+
139
+ global _active_host
140
+ with _swap_lock:
141
+ previous = _active_host
142
+ _active_host = host
143
+ try:
144
+ yield host
145
+ finally:
146
+ with _swap_lock:
147
+ _active_host = previous
148
+
149
+
150
+ @atexit.register
151
+ def _dispose_at_exit() -> None: # pragma: no cover - interpreter teardown
152
+ _default_host.dispose()
nodemantis/_process.py ADDED
@@ -0,0 +1,445 @@
1
+ """Native runtime process ownership: resolution, spawn, handshake, shutdown.
2
+
3
+ Port of the TS SDK's runtime-process layer. This layer owns one runtime child
4
+ process and its RPC client — no agent policy and no request construction
5
+ belong here.
6
+
7
+ Binary resolution order (fixed by the SDK contract):
8
+ 1. explicit ``runtime_path`` argument (development/test seam, no checksum),
9
+ 2. ``NODEMANTIS_RUNTIME_PATH`` environment variable (no checksum),
10
+ 3. the wheel-bundled binary at ``nodemantis/_runtime_bin/`` — verified against
11
+ the bundled ``runtime-manifest.json`` sha256 once per interpreter.
12
+ There is deliberately no PATH lookup and no fallback download.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import json
19
+ import os
20
+ import subprocess
21
+ import sys
22
+ import threading
23
+ import time
24
+ from typing import Any, Callable, Optional
25
+
26
+ from ._protocol import (
27
+ METHOD_RUNTIME_HELLO,
28
+ METHOD_RUNTIME_SHUTDOWN,
29
+ NODEMANTIS_PROTOCOL_VERSION,
30
+ NODEMANTIS_RUNTIME_IDENTITY,
31
+ )
32
+ from ._rpc import RuntimeClient
33
+ from .errors import (
34
+ NativeRuntimeExitedError,
35
+ NativeRuntimeHandshakeError,
36
+ NativeRuntimeResolutionError,
37
+ NativeRuntimeTerminationError,
38
+ NodeMantisError,
39
+ RuntimeExit,
40
+ )
41
+ from .runtime import UnsupportedPlatformError, runtime_platform_info
42
+
43
+ DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000
44
+ DEFAULT_SHUTDOWN_TIMEOUT_MS = 2_000
45
+ DEFAULT_KILL_TIMEOUT_MS = 2_000
46
+ DEFAULT_STDERR_TAIL_BYTES = 64 * 1024
47
+
48
+ _RUNTIME_BIN_DIR = "_runtime_bin"
49
+ _MANIFEST_NAME = "runtime-manifest.json"
50
+
51
+ _checksum_cache: "dict[str, bool]" = {}
52
+ _checksum_lock = threading.Lock()
53
+
54
+
55
+ def runtime_executable_name(os_name: Optional[str] = None) -> str:
56
+ resolved = os_name if os_name is not None else sys.platform
57
+ is_windows = resolved in ("win32", "Windows", "windows")
58
+ return "nodemantis-runtime.exe" if is_windows else "nodemantis-runtime"
59
+
60
+
61
+ def _bundled_runtime_dir() -> str:
62
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), _RUNTIME_BIN_DIR)
63
+
64
+
65
+ def _validate_executable(path: str) -> str:
66
+ try:
67
+ real = os.path.realpath(path)
68
+ if not os.path.isfile(real):
69
+ raise OSError("path is not a file")
70
+ mode = os.F_OK if sys.platform == "win32" else os.X_OK
71
+ if not os.access(real, mode):
72
+ raise OSError("path is not executable")
73
+ return real
74
+ except OSError as error:
75
+ raise NativeRuntimeResolutionError(
76
+ "INVALID_RUNTIME_PATH",
77
+ f"Native runtime executable is missing or not executable: {path}",
78
+ ) from error
79
+
80
+
81
+ def _verify_bundled_checksum(binary_path: str, manifest_path: str) -> None:
82
+ with _checksum_lock:
83
+ if _checksum_cache.get(binary_path):
84
+ return
85
+ try:
86
+ with open(manifest_path, "r", encoding="utf-8") as handle:
87
+ manifest = json.load(handle)
88
+ expected = manifest.get("sha256")
89
+ except (OSError, ValueError) as error:
90
+ raise NativeRuntimeResolutionError(
91
+ "RUNTIME_CHECKSUM_MISMATCH",
92
+ f"Bundled runtime manifest is missing or unreadable: {manifest_path}",
93
+ ) from error
94
+ if not isinstance(expected, str) or not expected:
95
+ raise NativeRuntimeResolutionError(
96
+ "RUNTIME_CHECKSUM_MISMATCH",
97
+ f"Bundled runtime manifest has no sha256: {manifest_path}",
98
+ )
99
+ digest = hashlib.sha256()
100
+ with open(binary_path, "rb") as handle:
101
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
102
+ digest.update(chunk)
103
+ actual = digest.hexdigest()
104
+ if actual != expected:
105
+ raise NativeRuntimeResolutionError(
106
+ "RUNTIME_CHECKSUM_MISMATCH",
107
+ f"Bundled runtime checksum mismatch: expected {expected}, got {actual}",
108
+ )
109
+ with _checksum_lock:
110
+ _checksum_cache[binary_path] = True
111
+
112
+
113
+ def resolve_runtime_path(
114
+ runtime_path: Optional[str] = None,
115
+ *,
116
+ env: Optional["dict[str, str]"] = None,
117
+ ) -> str:
118
+ """Resolve the runtime executable per the SDK contract (see module doc)."""
119
+
120
+ environment = env if env is not None else os.environ
121
+ if runtime_path is not None:
122
+ if not isinstance(runtime_path, str) or not runtime_path.strip():
123
+ raise NativeRuntimeResolutionError(
124
+ "INVALID_RUNTIME_PATH",
125
+ "The native runtime path must be a non-empty string",
126
+ )
127
+ return _validate_executable(os.path.abspath(runtime_path))
128
+
129
+ env_path = environment.get("NODEMANTIS_RUNTIME_PATH")
130
+ if env_path:
131
+ return _validate_executable(os.path.abspath(env_path))
132
+
133
+ try:
134
+ runtime_platform_info()
135
+ except UnsupportedPlatformError as error:
136
+ raise NativeRuntimeResolutionError("UNSUPPORTED_PLATFORM", str(error)) from error
137
+
138
+ bundled_dir = _bundled_runtime_dir()
139
+ binary_path = os.path.join(bundled_dir, runtime_executable_name())
140
+ if not os.path.isfile(binary_path):
141
+ raise NativeRuntimeResolutionError(
142
+ "RUNTIME_NOT_INSTALLED",
143
+ "This installation has no bundled native runtime (source-free build). "
144
+ "Install the platform wheel from PyPI, or point NODEMANTIS_RUNTIME_PATH "
145
+ "at a nodemantis-runtime executable.",
146
+ )
147
+ _verify_bundled_checksum(binary_path, os.path.join(bundled_dir, _MANIFEST_NAME))
148
+ return _validate_executable(binary_path)
149
+
150
+
151
+ class NativeRuntimeProcess:
152
+ """One spawned runtime child + its full-duplex RPC client."""
153
+
154
+ def __init__(
155
+ self,
156
+ *,
157
+ binary_path: str,
158
+ child: "subprocess.Popen[bytes]",
159
+ client: RuntimeClient,
160
+ hello: "dict[str, Any]",
161
+ shutdown_timeout_ms: float,
162
+ kill_timeout_ms: float,
163
+ max_stderr_tail_bytes: int,
164
+ ) -> None:
165
+ self.binary_path = binary_path
166
+ self.client = client
167
+ self.hello = hello
168
+ self._child = child
169
+ self._shutdown_timeout_ms = shutdown_timeout_ms
170
+ self._kill_timeout_ms = kill_timeout_ms
171
+ self._max_stderr_tail_bytes = max_stderr_tail_bytes
172
+ self._stderr_tail = bytearray()
173
+ self._stderr_lock = threading.Lock()
174
+ self._exit: Optional[RuntimeExit] = None
175
+ self._exit_event = threading.Event()
176
+ self._closing = False
177
+ self._close_lock = threading.Lock()
178
+ self._close_error: "Optional[Exception]" = None
179
+ self._closed = False
180
+
181
+ # ── construction ─────────────────────────────────────────────────────────
182
+
183
+ @classmethod
184
+ def start(
185
+ cls,
186
+ *,
187
+ runtime_path: Optional[str] = None,
188
+ env: Optional["dict[str, str]"] = None,
189
+ handshake_timeout_ms: float = DEFAULT_HANDSHAKE_TIMEOUT_MS,
190
+ shutdown_timeout_ms: float = DEFAULT_SHUTDOWN_TIMEOUT_MS,
191
+ kill_timeout_ms: float = DEFAULT_KILL_TIMEOUT_MS,
192
+ max_stderr_tail_bytes: int = DEFAULT_STDERR_TAIL_BYTES,
193
+ spawn: Optional[Callable[..., "subprocess.Popen[bytes]"]] = None,
194
+ ) -> "NativeRuntimeProcess":
195
+ for name, value in (
196
+ ("handshake_timeout_ms", handshake_timeout_ms),
197
+ ("shutdown_timeout_ms", shutdown_timeout_ms),
198
+ ("kill_timeout_ms", kill_timeout_ms),
199
+ ):
200
+ if not (value > 0):
201
+ raise ValueError(f"{name} must be a positive number")
202
+ if not isinstance(max_stderr_tail_bytes, int) or max_stderr_tail_bytes <= 0:
203
+ raise ValueError("max_stderr_tail_bytes must be a positive integer")
204
+
205
+ binary_path = resolve_runtime_path(runtime_path)
206
+ spawn_env = None if env is None else {**os.environ, **env}
207
+ creationflags = 0
208
+ if sys.platform == "win32": # pragma: no cover - windows only
209
+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
210
+ spawner = spawn if spawn is not None else subprocess.Popen
211
+ try:
212
+ child = spawner(
213
+ [binary_path],
214
+ stdin=subprocess.PIPE,
215
+ stdout=subprocess.PIPE,
216
+ stderr=subprocess.PIPE,
217
+ shell=False,
218
+ env=spawn_env,
219
+ creationflags=creationflags,
220
+ # Raw pipes: a buffered reader's read(n) would block until the
221
+ # full n bytes arrive, stalling frame delivery indefinitely.
222
+ bufsize=0,
223
+ )
224
+ except OSError as error:
225
+ raise NativeRuntimeHandshakeError(
226
+ f"Could not start native runtime at {binary_path}", ""
227
+ ) from error
228
+
229
+ client = RuntimeClient(child.stdout, child.stdin)
230
+ process = cls(
231
+ binary_path=binary_path,
232
+ child=child,
233
+ client=client,
234
+ hello={},
235
+ shutdown_timeout_ms=shutdown_timeout_ms,
236
+ kill_timeout_ms=kill_timeout_ms,
237
+ max_stderr_tail_bytes=max_stderr_tail_bytes,
238
+ )
239
+ process._start_watchers()
240
+ client.start()
241
+
242
+ try:
243
+ hello_value = client.request(
244
+ METHOD_RUNTIME_HELLO, timeout_ms=handshake_timeout_ms
245
+ )
246
+ process.hello = process._validate_hello(hello_value)
247
+ return process
248
+ except Exception as error: # noqa: BLE001 - handshake boundary
249
+ client.dispose(error if isinstance(error, NodeMantisError) else None)
250
+ # Distinguish "child died on its own" from "we had to put it down":
251
+ # check for a self-exit BEFORE escalating to termination.
252
+ exit_value = process._exit_within(0.5)
253
+ terminated = process._terminate(kill_timeout_ms)
254
+ if exit_value is not None and not isinstance(
255
+ error, NativeRuntimeHandshakeError
256
+ ):
257
+ raise process._exited_error(
258
+ "Native runtime exited before completing its handshake", exit_value
259
+ ) from error
260
+ if not terminated:
261
+ raise NativeRuntimeTerminationError(
262
+ f"Native runtime at {binary_path} did not exit after "
263
+ "SIGTERM and SIGKILL",
264
+ process.stderr_tail,
265
+ ) from error
266
+ if isinstance(error, (NativeRuntimeHandshakeError, NativeRuntimeExitedError)):
267
+ raise
268
+ raise NativeRuntimeHandshakeError(
269
+ f"Native runtime handshake failed: {error}", process.stderr_tail
270
+ ) from error
271
+
272
+ # ── observers ────────────────────────────────────────────────────────────
273
+
274
+ @property
275
+ def stderr_tail(self) -> str:
276
+ with self._stderr_lock:
277
+ return bytes(self._stderr_tail).decode("utf-8", errors="replace")
278
+
279
+ @property
280
+ def has_exited(self) -> bool:
281
+ return self._exit is not None
282
+
283
+ def wait_for_exit(self, timeout_seconds: Optional[float] = None) -> Optional[RuntimeExit]:
284
+ self._exit_event.wait(timeout_seconds)
285
+ return self._exit
286
+
287
+ # ── shutdown ─────────────────────────────────────────────────────────────
288
+
289
+ def close(self) -> None:
290
+ """Graceful and idempotent; escalates to termination if shutdown stalls."""
291
+
292
+ with self._close_lock:
293
+ if self._closed:
294
+ if self._close_error is not None:
295
+ raise self._close_error
296
+ return
297
+ self._closing = True
298
+ try:
299
+ self._close_once()
300
+ self._close_error = None
301
+ except Exception as error: # noqa: BLE001 - recorded for idempotency
302
+ self._close_error = error
303
+ raise
304
+ finally:
305
+ self._closed = True
306
+ self.client.dispose()
307
+
308
+ def _close_once(self) -> None:
309
+ if self._exit is not None:
310
+ return
311
+ try:
312
+ self.client.request(
313
+ METHOD_RUNTIME_SHUTDOWN, timeout_ms=self._shutdown_timeout_ms
314
+ )
315
+ except Exception: # noqa: BLE001 - escalation below handles a wedged runtime
316
+ pass
317
+ if self._exit_within(self._shutdown_timeout_ms / 1000.0) is not None:
318
+ return
319
+ if not self._terminate(self._kill_timeout_ms):
320
+ raise NativeRuntimeTerminationError(
321
+ f"Native runtime at {self.binary_path} did not exit after "
322
+ "SIGTERM and SIGKILL",
323
+ self.stderr_tail,
324
+ )
325
+
326
+ def _terminate(self, kill_timeout_ms: float) -> bool:
327
+ if self._exit is not None:
328
+ return True
329
+ try:
330
+ if self._child.stdin is not None:
331
+ self._child.stdin.close()
332
+ except OSError:
333
+ pass
334
+ self._safe_signal(self._child.terminate)
335
+ if self._exit_within(kill_timeout_ms / 1000.0) is not None:
336
+ return True
337
+ self._safe_signal(self._child.kill)
338
+ return self._exit_within(kill_timeout_ms / 1000.0) is not None
339
+
340
+ @staticmethod
341
+ def _safe_signal(action: Callable[[], None]) -> None:
342
+ try:
343
+ action()
344
+ except OSError:
345
+ pass
346
+
347
+ def _exit_within(self, timeout_seconds: float) -> Optional[RuntimeExit]:
348
+ self._exit_event.wait(timeout_seconds)
349
+ return self._exit
350
+
351
+ # ── watchers ─────────────────────────────────────────────────────────────
352
+
353
+ def _start_watchers(self) -> None:
354
+ threading.Thread(
355
+ target=self._stderr_loop, name="nodemantis-runtime-stderr", daemon=True
356
+ ).start()
357
+ threading.Thread(
358
+ target=self._exit_loop, name="nodemantis-runtime-exit", daemon=True
359
+ ).start()
360
+
361
+ def _stderr_loop(self) -> None:
362
+ stream = self._child.stderr
363
+ if stream is None: # pragma: no cover - stderr is always piped
364
+ return
365
+ try:
366
+ while True:
367
+ chunk = stream.read1(65536) if hasattr(stream, "read1") else stream.read(65536)
368
+ if not chunk:
369
+ return
370
+ self._append_stderr(chunk)
371
+ except (OSError, ValueError):
372
+ return
373
+
374
+ def _append_stderr(self, chunk: bytes) -> None:
375
+ with self._stderr_lock:
376
+ limit = self._max_stderr_tail_bytes
377
+ if len(chunk) >= limit:
378
+ self._stderr_tail = bytearray(chunk[-limit:])
379
+ return
380
+ self._stderr_tail.extend(chunk)
381
+ overflow = len(self._stderr_tail) - limit
382
+ if overflow > 0:
383
+ del self._stderr_tail[:overflow]
384
+
385
+ def _exit_loop(self) -> None:
386
+ try:
387
+ returncode = self._child.wait()
388
+ except OSError: # pragma: no cover - only on interpreter teardown
389
+ returncode = self._child.returncode
390
+ # Give the stderr drain a beat so the tail includes final diagnostics.
391
+ time.sleep(0.02)
392
+ exit_value = RuntimeExit(
393
+ code=returncode if returncode is None or returncode >= 0 else None,
394
+ signal=-returncode if returncode is not None and returncode < 0 else None,
395
+ )
396
+ self._exit = exit_value
397
+ self._exit_event.set()
398
+ if self._closing:
399
+ self.client.dispose()
400
+ else:
401
+ self.client.dispose(
402
+ self._exited_error("Native runtime exited unexpectedly", exit_value)
403
+ )
404
+
405
+ # ── helpers ──────────────────────────────────────────────────────────────
406
+
407
+ def _exited_error(self, message: str, exit_value: RuntimeExit) -> NativeRuntimeExitedError:
408
+ if exit_value.error:
409
+ status = exit_value.error
410
+ elif exit_value.signal is not None:
411
+ status = f"signal {exit_value.signal}"
412
+ else:
413
+ status = f"exit code {exit_value.code}"
414
+ return NativeRuntimeExitedError(
415
+ f"{message} ({status})", exit_value, self.stderr_tail
416
+ )
417
+
418
+ def _validate_hello(self, value: Any) -> "dict[str, Any]":
419
+ if not isinstance(value, dict):
420
+ raise NativeRuntimeHandshakeError(
421
+ "Native runtime returned an invalid handshake", self.stderr_tail
422
+ )
423
+ if value.get("protocolVersion") != NODEMANTIS_PROTOCOL_VERSION:
424
+ raise NativeRuntimeHandshakeError(
425
+ "Native runtime protocol mismatch: expected "
426
+ f"{NODEMANTIS_PROTOCOL_VERSION}, received "
427
+ f"{value.get('protocolVersion')!r}",
428
+ self.stderr_tail,
429
+ )
430
+ if value.get("runtime") != NODEMANTIS_RUNTIME_IDENTITY:
431
+ raise NativeRuntimeHandshakeError(
432
+ "Native runtime identity mismatch: expected "
433
+ f"{NODEMANTIS_RUNTIME_IDENTITY}, received {value.get('runtime')!r}",
434
+ self.stderr_tail,
435
+ )
436
+ version = value.get("runtimeVersion")
437
+ if not isinstance(version, str) or not version.strip():
438
+ raise NativeRuntimeHandshakeError(
439
+ "Native runtime returned an invalid runtime version", self.stderr_tail
440
+ )
441
+ return {
442
+ "protocolVersion": NODEMANTIS_PROTOCOL_VERSION,
443
+ "runtime": NODEMANTIS_RUNTIME_IDENTITY,
444
+ "runtimeVersion": version,
445
+ }