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_execution.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_execution.py · 17.3 KB · 537 lines
1"""Object execution contract.
2
3This module defines the small result shape shared by the daemon, future ASGI
4server, DBBASIC Scroll, and AI-assisted repair loop. It does not implement the
5object runtime itself; it wraps an existing runtime object and turns execution
6success or failure into structured data.
7"""
8from __future__ import annotations
9
10import time
11import traceback
12from dataclasses import dataclass
13from datetime import datetime, timezone
14from multiprocessing import get_context
15from multiprocessing.connection import Connection
16from pathlib import Path
17from typing import Any, Iterable, Mapping, Protocol
18
19import object_correlation
20from object_namespace import resolve_object_id
21
22
23@dataclass(frozen=True)
24class ObjectExecutionRequest:
25 """A request to execute one object method with a payload."""
26
27 object_id: str
28 method: str = "GET"
29 payload: Mapping[str, Any] | None = None
30 path: Path | None = None
31 correlation_id: str | None = None
32 # True only for the daemon running a method an object scheduled for
33 # itself (object_schedule): `method` is then a function name (`tick`),
34 # kept exactly as written and called by the scheduled-method
35 # convention. No HTTP or composition path ever sets it.
36 named_method: bool = False
37
38 def normalized_method(self) -> str:
39 """Return the method name used by object runtimes."""
40 method = self.method.strip() if isinstance(self.method, str) else ""
41 if self.named_method:
42 return method
43 return method.upper() or "GET"
44
45 def normalized_payload(self) -> dict[str, Any]:
46 """Return a mutable dict payload for object execution."""
47 if self.payload is None:
48 return {}
49 return dict(self.payload)
50
51
52@dataclass(frozen=True)
53class ObjectExecutionError:
54 """Structured execution failure details."""
55
56 type: str
57 message: str
58 traceback: str = ""
59
60 def to_dict(self) -> dict[str, str]:
61 return {
62 "type": self.type,
63 "message": self.message,
64 "traceback": self.traceback,
65 }
66
67
68@dataclass(frozen=True)
69class ObjectExecutionResult:
70 """Structured result for one object execution attempt."""
71
72 object_id: str
73 method: str
74 path: Path | None
75 ok: bool
76 result: Any
77 error: ObjectExecutionError | None
78 started_at: str
79 finished_at: str
80 duration_ms: float
81 correlation_id: str | None = None
82
83 def to_dict(self) -> dict[str, Any]:
84 return {
85 "object_id": self.object_id,
86 "method": self.method,
87 "path": str(self.path) if self.path is not None else None,
88 "ok": self.ok,
89 "result": self.result,
90 "error": self.error.to_dict() if self.error else None,
91 "started_at": self.started_at,
92 "finished_at": self.finished_at,
93 "duration_ms": self.duration_ms,
94 "correlation_id": self.correlation_id,
95 }
96
97
98class ObjectRuntimeProtocol(Protocol):
99 """Runtime boundary required by this execution contract."""
100
101 def load_object(self, path: Path, object_id: str | None = None) -> "ExecutableObjectProtocol":
102 ...
103
104
105class ExecutableObjectProtocol(Protocol):
106 """Object boundary required by this execution contract."""
107
108 def execute(self, method: str, payload: dict[str, Any]) -> Any:
109 ...
110
111
112class ObjectExecutionFailure(RuntimeError):
113 """Exception wrapper for callers that still need raise-on-failure behavior."""
114
115 def __init__(self, execution_result: ObjectExecutionResult):
116 self.execution_result = execution_result
117 message = "Object execution failed"
118 if execution_result.error is not None:
119 message = execution_result.error.message
120 super().__init__(message)
121
122
123TIMEOUT_ERROR_TYPE = "ObjectExecutionTimeoutError"
124WORKER_ERROR_TYPE = "ObjectWorkerError"
125
126
127def execute_object(
128 runtime: ObjectRuntimeProtocol,
129 request: ObjectExecutionRequest,
130 roots: Iterable[Path] | None = None,
131 *,
132 raise_on_error: bool = False,
133) -> ObjectExecutionResult:
134 """Execute an object and capture success or failure as structured data."""
135 import object_records # lazy: object_records sits below this module
136
137 running = object_records.in_locked_check()
138 if running is not None:
139 # A locked check holds locks every ledger writer waits on; running
140 # another object from inside one is running code nobody declared
141 # read-only. Refused, never queued (see object_records).
142 raise object_records.LockedCheckWriteError(
143 f"Locked check {running!r} tried to run object {request.object_id}; a check only reads."
144 )
145 correlation_id = object_correlation.ensure_correlation_id(
146 request.correlation_id or object_correlation.current_correlation_id()
147 )
148 request = _request_with_correlation_id(request, correlation_id)
149 token = object_correlation.set_current_correlation_id(correlation_id)
150
151 try:
152 return _execute_object_with_context(runtime, request, roots, raise_on_error=raise_on_error)
153 finally:
154 object_correlation.reset_current_correlation_id(token)
155
156
157def _execute_object_with_context(
158 runtime: ObjectRuntimeProtocol,
159 request: ObjectExecutionRequest,
160 roots: Iterable[Path] | None = None,
161 *,
162 raise_on_error: bool = False,
163) -> ObjectExecutionResult:
164 """Execute an object with a correlation context already installed."""
165 started_perf = time.perf_counter()
166 started_at = _utc_timestamp()
167 method = request.normalized_method()
168 payload = request.normalized_payload()
169
170 path = request.path
171 if path is None:
172 path = resolve_object_id(request.object_id, roots)
173
174 if path is None or not path.exists():
175 result = _finish_error(
176 request=request,
177 method=method,
178 path=path,
179 error=ObjectExecutionError(
180 type="ObjectNotFoundError",
181 message=f"Object not found: {request.object_id}",
182 ),
183 started_at=started_at,
184 started_perf=started_perf,
185 )
186 if raise_on_error:
187 raise ObjectExecutionFailure(result)
188 return result
189
190 import object_sandbox # lazy: object_sandbox imports this module
191
192 if object_sandbox.is_user_code(request.object_id, path):
193 # User code never runs in this process (or in whatever process this
194 # is: the server, a warm pool worker, a spawned child, the daemon).
195 result = object_sandbox.execute_request(request, path, base_dir=_runtime_base_dir(runtime))
196 if raise_on_error and not result.ok:
197 raise ObjectExecutionFailure(result)
198 return result
199
200 try:
201 obj = runtime.load_object(path, request.object_id)
202 if request.named_method:
203 output = obj.execute_named(method, payload)
204 else:
205 output = obj.execute(method, payload)
206 except Exception as exc:
207 result = _finish_error(
208 request=request,
209 method=method,
210 path=path,
211 error=_error_from_exception(exc),
212 started_at=started_at,
213 started_perf=started_perf,
214 )
215 if raise_on_error:
216 raise ObjectExecutionFailure(result) from exc
217 return result
218
219 return _finish_success(
220 request=request,
221 method=method,
222 path=path,
223 output=output,
224 started_at=started_at,
225 started_perf=started_perf,
226 )
227
228
229def _runtime_base_dir(runtime: Any) -> Path:
230 """The data directory a runtime would bind helpers to."""
231 base = getattr(runtime, "_base_dir", None)
232 if callable(base):
233 return Path(base())
234 import os
235
236 from object_versions import DEFAULT_DATA_DIR
237
238 return Path(os.environ.get("DBBASIC_DATA_DIR", DEFAULT_DATA_DIR))
239
240
241def execute_python_object_subprocess(
242 request: ObjectExecutionRequest,
243 roots: Iterable[Path] | None = None,
244 *,
245 timeout_seconds: float,
246 raise_on_error: bool = False,
247) -> ObjectExecutionResult:
248 """Execute a Python object in a subprocess with a wall-clock timeout."""
249 correlation_id = object_correlation.ensure_correlation_id(
250 request.correlation_id or object_correlation.current_correlation_id()
251 )
252 request = _request_with_correlation_id(request, correlation_id)
253
254 if timeout_seconds <= 0:
255 from python_object_runtime import PythonObjectRuntime
256
257 return execute_object(
258 PythonObjectRuntime(),
259 request,
260 roots,
261 raise_on_error=raise_on_error,
262 )
263
264 started_perf = time.perf_counter()
265 started_at = _utc_timestamp()
266 method = request.normalized_method()
267 roots_list = list(roots) if roots is not None else None
268 resolved_request = _request_with_resolved_path(request, roots_list)
269
270 import object_sandbox
271
272 if object_sandbox.is_user_code(resolved_request.object_id, resolved_request.path):
273 # Never the spawn path: user code goes to its own sandboxed worker.
274 from python_object_runtime import PythonObjectRuntime
275
276 if resolved_request.path is None:
277 return execute_object(PythonObjectRuntime(), resolved_request, roots_list, raise_on_error=raise_on_error)
278 result = object_sandbox.execute_request(
279 resolved_request,
280 resolved_request.path,
281 base_dir=_runtime_base_dir(PythonObjectRuntime()),
282 timeout_seconds=timeout_seconds,
283 )
284 if raise_on_error and not result.ok:
285 raise ObjectExecutionFailure(result)
286 return result
287
288 context = get_context("spawn")
289 parent_conn, child_conn = context.Pipe(duplex=False)
290 process = context.Process(
291 target=_execute_python_object_child,
292 args=(child_conn, resolved_request, roots_list),
293 daemon=True,
294 )
295 process.start()
296 child_conn.close()
297 process.join(timeout_seconds)
298
299 if process.is_alive():
300 process.terminate()
301 process.join(1)
302 if process.is_alive():
303 process.kill()
304 process.join(1)
305 parent_conn.close()
306 result = _finish_error(
307 request=resolved_request,
308 method=method,
309 path=resolved_request.path,
310 error=ObjectExecutionError(
311 type=TIMEOUT_ERROR_TYPE,
312 message=(
313 f"{method} timed out for object {resolved_request.object_id} "
314 f"after {_format_seconds(timeout_seconds)} seconds"
315 ),
316 ),
317 started_at=started_at,
318 started_perf=started_perf,
319 )
320 if raise_on_error:
321 raise ObjectExecutionFailure(result)
322 return result
323
324 try:
325 if parent_conn.poll():
326 result = parent_conn.recv()
327 else:
328 result = _finish_error(
329 request=resolved_request,
330 method=method,
331 path=resolved_request.path,
332 error=ObjectExecutionError(
333 type=WORKER_ERROR_TYPE,
334 message=(
335 f"Object worker exited without a result "
336 f"(exit code {process.exitcode})"
337 ),
338 ),
339 started_at=started_at,
340 started_perf=started_perf,
341 )
342 finally:
343 parent_conn.close()
344
345 if raise_on_error and not result.ok:
346 raise ObjectExecutionFailure(result)
347 return result
348
349
350def _finish_success(
351 *,
352 request: ObjectExecutionRequest,
353 method: str,
354 path: Path,
355 output: Any,
356 started_at: str,
357 started_perf: float,
358) -> ObjectExecutionResult:
359 return ObjectExecutionResult(
360 object_id=request.object_id,
361 method=method,
362 path=path,
363 ok=True,
364 result=output,
365 error=None,
366 started_at=started_at,
367 finished_at=_utc_timestamp(),
368 duration_ms=_duration_ms(started_perf),
369 correlation_id=request.correlation_id,
370 )
371
372
373def _finish_error(
374 *,
375 request: ObjectExecutionRequest,
376 method: str,
377 path: Path | None,
378 error: ObjectExecutionError,
379 started_at: str,
380 started_perf: float,
381) -> ObjectExecutionResult:
382 return ObjectExecutionResult(
383 object_id=request.object_id,
384 method=method,
385 path=path,
386 ok=False,
387 result=None,
388 error=error,
389 started_at=started_at,
390 finished_at=_utc_timestamp(),
391 duration_ms=_duration_ms(started_perf),
392 correlation_id=request.correlation_id,
393 )
394
395
396def _request_with_correlation_id(
397 request: ObjectExecutionRequest,
398 correlation_id: str,
399) -> ObjectExecutionRequest:
400 return ObjectExecutionRequest(
401 object_id=request.object_id,
402 method=request.method,
403 payload=request.payload,
404 path=request.path,
405 correlation_id=correlation_id,
406 named_method=request.named_method,
407 )
408
409
410def _request_with_resolved_path(
411 request: ObjectExecutionRequest,
412 roots: Iterable[Path] | None,
413) -> ObjectExecutionRequest:
414 if request.path is not None:
415 return request
416
417 return ObjectExecutionRequest(
418 object_id=request.object_id,
419 method=request.method,
420 payload=request.payload,
421 path=resolve_object_id(request.object_id, roots),
422 correlation_id=request.correlation_id,
423 named_method=request.named_method,
424 )
425
426
427def _execute_python_object_child(
428 connection: Connection,
429 request: ObjectExecutionRequest,
430 roots: list[Path] | None,
431) -> None:
432 try:
433 from python_object_runtime import PythonObjectRuntime
434
435 result = execute_object(PythonObjectRuntime(), request, roots)
436 connection.send(result)
437 except BaseException as exc:
438 error_result = _finish_error(
439 request=request,
440 method=request.normalized_method(),
441 path=request.path,
442 error=ObjectExecutionError(
443 type=WORKER_ERROR_TYPE,
444 message=f"Object worker failed: {type(exc).__name__}: {exc}",
445 traceback="".join(traceback.format_exception(type(exc), exc, exc.__traceback__)),
446 ),
447 started_at=_utc_timestamp(),
448 started_perf=time.perf_counter(),
449 )
450 try:
451 connection.send(error_result)
452 except BaseException:
453 pass
454 finally:
455 connection.close()
456
457
458def _error_from_exception(exc: Exception) -> ObjectExecutionError:
459 return ObjectExecutionError(
460 type=exc.__class__.__name__,
461 message=str(exc),
462 traceback="".join(traceback.format_exception(type(exc), exc, exc.__traceback__)),
463 )
464
465
466def _duration_ms(started_perf: float) -> float:
467 return round((time.perf_counter() - started_perf) * 1000, 3)
468
469
470def _utc_timestamp() -> str:
471 return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
472
473
474def _format_seconds(seconds: float) -> str:
475 return f"{seconds:g}"
476
477
478# ---------------------------------------------------------------------------
479# A result JSON cannot hold (bytes, a set, a tuple as a dict key). Shared by
480# the warm-pool worker, which sends its reply as JSON, and the server, which
481# encodes a JSON answer from the result.
482# ---------------------------------------------------------------------------
483
484_UNENCODABLE_WALK_LIMIT = 100_000
485
486
487def _find_unencodable(value: Any) -> tuple[str, str] | None:
488 """(type name, key path) of the first value json.dumps would refuse, or
489 None when this walk finds none. Decides nothing: it is only called after
490 json.dumps has already refused, to say where."""
491 budget = [_UNENCODABLE_WALK_LIMIT]
492
493 def walk(item: Any, path: str, depth: int) -> tuple[str, str] | None:
494 budget[0] -= 1
495 if budget[0] < 0 or depth > 200:
496 return None
497 if item is None or isinstance(item, (str, int, float)):
498 return None
499 if isinstance(item, dict):
500 for key, child in item.items():
501 if not (key is None or isinstance(key, (str, int, float))):
502 return f"{type(key).__name__} key", path
503 part = str(key)[:60]
504 found = walk(child, f"{path}.{part}" if path else part, depth + 1)
505 if found is not None:
506 return found
507 return None
508 if isinstance(item, (list, tuple)):
509 for index, child in enumerate(item):
510 found = walk(child, f"{path}[{index}]", depth + 1)
511 if found is not None:
512 return found
513 return None
514 return type(item).__name__, path
515
516 return walk(value, "", 0)
517
518
519def unencodable_result_message(value: Any, exc: BaseException) -> tuple[str, str]:
520 """(message, type name) for a result json.dumps refused with `exc`: the
521 type that could not be encoded and its key path, never the value."""
522 try:
523 found = _find_unencodable(value)
524 except Exception: # noqa: BLE001 -- a hostile __iter__/items: fall back
525 found = None
526 if found is not None:
527 type_name, where = found
528 type_name = type_name[:80]
529 message = f"object returned a value that is not JSON: {type_name}"
530 message += f" at {where[:300]}" if where else " at the top level"
531 return message, type_name
532 reason = (
533 "it could not be encoded"
534 if isinstance(exc, TypeError)
535 else "it refers to itself or nests too deeply"
536 )
537 return f"object returned a value that is not JSON: {reason}", type(exc).__name__