Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_worker_pool.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_worker_pool.py · 22.2 KB · 624 lines
1"""Persistent worker-process pool for near-in-process object execution.
2
3Objects that are not listed in ``DBBASIC_TRUSTED_IN_PROCESS_OBJECTS`` run
4through ``object_execution.execute_python_object_subprocess`` today, which
5spawns a brand new interpreter for every single request. That keeps process
6isolation and wall-clock timeout enforcement, but a cold interpreter boot
7dominates latency (roughly 100-200ms) for objects that could otherwise run
8in a couple of milliseconds.
9
10This module keeps a small pool of long-lived worker subprocesses around
11instead. Each worker runs a tiny read-request/write-response loop
12(``_worker_main`` below, reachable as ``python -m object_worker_pool
13--worker``) and re-loads the target object's source fresh on every request
14via ``python_object_runtime.PythonObjectRuntime`` -- so a warm worker still
15picks up source edits made between requests (the "live edit" guarantee
16objects depend on). Isolation and timeout enforcement are preserved because
17every request still runs in its own OS process; only the process-spawn cost
18is amortized away by keeping the process around between requests.
19
20Disabled by default: ``DBBASIC_WORKER_POOL_SIZE`` unset or ``0`` means the
21pool is never constructed and callers should keep using the existing
22spawn-per-request path untouched.
23
24Wire protocol
25--------------
26Parent and worker exchange one JSON message per request/response, each
27framed as a 4-byte big-endian length prefix followed by that many bytes of
28UTF-8 JSON (``_encode_message`` / ``_read_message_async`` /
29``_read_message_sync``).
30
31Request message::
32
33 {
34 "object_id": str,
35 "method": str,
36 "payload": dict,
37 "correlation_id": str | None,
38 "path": str | None, # pre-resolved by the pool manager
39 "base_dir": str | None, # optional PythonObjectRuntime base_dir override
40 "named_method": bool, # optional; a scheduled method (object_schedule)
41 }
42
43Response message is ``object_execution.ObjectExecutionResult.to_dict()``.
44
45Worker stderr is left connected to the parent's stderr (not piped), so
46worker-side tracebacks/log noise land in the normal server logs.
47"""
48from __future__ import annotations
49
50import asyncio
51import atexit
52import json
53import os
54import signal
55import struct
56import sys
57import time
58from pathlib import Path
59from typing import Any, Iterable
60
61import object_execution
62from object_execution import (
63 ObjectExecutionError,
64 ObjectExecutionRequest,
65 ObjectExecutionResult,
66)
67from object_namespace import resolve_object_id
68
69WORKER_POOL_SIZE_ENV = "DBBASIC_WORKER_POOL_SIZE"
70
71_LENGTH_PREFIX = struct.Struct(">I")
72_MAX_MESSAGE_BYTES = 64 * 1024 * 1024 # guard against a corrupt/desynced stream
73
74# Reuse object_execution's private timestamp/duration/format helpers so the
75# results this module builds (timeouts, crashes, worker responses) are
76# byte-for-byte identical in shape to the ones execute_python_object_subprocess
77# produces. These are considered part of the internal contract between the
78# two modules, not object_execution's public API.
79_utc_timestamp = object_execution._utc_timestamp
80_duration_ms = object_execution._duration_ms
81_format_seconds = object_execution._format_seconds
82
83
84# ---------------------------------------------------------------------------
85# Wire protocol helpers
86# ---------------------------------------------------------------------------
87
88
89def _encode_message(payload: dict[str, Any]) -> bytes:
90 body = json.dumps(payload).encode("utf-8")
91 return _LENGTH_PREFIX.pack(len(body)) + body
92
93
94async def _read_message_async(reader: asyncio.StreamReader) -> dict[str, Any]:
95 header = await reader.readexactly(4)
96 (length,) = _LENGTH_PREFIX.unpack(header)
97 if length > _MAX_MESSAGE_BYTES:
98 raise ValueError(f"worker message too large ({length} bytes)")
99 body = await reader.readexactly(length)
100 return json.loads(body.decode("utf-8"))
101
102
103def _read_message_sync(stream: Any) -> dict[str, Any] | None:
104 header = _read_exact_sync(stream, 4)
105 if header is None:
106 return None
107 (length,) = _LENGTH_PREFIX.unpack(header)
108 body = _read_exact_sync(stream, length)
109 if body is None:
110 return None
111 return json.loads(body.decode("utf-8"))
112
113
114def _read_exact_sync(stream: Any, size: int) -> bytes | None:
115 chunks: list[bytes] = []
116 remaining = size
117 while remaining > 0:
118 chunk = stream.read(remaining)
119 if not chunk:
120 return None
121 chunks.append(chunk)
122 remaining -= len(chunk)
123 return b"".join(chunks)
124
125
126# ---------------------------------------------------------------------------
127# Worker process (child side)
128# ---------------------------------------------------------------------------
129
130
131def _worker_main() -> None:
132 """Entry point for a worker subprocess (``python -m object_worker_pool --worker``)."""
133 from python_object_runtime import PythonObjectRuntime
134
135 stdin = sys.stdin.buffer
136 stdout = sys.stdout.buffer
137
138 while True:
139 try:
140 request_message = _read_message_sync(stdin)
141 except Exception:
142 return
143 if request_message is None:
144 return # parent closed stdin (pool shutdown) -- exit cleanly
145
146 response = _handle_worker_request(request_message, PythonObjectRuntime())
147 try:
148 encoded = _encode_message(response)
149 except (TypeError, ValueError, RecursionError) as exc:
150 # The object returned something JSON cannot hold (bytes, a set,
151 # ...). Dying here was "exited without a result (exit code 0)"
152 # with nothing in the log: answer with the reason instead.
153 response = _unencodable_result_response(response, exc)
154 try:
155 encoded = _encode_message(response)
156 except Exception:
157 return
158 try:
159 stdout.write(encoded)
160 stdout.flush()
161 except Exception:
162 return
163
164
165def _unencodable_result_response(response: dict[str, Any], exc: BaseException) -> dict[str, Any]:
166 """The reply for a result that cannot travel as JSON: the same envelope,
167 an error naming the type and where it sits, and one stderr line (which
168 reaches the server log) with the object id and the type only -- never
169 the value."""
170 message, type_name = object_execution.unencodable_result_message(response.get("result"), exc)
171 object_id = str(response.get("object_id") or "")
172 try:
173 print(
174 f"object worker: {object_id!r} returned a value that is not JSON ({type_name})",
175 file=sys.stderr,
176 flush=True,
177 )
178 except Exception: # noqa: BLE001
179 pass
180 return {
181 "object_id": object_id,
182 "method": str(response.get("method") or ""),
183 "path": response.get("path") if isinstance(response.get("path"), str) else None,
184 "ok": False,
185 "result": None,
186 "error": {"type": object_execution.WORKER_ERROR_TYPE, "message": message, "traceback": ""},
187 "started_at": response.get("started_at") if isinstance(response.get("started_at"), str) else _utc_timestamp(),
188 "finished_at": _utc_timestamp(),
189 "duration_ms": response.get("duration_ms") if isinstance(response.get("duration_ms"), (int, float)) else 0.0,
190 "correlation_id": response.get("correlation_id") if isinstance(response.get("correlation_id"), str) else None,
191 }
192
193
194def _handle_worker_request(message: dict[str, Any], runtime: Any) -> dict[str, Any]:
195 object_id = message.get("object_id") or ""
196 method = message.get("method") or "GET"
197 payload = message.get("payload") or {}
198 correlation_id = message.get("correlation_id")
199 path_value = message.get("path")
200
201 request = ObjectExecutionRequest(
202 object_id=object_id,
203 method=method,
204 payload=payload,
205 path=Path(path_value) if path_value else None,
206 correlation_id=correlation_id,
207 named_method=message.get("named_method") is True,
208 )
209
210 try:
211 result = object_execution.execute_object(runtime, request, roots=None)
212 except BaseException as exc: # keep the worker loop alive no matter what happened
213 result = _worker_error_result(request, exc)
214
215 return result.to_dict()
216
217
218def _worker_error_result(request: ObjectExecutionRequest, exc: BaseException) -> ObjectExecutionResult:
219 import traceback
220
221 now = _utc_timestamp()
222 return ObjectExecutionResult(
223 object_id=request.object_id,
224 method=request.normalized_method(),
225 path=request.path,
226 ok=False,
227 result=None,
228 error=ObjectExecutionError(
229 type=object_execution.WORKER_ERROR_TYPE,
230 message=f"Object worker failed: {type(exc).__name__}: {exc}",
231 traceback="".join(traceback.format_exception(type(exc), exc, exc.__traceback__)),
232 ),
233 started_at=now,
234 finished_at=now,
235 duration_ms=0.0,
236 correlation_id=request.correlation_id,
237 )
238
239
240# ---------------------------------------------------------------------------
241# Pool manager (parent side)
242# ---------------------------------------------------------------------------
243
244_LAZY = object() # sentinel occupying a queue slot: "spawn a worker on demand"
245
246
247class _Worker:
248 __slots__ = ("process", "pid")
249
250 def __init__(self, process: "asyncio.subprocess.Process"):
251 self.process = process
252 self.pid = process.pid
253
254
255def _error_result(
256 request: ObjectExecutionRequest,
257 method: str,
258 error_type: str,
259 message: str,
260 started_at: str,
261 started_perf: float,
262) -> ObjectExecutionResult:
263 return ObjectExecutionResult(
264 object_id=request.object_id,
265 method=method,
266 path=request.path,
267 ok=False,
268 result=None,
269 error=ObjectExecutionError(type=error_type, message=message),
270 started_at=started_at,
271 finished_at=_utc_timestamp(),
272 duration_ms=_duration_ms(started_perf),
273 correlation_id=request.correlation_id,
274 )
275
276
277def _result_from_dict(data: dict[str, Any]) -> ObjectExecutionResult:
278 error = None
279 error_data = data.get("error")
280 if error_data:
281 error = ObjectExecutionError(
282 type=error_data["type"],
283 message=error_data["message"],
284 traceback=error_data.get("traceback", ""),
285 )
286
287 path_value = data.get("path")
288 return ObjectExecutionResult(
289 object_id=data["object_id"],
290 method=data["method"],
291 path=Path(path_value) if path_value else None,
292 ok=bool(data["ok"]),
293 result=data.get("result"),
294 error=error,
295 started_at=data["started_at"],
296 finished_at=data["finished_at"],
297 duration_ms=data["duration_ms"],
298 correlation_id=data.get("correlation_id"),
299 )
300
301
302def _request_with_resolved_path(
303 request: ObjectExecutionRequest,
304 roots: Iterable[Path] | None,
305) -> ObjectExecutionRequest:
306 if request.path is not None:
307 return request
308 return ObjectExecutionRequest(
309 object_id=request.object_id,
310 method=request.method,
311 payload=request.payload,
312 path=resolve_object_id(request.object_id, roots),
313 correlation_id=request.correlation_id,
314 named_method=request.named_method,
315 )
316
317
318class WorkerPool:
319 """Async pool of persistent worker subprocesses.
320
321 Workers are spawned lazily -- nothing is started until the first
322 ``execute()`` call needs one, and at most ``size`` workers ever run at
323 once. Each worker handles one request at a time; ``execute()`` acquires
324 a free worker (or spawns one if a lazy slot is available), ships it one
325 request over the wire protocol above, and returns it to the pool when
326 done. A worker that times out or crashes is killed/discarded and its
327 slot is put back as "lazy" so a replacement spawns on next use.
328 """
329
330 def __init__(
331 self,
332 size: int,
333 *,
334 env: dict[str, str] | None = None,
335 python_executable: str | None = None,
336 ) -> None:
337 if size <= 0:
338 raise ValueError("WorkerPool size must be positive")
339 self.size = size
340 self._env = dict(env) if env is not None else None
341 self._python_executable = python_executable or sys.executable
342 self._loop: asyncio.AbstractEventLoop | None = None
343 self._queue: asyncio.Queue | None = None
344 self._known_pids: set[int] = set()
345 self._closed = False
346 atexit.register(self._atexit_kill)
347
348 # -- queue / lifecycle -------------------------------------------------
349
350 def _queue_for_current_loop(self) -> asyncio.Queue:
351 loop = asyncio.get_running_loop()
352 if self._loop is not loop:
353 # A pool must not straddle event loops: asyncio subprocess
354 # transports are bound to the loop that created them. If we're
355 # being used from a new loop (process restart of the loop, or a
356 # test harness that opens a fresh loop per call), hard-kill any
357 # previously known workers by pid (loop-independent) and start
358 # over with fresh lazy slots.
359 self._reap_stale_workers()
360 self._loop = loop
361 self._queue = asyncio.Queue()
362 for _ in range(self.size):
363 self._queue.put_nowait(_LAZY)
364 assert self._queue is not None
365 return self._queue
366
367 def _reap_stale_workers(self) -> None:
368 for pid in self._known_pids:
369 _hard_kill(pid)
370 self._known_pids.clear()
371
372 def _atexit_kill(self) -> None:
373 for pid in list(self._known_pids):
374 _hard_kill(pid)
375
376 async def _spawn_worker(self) -> _Worker:
377 kwargs: dict[str, Any] = {
378 "stdin": asyncio.subprocess.PIPE,
379 "stdout": asyncio.subprocess.PIPE,
380 "stderr": None, # inherit -- worker stderr flows to server logs
381 }
382 if self._env is not None:
383 kwargs["env"] = self._env
384 process = await asyncio.create_subprocess_exec(
385 self._python_executable,
386 "-m",
387 "object_worker_pool",
388 "--worker",
389 **kwargs,
390 )
391 worker = _Worker(process)
392 self._known_pids.add(worker.pid)
393 return worker
394
395 async def _kill_worker(self, worker: _Worker) -> None:
396 process = worker.process
397 self._known_pids.discard(worker.pid)
398 if process.returncode is not None:
399 return
400 try:
401 process.kill()
402 except ProcessLookupError:
403 return
404 try:
405 await asyncio.wait_for(process.wait(), timeout=1.0)
406 except asyncio.TimeoutError:
407 pass
408
409 async def _exit_code(self, worker: _Worker) -> int | None:
410 process = worker.process
411 if process.returncode is not None:
412 return process.returncode
413 try:
414 await asyncio.wait_for(process.wait(), timeout=0.5)
415 except asyncio.TimeoutError:
416 return None
417 return process.returncode
418
419 # -- execution -----------------------------------------------------
420
421 async def execute(
422 self,
423 request: ObjectExecutionRequest,
424 *,
425 timeout_seconds: float,
426 roots: Iterable[Path] | None = None,
427 ) -> ObjectExecutionResult:
428 """Execute one object method on a warm worker, enforcing timeout_seconds."""
429 if self._closed:
430 raise RuntimeError("WorkerPool is closed")
431
432 started_perf = time.perf_counter()
433 started_at = _utc_timestamp()
434 method = request.normalized_method()
435 roots = list(roots) if roots is not None else None
436 resolved_request = _request_with_resolved_path(request, roots)
437
438 import object_sandbox
439
440 if object_sandbox.is_user_code(resolved_request.object_id, resolved_request.path):
441 # Never the admin warm pool: a worker here has the server's
442 # environment and filesystem. User code goes to object_sandbox.
443 return await asyncio.to_thread(
444 object_execution.execute_python_object_subprocess,
445 resolved_request,
446 roots,
447 timeout_seconds=timeout_seconds,
448 )
449
450 message = {
451 "object_id": resolved_request.object_id,
452 "method": method,
453 "payload": resolved_request.normalized_payload(),
454 "correlation_id": resolved_request.correlation_id,
455 "path": str(resolved_request.path) if resolved_request.path is not None else None,
456 "named_method": resolved_request.named_method,
457 }
458 # Encode before taking a worker: a payload JSON can't carry (bytes,
459 # say) used to raise out of here holding the worker, and once every
460 # worker had leaked that way each request waited forever.
461 try:
462 encoded = _encode_message(message)
463 except (TypeError, ValueError) as exc:
464 return _error_result(
465 resolved_request,
466 method,
467 object_execution.WORKER_ERROR_TYPE,
468 f"Request can't be sent to an object worker: {type(exc).__name__}: {exc}",
469 started_at,
470 started_perf,
471 )
472
473 queue = self._queue_for_current_loop()
474 try:
475 slot = await asyncio.wait_for(queue.get(), timeout=timeout_seconds)
476 except asyncio.TimeoutError:
477 return _error_result(
478 resolved_request,
479 method,
480 object_execution.TIMEOUT_ERROR_TYPE,
481 (
482 f"No object worker came free for {resolved_request.object_id} "
483 f"within {_format_seconds(timeout_seconds)} seconds"
484 ),
485 started_at,
486 started_perf,
487 )
488 worker = slot if isinstance(slot, _Worker) else None
489
490 if worker is None:
491 try:
492 worker = await self._spawn_worker()
493 except BaseException as exc:
494 queue.put_nowait(_LAZY)
495 if not isinstance(exc, Exception):
496 raise
497 return _error_result(
498 resolved_request,
499 method,
500 object_execution.WORKER_ERROR_TYPE,
501 f"Failed to start object worker: {type(exc).__name__}: {exc}",
502 started_at,
503 started_perf,
504 )
505
506 worker_died = False
507 try:
508 response = await asyncio.wait_for(
509 _talk_to_worker(worker, encoded),
510 timeout=timeout_seconds,
511 )
512 except asyncio.TimeoutError:
513 worker_died = True
514 await self._kill_worker(worker)
515 result = _error_result(
516 resolved_request,
517 method,
518 object_execution.TIMEOUT_ERROR_TYPE,
519 (
520 f"{method} timed out for object {resolved_request.object_id} "
521 f"after {_format_seconds(timeout_seconds)} seconds"
522 ),
523 started_at,
524 started_perf,
525 )
526 except (asyncio.IncompleteReadError, ConnectionResetError, BrokenPipeError, OSError):
527 worker_died = True
528 exit_code = await self._exit_code(worker)
529 self._known_pids.discard(worker.pid)
530 result = _error_result(
531 resolved_request,
532 method,
533 object_execution.WORKER_ERROR_TYPE,
534 f"Object worker exited without a result (exit code {exit_code})",
535 started_at,
536 started_perf,
537 )
538 except Exception as exc:
539 # A reply we can't read (too large, not JSON) leaves the worker's
540 # stream in an unknown state: replace the worker.
541 worker_died = True
542 self._known_pids.discard(worker.pid)
543 _hard_kill(worker.pid)
544 result = _error_result(
545 resolved_request,
546 method,
547 object_execution.WORKER_ERROR_TYPE,
548 f"Object worker sent a reply that couldn't be read: {type(exc).__name__}: {exc}",
549 started_at,
550 started_perf,
551 )
552 except BaseException:
553 # Cancelled mid-conversation: same, and the slot still goes back
554 # (finally) so the pool never shrinks.
555 worker_died = True
556 self._known_pids.discard(worker.pid)
557 _hard_kill(worker.pid)
558 raise
559 else:
560 result = _result_from_dict(response)
561 finally:
562 queue.put_nowait(_LAZY if worker_died else worker)
563
564 return result
565
566 async def shutdown(self) -> None:
567 """Best-effort termination of every known worker. Never blocks long."""
568 self._closed = True
569 atexit.unregister(self._atexit_kill)
570
571 try:
572 loop = asyncio.get_running_loop()
573 except RuntimeError:
574 loop = None
575
576 if self._queue is None or loop is not self._loop:
577 # Either never used, or being shut down from a different event
578 # loop than the one that spawned the current workers (asyncio
579 # subprocess transports can't be awaited from another loop).
580 # Hard-kill by pid instead of the graceful kill()+wait() path.
581 self._reap_stale_workers()
582 return
583
584 workers: list[_Worker] = []
585 while not self._queue.empty():
586 slot = self._queue.get_nowait()
587 if isinstance(slot, _Worker):
588 workers.append(slot)
589 for worker in workers:
590 await self._kill_worker(worker)
591 self._known_pids.clear()
592
593
594async def _talk_to_worker(worker: _Worker, encoded: bytes) -> dict[str, Any]:
595 process = worker.process
596 assert process.stdin is not None and process.stdout is not None
597 process.stdin.write(encoded)
598 await process.stdin.drain()
599 return await _read_message_async(process.stdout)
600
601
602def _hard_kill(pid: int) -> None:
603 try:
604 os.kill(pid, signal.SIGKILL)
605 except (ProcessLookupError, PermissionError, OSError):
606 pass
607
608
609# ---------------------------------------------------------------------------
610# CLI entry point
611# ---------------------------------------------------------------------------
612
613
614def main(argv: list[str] | None = None) -> int:
615 args = sys.argv[1:] if argv is None else argv
616 if "--worker" in args:
617 _worker_main()
618 return 0
619 print("usage: python -m object_worker_pool --worker", file=sys.stderr)
620 return 2
621
622
623if __name__ == "__main__":
624 raise SystemExit(main())