mimiry-serverless 0.7.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,303 @@
1
+ """The part of mimiry-serverless that runs inside the session's container.
2
+
3
+ The SDK uploads this file (with the caller's own cloudpickle) to /tmp/mimiry/lib and runs it
4
+ through `mimiry session exec`. It is also imported on the caller's side, for `rebuild_tensor`:
5
+ a result names that function, so both sides must have it under the same name.
6
+
7
+ Only the standard library and cloudpickle: nothing is fetched from the network.
8
+
9
+ python3 -m mimiry_serverless._runtime call <n> payload on stdin; waits; result on stdout
10
+ python3 -m mimiry_serverless._runtime shell <n> a shell script on stdin; waits; its output on stdout
11
+ python3 -m mimiry_serverless._runtime fetch <n> the answer to call <n>, after a lost connection
12
+ python3 -m mimiry_serverless._runtime hold <idle> the container's main process
13
+
14
+ A call is run by a separate worker process in its own session, so a lost SSH connection does not
15
+ end it: its result is still written to results/<n>.pkl, and `fetch` reads it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import io
21
+ import os
22
+ import pickle
23
+ import subprocess
24
+ import sys
25
+ import time
26
+ import traceback
27
+
28
+ # MIMIRY_RUNTIME_ROOT only for the tests, which run this outside a container.
29
+ ROOT = os.environ.get("MIMIRY_RUNTIME_ROOT") or "/tmp/mimiry"
30
+ LIB = ROOT + "/lib"
31
+ CALLS = ROOT + "/calls"
32
+ RESULTS = ROOT + "/results"
33
+ READY = ROOT + "/ready"
34
+ LIB_READY = ROOT + "/lib-ready"
35
+ DONE = ROOT + "/done"
36
+ BOOTSTRAP_ERROR = ROOT + "/bootstrap-error"
37
+
38
+ #: A result up to this size comes back in the exec output; a larger one is downloaded.
39
+ INLINE_LIMIT = 6 << 20
40
+ #: How much of a call's log comes back with it.
41
+ LOG_TAIL = 256 << 10
42
+
43
+ # The first byte of a `call` or `fetch` output says what follows.
44
+ INLINE = b"R" # the result, pickled
45
+ IN_FILE = b"F" # the path of the result file
46
+ SHELL = b"S" # a shell call: its exit status, a newline, then its output (or IN_FILE and a path)
47
+
48
+ EXIT_RUNNING = 3 # fetch: the worker is still running
49
+ EXIT_LOST = 5 # the worker ended without a result
50
+
51
+
52
+ # ---- shared with the caller -------------------------------------------------------------
53
+
54
+
55
+ def rebuild_tensor(data, dtype, shape):
56
+ """A Torch tensor, from the bytes, dtype name and shape a result carried it as (caller's side).
57
+
58
+ Every argument is plain data written by the container, so each is checked before use.
59
+ """
60
+ try:
61
+ import torch
62
+ except ImportError:
63
+ raise ImportError("the result holds a Torch tensor: install torch to load it") from None
64
+ want = getattr(torch, dtype, None) if isinstance(dtype, str) else None
65
+ if not isinstance(want, torch.dtype):
66
+ raise ValueError(f"the result names an unknown tensor dtype {dtype!r}")
67
+ if not isinstance(data, (bytes, bytearray)):
68
+ raise ValueError("the result's tensor data is not bytes")
69
+ if not isinstance(shape, tuple) or not all(isinstance(d, int) and not isinstance(d, bool) and d >= 0 for d in shape):
70
+ raise ValueError(f"the result names an invalid tensor shape {shape!r}")
71
+ count = 1
72
+ for d in shape:
73
+ count *= d
74
+ size = torch.empty((), dtype=want).element_size()
75
+ if len(data) != count * size:
76
+ raise ValueError(f"the result's tensor holds {len(data)} bytes, not {count} x {size}")
77
+ if count == 0:
78
+ return torch.empty(shape, dtype=want)
79
+ return torch.frombuffer(bytearray(data), dtype=want).reshape(shape)
80
+
81
+
82
+ def _reduce_tensor(obj):
83
+ """How a Torch tensor travels when results are checked: its bytes, dtype and shape, on the CPU.
84
+
85
+ Torch's own pickling of a tensor calls `torch.load` on the caller's side, which can run
86
+ anything; this form is plain data plus one allowed function. It needs no NumPy on either side
87
+ (Torch does not install it), and every dtype, bfloat16 included, arrives exactly.
88
+ """
89
+ import ctypes
90
+
91
+ import torch
92
+
93
+ t = obj.detach()
94
+ if t.layout != torch.strided:
95
+ t = t.to_dense()
96
+ t = t.resolve_conj().resolve_neg().cpu().contiguous()
97
+ dtype = str(t.dtype).replace("torch.", "")
98
+ nbytes = t.numel() * t.element_size()
99
+ data = ctypes.string_at(t.data_ptr(), nbytes) if nbytes else b""
100
+ # In the container this file runs as __main__ (`python -m`), and a result must name the
101
+ # function as the caller's allow-list does: by its module, not as __main__.rebuild_tensor.
102
+ import importlib
103
+
104
+ rebuild = importlib.import_module("mimiry_serverless._runtime").rebuild_tensor
105
+ return rebuild, (data, dtype, tuple(t.shape))
106
+
107
+
108
+ class _ResultPickler(pickle.Pickler):
109
+ """Plain pickle: classes by name, never as code. Torch tensors as bytes, dtype and shape."""
110
+
111
+ def reducer_override(self, obj):
112
+ torch = sys.modules.get("torch")
113
+ if torch is not None and isinstance(obj, torch.Tensor):
114
+ return _reduce_tensor(obj)
115
+ return NotImplemented
116
+
117
+
118
+ # ---- the container's side ---------------------------------------------------------------
119
+
120
+
121
+ def _write_atomic(path: str, data: bytes) -> None:
122
+ tmp = path + ".partial"
123
+ with open(tmp, "wb") as f:
124
+ f.write(data)
125
+ os.replace(tmp, path)
126
+
127
+
128
+ def _paths(n: str) -> tuple[str, str, str, str]:
129
+ if not n.isdigit():
130
+ raise SystemExit("call number must be digits")
131
+ return (f"{CALLS}/{n}.pkl", f"{RESULTS}/{n}.pkl", f"{CALLS}/{n}.log", f"{CALLS}/{n}.pid")
132
+
133
+
134
+ def _shell_paths(n: str) -> tuple[str, str, str]:
135
+ """A shell call's script, output and exit status."""
136
+ return (f"{CALLS}/{n}.sh", f"{RESULTS}/{n}.out", f"{RESULTS}/{n}.exit")
137
+
138
+
139
+ def _touch(path: str) -> None:
140
+ with open(path, "a"):
141
+ os.utime(path, None)
142
+
143
+
144
+ def _error(kind: str, message: str, tb: str = "") -> dict:
145
+ return {"ok": False, "error": {"type": kind, "message": message, "traceback": tb}}
146
+
147
+
148
+ def _work(n: str) -> int:
149
+ """Runs one call: loads the payload, runs the function, writes the result."""
150
+ payload_path, result_path, _, _ = _paths(n)
151
+ # What the function prints goes to the log (this process's stdout and stderr), never into
152
+ # the result.
153
+ try:
154
+ import cloudpickle
155
+
156
+ with open(payload_path, "rb") as f:
157
+ payload = cloudpickle.load(f)
158
+ fn, args, kwargs = payload["fn"], payload["args"], payload["kwargs"]
159
+ trust = bool(payload.get("trust"))
160
+ # Classes defined in the caller's script travel inside the function as code. Named in
161
+ # __main__ here, a result can refer to them by name, which is what the caller's
162
+ # allow-list checks.
163
+ main = sys.modules["__main__"]
164
+ for name in payload.get("main_names", []):
165
+ obj = getattr(fn, "__globals__", {}).get(name)
166
+ if obj is not None:
167
+ setattr(main, name, obj)
168
+ except Exception as e:
169
+ envelope = _error("PayloadError", f"the call could not be loaded: {e}", traceback.format_exc())
170
+ _write_atomic(result_path, pickle.dumps(envelope, protocol=5))
171
+ return 0
172
+
173
+ try:
174
+ envelope = {"ok": True, "result": fn(*args, **kwargs)}
175
+ except BaseException as e:
176
+ envelope = _error(type(e).__name__, str(e), traceback.format_exc())
177
+
178
+ try:
179
+ if trust:
180
+ data = cloudpickle.dumps(envelope, protocol=5)
181
+ else:
182
+ buf = io.BytesIO()
183
+ _ResultPickler(buf, protocol=5).dump(envelope)
184
+ data = buf.getvalue()
185
+ except Exception as e:
186
+ envelope = _error(
187
+ "ResultNotSendable",
188
+ f"the function returned {type(envelope.get('result')).__name__}, which cannot be sent "
189
+ f"by name ({e}). Return plain data, or name its class in result_types, or set "
190
+ "trust_results=True.",
191
+ traceback.format_exc(),
192
+ )
193
+ data = pickle.dumps(envelope, protocol=5)
194
+ _write_atomic(result_path, data)
195
+ return 0
196
+
197
+
198
+ def _answer(n: str) -> int:
199
+ """Writes call <n>'s answer to stdout (or where to download it) and its log tail to stderr."""
200
+ _, result_path, log_path, _ = _paths(n)
201
+ _, out_path, exit_path = _shell_paths(n)
202
+ try:
203
+ with open(log_path, "rb") as f:
204
+ f.seek(0, os.SEEK_END)
205
+ f.seek(max(0, f.tell() - LOG_TAIL))
206
+ sys.stderr.buffer.write(f.read())
207
+ except OSError:
208
+ pass
209
+ out = sys.stdout.buffer
210
+ if os.path.exists(exit_path):
211
+ with open(exit_path, "rb") as f:
212
+ out.write(SHELL + f.read().strip() + b"\n")
213
+ path, prefix = out_path, b""
214
+ elif os.path.exists(result_path):
215
+ path, prefix = result_path, INLINE
216
+ else:
217
+ return EXIT_LOST
218
+ if os.path.getsize(path) <= INLINE_LIMIT:
219
+ with open(path, "rb") as f:
220
+ out.write(prefix + f.read())
221
+ else:
222
+ out.write(IN_FILE + path.encode())
223
+ out.flush()
224
+ return 0
225
+
226
+
227
+ def _running(pid_path: str) -> bool:
228
+ try:
229
+ with open(pid_path) as f:
230
+ pid = int(f.read().strip())
231
+ os.kill(pid, 0)
232
+ except (OSError, ValueError):
233
+ return False
234
+ # A finished worker that nobody waited for is a zombie: alive to kill(0), but done.
235
+ try:
236
+ with open(f"/proc/{pid}/stat") as f:
237
+ return f.read().split(")")[-1].split()[0] != "Z"
238
+ except OSError:
239
+ return True
240
+
241
+
242
+ def _call(n: str, shell: bool) -> int:
243
+ """Starts call <n> in a worker of its own, waits for it, and answers. The payload (or the
244
+ script) comes on stdin; an empty stdin means it was uploaded to its place beforehand."""
245
+ payload_path, _, log_path, pid_path = _paths(n)
246
+ script_path, out_path, exit_path = _shell_paths(n)
247
+ os.makedirs(CALLS, exist_ok=True)
248
+ os.makedirs(RESULTS, exist_ok=True)
249
+ data = sys.stdin.buffer.read()
250
+ if data:
251
+ _write_atomic(script_path if shell else payload_path, data)
252
+ _touch(ROOT + "/active")
253
+ if shell:
254
+ argv = ["sh", "-c", f'sh {script_path} > {out_path}; echo $? > {exit_path}.partial && mv {exit_path}.partial {exit_path}']
255
+ else:
256
+ argv = [sys.executable, "-m", "mimiry_serverless._runtime", "work", n]
257
+ with open(log_path, "wb") as log, open(os.devnull, "rb") as devnull:
258
+ worker = subprocess.Popen(argv, stdin=devnull, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
259
+ _write_atomic(pid_path, str(worker.pid).encode())
260
+ worker.wait()
261
+ _touch(ROOT + "/active")
262
+ return _answer(n)
263
+
264
+
265
+ def _fetch(n: str) -> int:
266
+ _, result_path, _, pid_path = _paths(n)
267
+ _, _, exit_path = _shell_paths(n)
268
+ if not os.path.exists(result_path) and not os.path.exists(exit_path) and _running(pid_path):
269
+ return EXIT_RUNNING
270
+ return _answer(n)
271
+
272
+
273
+ def _hold(idle: int) -> int:
274
+ """The container's main process: ends on the done flag, or after `idle` seconds with no call
275
+ running or started, so a caller that vanished does not leave a session running."""
276
+ active = ROOT + "/active"
277
+ _touch(active)
278
+ while not os.path.exists(DONE):
279
+ pids = [os.path.join(CALLS, p) for p in os.listdir(CALLS) if p.endswith(".pid")] if os.path.isdir(CALLS) else []
280
+ if any(_running(p) for p in pids):
281
+ _touch(active)
282
+ elif time.time() - os.path.getmtime(active) > idle:
283
+ print(f"mimiry: no call for {idle}s; ending", file=sys.stderr, flush=True)
284
+ return 0
285
+ time.sleep(2)
286
+ return 0
287
+
288
+
289
+ def main(argv: list[str]) -> int:
290
+ if len(argv) >= 2 and argv[0] in ("call", "shell"):
291
+ return _call(argv[1], argv[0] == "shell")
292
+ if len(argv) >= 2 and argv[0] == "fetch":
293
+ return _fetch(argv[1])
294
+ if len(argv) >= 2 and argv[0] == "work":
295
+ return _work(argv[1])
296
+ if len(argv) >= 2 and argv[0] == "hold":
297
+ return _hold(int(argv[1]))
298
+ print("usage: call <n> | shell <n> | fetch <n> | work <n> | hold <idle seconds>", file=sys.stderr)
299
+ return 2
300
+
301
+
302
+ if __name__ == "__main__":
303
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,378 @@
1
+ """One session that runs calls: started, prepared, called, released.
2
+
3
+ Everything reaches the container through `mimiry session exec`, `upload` and `download`: SSH
4
+ through the Mimiry gateway, with the session's host key checked. Nothing about a call goes into
5
+ the session request, so the platform stores no function, argument or result.
6
+
7
+ Each exec takes one gateway ticket, and tickets are limited per user (60 a minute), so a call is
8
+ one exec: payload in on stdin, result out on stdout.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import io
14
+ import os
15
+ import re
16
+ import sys
17
+ import tempfile
18
+ import time
19
+ import zipfile
20
+ from dataclasses import dataclass, field
21
+ from datetime import datetime
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ import cloudpickle
26
+ from mimiry import Client, FailedError, SessionError as RPCSessionError
27
+
28
+ from . import _runtime
29
+ from ._errors import RemoteFunctionError, ResultParseError, SessionError, SessionFailed
30
+ from ._image import Image, caller_python
31
+ from ._results import load
32
+
33
+ #: Seconds the container waits for its next call before ending itself, so a caller that vanished
34
+ #: does not leave a session running.
35
+ IDLE_SECONDS = 600
36
+ #: How long the container may take to be ready: image install steps included.
37
+ SETUP_SECONDS = 1800
38
+ #: After a lost connection, how often to ask for the result (each ask is a gateway ticket).
39
+ FETCH_EVERY = 15
40
+
41
+ # The session states after which nothing more runs (sdk/mimiry/compute_types.go).
42
+ _TERMINAL = {"boot_failed", "setup_failed", "pull_failed", "start_failed", "provision_failed", "exited",
43
+ "terminating", "terminated"}
44
+
45
+ _PY = "env PYTHONPATH=" + _runtime.LIB + " python3"
46
+
47
+
48
+ def log(msg: str) -> None:
49
+ if os.environ.get("MIMIRY_VERBOSE", "1") != "0":
50
+ print(f"[mimiry] {msg}", file=sys.stderr, flush=True)
51
+
52
+
53
+ def printable(data: bytes) -> str:
54
+ """Container output, safe for a terminal: no escape sequences or other control characters
55
+ (a container must not be able to rewrite the caller's screen)."""
56
+ text = data.decode("utf-8", errors="replace")
57
+ return "".join(c for c in text if c in "\n\r\t" or (c >= " " and c != "\x7f" and not "\x80" <= c <= "\x9f"))
58
+
59
+
60
+ @dataclass
61
+ class RunInfo:
62
+ """What one session cost and how long it took, from the platform's own numbers."""
63
+
64
+ session_id: str
65
+ gpu_type: str | None = None
66
+ hourly_rate: float | None = None
67
+ currency: str | None = None
68
+ duration: float | None = None
69
+ final_cost: float | None = None
70
+ state: str | None = None
71
+ stop_reason: str | None = None
72
+ phases: dict[str, float] = field(default_factory=dict)
73
+
74
+
75
+ @dataclass
76
+ class Spec:
77
+ """What a session is asked for."""
78
+
79
+ image: Image
80
+ gpu: list[str] | None = None
81
+ family: list[str] | None = None
82
+ min_vram_gb: int | None = None
83
+ gpu_count: int = 1
84
+ location: str | None = None
85
+ max_rate: float | None = None
86
+ env: dict[str, str] = field(default_factory=dict)
87
+ volumes: dict[str, str] = field(default_factory=dict)
88
+ timeout: int = 3600
89
+ name: str = "mimiry-fn"
90
+
91
+
92
+ def _session_name(prefix: str) -> str:
93
+ base = re.sub(r"[^A-Za-z0-9_-]+", "-", prefix).strip("-_") or "mimiry-fn"
94
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
95
+ return f"{base[: 64 - len(stamp) - 1]}-{stamp}"
96
+
97
+
98
+ def _bootstrap(image: Image) -> str:
99
+ """The container's command (POSIX sh). Holds no call data: it is stored with the session."""
100
+ r = _runtime
101
+ steps = image.install_steps()
102
+ lines = [
103
+ f"mkdir -p {r.LIB} {r.CALLS} {r.RESULTS} || exit 1",
104
+ f'fail() {{ echo "$1" > {r.BOOTSTRAP_ERROR}; echo "mimiry: $1" >&2; exit 1; }}',
105
+ "command -v python3 >/dev/null 2>&1 || { apt-get update -qq && DEBIAN_FRONTEND=noninteractive "
106
+ "apt-get install -y -q --no-install-recommends python3-minimal >/dev/null 2>&1; } "
107
+ '|| fail "python3 is missing and could not be installed"',
108
+ ]
109
+ if steps:
110
+ lines.append(f'{{ {steps}; }} || fail "the image\'s install steps failed"')
111
+ lines += [
112
+ f"touch {r.READY}",
113
+ "i=0",
114
+ f"while [ ! -f {r.LIB_READY} ]; do",
115
+ f" [ -f {r.DONE} ] && exit 0",
116
+ f' i=$((i+1)); [ "$i" -gt {IDLE_SECONDS} ] && {{ echo "mimiry: no caller arrived; ending" >&2; exit 0; }}',
117
+ " sleep 1",
118
+ "done",
119
+ f"exec {_PY} -m mimiry_serverless._runtime hold {IDLE_SECONDS}",
120
+ ]
121
+ return "\n".join(lines)
122
+
123
+
124
+ def _setup_script() -> str:
125
+ """Waits until the container is ready, unpacks the runtime from stdin, and prints the
126
+ container's Python version."""
127
+ r = _runtime
128
+ extract = (
129
+ "import io,sys,zipfile; "
130
+ f"zipfile.ZipFile(io.BytesIO(sys.stdin.buffer.read())).extractall({r.LIB!r})"
131
+ )
132
+ return "\n".join([
133
+ "i=0",
134
+ f"while [ ! -f {r.READY} ]; do",
135
+ f" if [ -f {r.BOOTSTRAP_ERROR} ]; then cat {r.BOOTSTRAP_ERROR} >&2; exit 9; fi",
136
+ f' i=$((i+1)); [ "$i" -gt {SETUP_SECONDS} ] && {{ echo "the container did not get ready" >&2; exit 10; }}',
137
+ " sleep 1",
138
+ "done",
139
+ f'python3 -c "{extract}" || exit 11',
140
+ f"touch {r.LIB_READY}",
141
+ "python3 -c 'import sys; print(\"%d.%d\" % sys.version_info[:2])'",
142
+ ])
143
+
144
+
145
+ def _runtime_zip() -> bytes:
146
+ """What the container needs, from this machine: the runtime and the caller's own
147
+ cloudpickle (pure Python, the same version on both sides, nothing fetched from a network)."""
148
+ buf = io.BytesIO()
149
+ cp_dir = Path(cloudpickle.__file__).parent
150
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
151
+ for f in sorted(cp_dir.glob("*.py")):
152
+ z.write(f, f"cloudpickle/{f.name}")
153
+ z.writestr("mimiry_serverless/__init__.py", "")
154
+ z.write(_runtime.__file__, "mimiry_serverless/_runtime.py")
155
+ return buf.getvalue()
156
+
157
+
158
+ class Session:
159
+ def __init__(self, client: Client, spec: Spec):
160
+ self.c = client
161
+ self.spec = spec
162
+ self.id: str | None = None
163
+ self.started = time.monotonic()
164
+ self.phases: dict[str, float] = {}
165
+ self._n = 0
166
+
167
+ # ---- start ----
168
+
169
+ def _request(self) -> dict[str, Any]:
170
+ s = self.spec
171
+ gpu: dict[str, Any] = {"count": s.gpu_count, "max_gpu_count": s.gpu_count, "priority": ["PRICE"]}
172
+ if s.gpu:
173
+ gpu["types"] = s.gpu
174
+ if s.family:
175
+ gpu["family"] = s.family
176
+ if s.min_vram_gb:
177
+ gpu["vram_gb"] = [s.min_vram_gb]
178
+ if s.location:
179
+ gpu["location"] = s.location
180
+ if s.max_rate is not None:
181
+ gpu["max_hourly_rate"] = s.max_rate
182
+ body: dict[str, Any] = {
183
+ "name": _session_name(s.name),
184
+ "image": {"uri": s.image.uri},
185
+ "gpu": gpu,
186
+ "command": _bootstrap(s.image),
187
+ "environment_vars": {**s.image.env_vars, **s.env},
188
+ "ssh_enabled": True,
189
+ "ssh_public_key": self.c.token().authorized_key,
190
+ "auto_terminate": {"mode": "on_complete"},
191
+ # The whole session, setup included, is bounded: a call that never ends still stops.
192
+ "max_duration": s.timeout + SETUP_SECONDS,
193
+ }
194
+ if s.volumes:
195
+ body["volume_mounts"] = [{"volume_name": n, "mount_path": p} for n, p in s.volumes.items()]
196
+ return body
197
+
198
+ def start(self, *, check_python: bool = True) -> None:
199
+ created = self.c.sessions.create(**self._request())
200
+ self.id = created.id
201
+ log(f"session {self.id} submitted")
202
+
203
+ def progress(sess: Any, transient: str | None) -> None:
204
+ state = getattr(sess, "state", None) if sess is not None else None
205
+ if state and state not in self.phases:
206
+ self.phases[state] = round(time.monotonic() - self.started, 1)
207
+ log(f"state={state}")
208
+
209
+ try:
210
+ ready = self.c.sessions.wait_ready(self.id, timeout=SETUP_SECONDS, on_progress=progress)
211
+ except FailedError:
212
+ self._ended("failed to start")
213
+ if ready.get("state") in _TERMINAL:
214
+ self._ended("ended before it was ready")
215
+ res = self._exec(["sh", "-c", _setup_script()], _runtime_zip(), timeout=SETUP_SECONDS)
216
+ if res.exit_status != 0:
217
+ self._ended(f"could not be prepared: {printable(res.stderr).strip()}")
218
+ theirs, ours = res.stdout.decode().strip(), caller_python()
219
+ if check_python and theirs != ours:
220
+ raise SessionFailed(
221
+ f"the image {self.spec.image.uri!r} runs Python {theirs}, and this script runs on Python {ours}: a "
222
+ "function travels as a cloudpickle blob, which loads only on the same minor version. Use an image "
223
+ f"with Python {ours} (the default, python:{ours}-slim, has it).",
224
+ session_id=self.id,
225
+ )
226
+ log("ready")
227
+
228
+ def _exec(self, argv: list[str], stdin: bytes | None, *, timeout: float | None):
229
+ assert self.id
230
+ return self.c.sessions.exec(self.id, argv, stdin=stdin, timeout=timeout)
231
+
232
+ def _ended(self, what: str) -> None:
233
+ """Raises SessionFailed with the session's own account of why it ended."""
234
+ state = stop = None
235
+ tail = ""
236
+ try:
237
+ s = self.c.sessions.get(self.id)
238
+ state, stop = s.get("state"), s.get("stop_reason")
239
+ tail = self.c.sessions.logs(self.id, tail=30).get("logs") or ""
240
+ except Exception:
241
+ pass
242
+ detail = f" (state {state}, {stop})" if state else ""
243
+ logs = f"\nLast container output:\n{printable(str(tail).encode())}" if tail else ""
244
+ raise SessionFailed(f"session {self.id} {what}{detail}{logs}", session_id=self.id, state=state,
245
+ stop_reason=stop)
246
+
247
+ # ---- calls ----
248
+
249
+ def _invoke(self, mode: str, data: bytes) -> tuple[str, Any]:
250
+ """Sends one call ("call" or "shell") and returns its number and the exec result. A
251
+ connection lost meanwhile does not lose the call: its answer is fetched once ready."""
252
+ n = str(self._n)
253
+ self._n += 1
254
+ argv = _PY.split() + ["-m", "mimiry_serverless._runtime", mode, n]
255
+ stdin: bytes | None = data
256
+ if len(data) > _runtime.INLINE_LIMIT:
257
+ self._upload(data, f"{_runtime.CALLS}/{n}.{'sh' if mode == 'shell' else 'pkl'}")
258
+ stdin = None
259
+ try:
260
+ return n, self._exec(argv, stdin, timeout=self.spec.timeout)
261
+ except RPCSessionError as e:
262
+ if e.raw.get("code") != "connection_lost":
263
+ raise
264
+ log("the connection was lost; the call keeps running, waiting for its result")
265
+ return n, self._fetch_after_loss(n)
266
+
267
+ def call(self, payload: bytes, allowed: frozenset | None) -> Any:
268
+ """Runs one function call and returns its result, or raises RemoteFunctionError."""
269
+ n, res = self._invoke("call", payload)
270
+ if res.stderr:
271
+ sys.stderr.write(printable(res.stderr))
272
+ if not res.stderr.endswith(b"\n"):
273
+ sys.stderr.write("\n")
274
+ sys.stderr.flush()
275
+ data = self._answer(n, res, _runtime.INLINE)
276
+ envelope = load(data, allowed)
277
+ if not isinstance(envelope, dict) or "ok" not in envelope:
278
+ raise ResultParseError(f"call {n}: unexpected result shape")
279
+ if envelope["ok"]:
280
+ return envelope["result"]
281
+ err = envelope.get("error") or {}
282
+ raise RemoteFunctionError(str(err.get("message", "")), remote_type=str(err.get("type", "Exception")),
283
+ remote_traceback=str(err.get("traceback", "")))
284
+
285
+ def shell(self, script: str) -> tuple[int, bytes, bytes]:
286
+ """Runs a shell script in the container: (exit status, stdout, the tail of stderr)."""
287
+ n, res = self._invoke("shell", script.encode())
288
+ out = res.stdout
289
+ if out[:1] != _runtime.SHELL or b"\n" not in out:
290
+ self._answer(n, res, _runtime.SHELL) # raises with the reason
291
+ head, rest = out[1:].split(b"\n", 1)
292
+ res.stdout = rest
293
+ return int(head or b"0"), self._answer(n, res, b""), res.stderr
294
+
295
+ def _upload(self, data: bytes, remote: str) -> None:
296
+ fd, path = tempfile.mkstemp(prefix="mimiry-payload-")
297
+ try:
298
+ with os.fdopen(fd, "wb") as f:
299
+ f.write(data)
300
+ assert self.id
301
+ self.c.sessions.upload(self.id, path, remote)
302
+ finally:
303
+ os.unlink(path)
304
+
305
+ def _fetch_after_loss(self, n: str):
306
+ deadline = time.monotonic() + self.spec.timeout
307
+ argv = _PY.split() + ["-m", "mimiry_serverless._runtime", "fetch", n]
308
+ while time.monotonic() < deadline:
309
+ time.sleep(FETCH_EVERY)
310
+ try:
311
+ res = self._exec(argv, None, timeout=120)
312
+ except RPCSessionError as e:
313
+ if e.raw.get("code") in ("connection_lost", "not_connected"):
314
+ continue
315
+ self._ended("ended while the call was running")
316
+ if res.exit_status != _runtime.EXIT_RUNNING:
317
+ return res
318
+ raise SessionError(f"call {n} did not finish within {self.spec.timeout}s", session_id=self.id)
319
+
320
+ def _answer(self, n: str, res: Any, prefix: bytes) -> bytes:
321
+ """The bytes of call <n>'s answer, after `prefix`: inline, or downloaded when large."""
322
+ if res.exit_status == _runtime.EXIT_LOST:
323
+ self._ended(f"lost call {n}: its worker ended without an answer")
324
+ if res.exit_status != 0:
325
+ raise ResultParseError(f"call {n}: the runtime exited {res.exit_status}: {printable(res.stderr)[-500:]}")
326
+ out = res.stdout
327
+ if out[:1] == _runtime.IN_FILE:
328
+ return self._download(out[1:].decode())
329
+ if out[: len(prefix)] == prefix:
330
+ return out[len(prefix):]
331
+ raise ResultParseError(f"call {n}: the runtime answered something unreadable")
332
+
333
+ def _download(self, remote: str) -> bytes:
334
+ """A large result: copied to a private temporary file (0600), read, and removed."""
335
+ d = tempfile.mkdtemp(prefix="mimiry-result-")
336
+ path = os.path.join(d, "result.pkl")
337
+ try:
338
+ assert self.id
339
+ self.c.sessions.download(self.id, remote, path)
340
+ return Path(path).read_bytes()
341
+ finally:
342
+ if os.path.exists(path):
343
+ os.unlink(path)
344
+ os.rmdir(d)
345
+
346
+ # ---- release ----
347
+
348
+ def release(self) -> RunInfo | None:
349
+ """Ends the session and reads what it cost. Never raises."""
350
+ if self.id is None:
351
+ return None
352
+ try:
353
+ s = self.c.sessions.get(self.id)
354
+ if s.get("state") not in _TERMINAL:
355
+ self.c.sessions.terminate(self.id)
356
+ except Exception as e:
357
+ log(f"could not end session {self.id} ({e}); end it with: mimiry session terminate {self.id}")
358
+ info = RunInfo(session_id=self.id, duration=round(time.monotonic() - self.started, 1), phases=self.phases)
359
+ deadline = time.monotonic() + 8
360
+ while True:
361
+ try:
362
+ s = self.c.sessions.get(self.id)
363
+ except Exception:
364
+ return info
365
+ billing = s.get("billing") or {}
366
+ info.gpu_type = s.get("gpu_type") or info.gpu_type
367
+ info.state, info.stop_reason = s.get("state"), s.get("stop_reason")
368
+ info.hourly_rate = billing.get("hourly_rate") or info.hourly_rate
369
+ info.currency = billing.get("currency") or info.currency
370
+ if billing.get("final_cost") is not None:
371
+ info.final_cost = float(billing["final_cost"])
372
+ break
373
+ if time.monotonic() >= deadline:
374
+ break
375
+ time.sleep(1)
376
+ cost = f"{info.final_cost:.4f} {info.currency or ''}".strip() if info.final_cost is not None else "not settled yet"
377
+ log(f"session {self.id}: {info.gpu_type or '?'} for {info.duration:.0f}s, cost {cost}")
378
+ return info