mimiry 0.2.1__tar.gz → 0.2.3__tar.gz

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.
Files changed (31) hide show
  1. {mimiry-0.2.1 → mimiry-0.2.3}/PKG-INFO +2 -2
  2. {mimiry-0.2.1 → mimiry-0.2.3}/README.md +1 -1
  3. {mimiry-0.2.1 → mimiry-0.2.3}/pyproject.toml +1 -1
  4. {mimiry-0.2.1 → mimiry-0.2.3}/src/Mimiry.egg-info/PKG-INFO +2 -2
  5. {mimiry-0.2.1 → mimiry-0.2.3}/src/Mimiry.egg-info/SOURCES.txt +7 -1
  6. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/__init__.py +1 -1
  7. mimiry-0.2.3/src/mimiry/_availability.py +96 -0
  8. mimiry-0.2.3/src/mimiry/_config.py +177 -0
  9. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/_serialization.py +8 -2
  10. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/_session.py +50 -0
  11. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/_setup.py +19 -16
  12. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/function.py +11 -2
  13. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/image.py +9 -1
  14. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/run.py +14 -2
  15. mimiry-0.2.3/tests/test_availability.py +114 -0
  16. mimiry-0.2.3/tests/test_bootstrap.py +54 -0
  17. mimiry-0.2.3/tests/test_config.py +104 -0
  18. mimiry-0.2.3/tests/test_session.py +61 -0
  19. mimiry-0.2.3/tests/test_setup.py +264 -0
  20. mimiry-0.2.1/src/mimiry/_config.py +0 -58
  21. {mimiry-0.2.1 → mimiry-0.2.3}/setup.cfg +0 -0
  22. {mimiry-0.2.1 → mimiry-0.2.3}/src/Mimiry.egg-info/dependency_links.txt +0 -0
  23. {mimiry-0.2.1 → mimiry-0.2.3}/src/Mimiry.egg-info/entry_points.txt +0 -0
  24. {mimiry-0.2.1 → mimiry-0.2.3}/src/Mimiry.egg-info/requires.txt +0 -0
  25. {mimiry-0.2.1 → mimiry-0.2.3}/src/Mimiry.egg-info/top_level.txt +0 -0
  26. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/__main__.py +0 -0
  27. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/_auth.py +0 -0
  28. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/_cli.py +0 -0
  29. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/_client.py +0 -0
  30. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/_ssh.py +0 -0
  31. {mimiry-0.2.1 → mimiry-0.2.3}/src/mimiry/exceptions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Mimiry
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Python SDK for serverless compute
5
5
  Author-email: Oliver <oliversorensen39@gmail.com>
6
6
  License: Proprietary
@@ -40,7 +40,7 @@ pip install -e .
40
40
 
41
41
  ## Auth
42
42
 
43
- Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, writes `MIMIRY_SSH_KEY` to your shell profile, and verifies the connection:
43
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
44
44
 
45
45
  ```bash
46
46
  mimiry setup # alias: mimiry init
@@ -19,7 +19,7 @@ pip install -e .
19
19
 
20
20
  ## Auth
21
21
 
22
- Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, writes `MIMIRY_SSH_KEY` to your shell profile, and verifies the connection:
22
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
23
23
 
24
24
  ```bash
25
25
  mimiry setup # alias: mimiry init
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "Mimiry"
7
- version = "0.2.1"
7
+ version = "0.2.3"
8
8
  description = "Python SDK for serverless compute"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Mimiry
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Python SDK for serverless compute
5
5
  Author-email: Oliver <oliversorensen39@gmail.com>
6
6
  License: Proprietary
@@ -40,7 +40,7 @@ pip install -e .
40
40
 
41
41
  ## Auth
42
42
 
43
- Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, writes `MIMIRY_SSH_KEY` to your shell profile, and verifies the connection:
43
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
44
44
 
45
45
  ```bash
46
46
  mimiry setup # alias: mimiry init
@@ -9,6 +9,7 @@ src/Mimiry.egg-info/top_level.txt
9
9
  src/mimiry/__init__.py
10
10
  src/mimiry/__main__.py
11
11
  src/mimiry/_auth.py
12
+ src/mimiry/_availability.py
12
13
  src/mimiry/_cli.py
13
14
  src/mimiry/_client.py
14
15
  src/mimiry/_config.py
@@ -19,4 +20,9 @@ src/mimiry/_ssh.py
19
20
  src/mimiry/exceptions.py
20
21
  src/mimiry/function.py
21
22
  src/mimiry/image.py
22
- src/mimiry/run.py
23
+ src/mimiry/run.py
24
+ tests/test_availability.py
25
+ tests/test_bootstrap.py
26
+ tests/test_config.py
27
+ tests/test_session.py
28
+ tests/test_setup.py
@@ -16,7 +16,7 @@ from mimiry.function import function, Function
16
16
  from mimiry.image import Image
17
17
  from mimiry.run import run
18
18
 
19
- __version__ = "0.2.0"
19
+ __version__ = "0.2.3"
20
20
 
21
21
  __all__ = [
22
22
  "__version__",
@@ -0,0 +1,96 @@
1
+ """Pre-create validation of the requested GPU/provider/location.
2
+
3
+ The scheduler rejects an impossible ``gpu``/``provider`` pairing only *after*
4
+ a session is created — e.g. asking for a ``T4`` from ``verda`` (which doesn't
5
+ carry it) fails the session with ``unsupported GPU type "T4"`` after a
6
+ provisioning round-trip. This module catches that locally, before the POST,
7
+ and turns it into an actionable error that names the providers which *do*
8
+ offer the GPU.
9
+
10
+ Design: the check is **best-effort**. A definitive mismatch (the GPU isn't
11
+ offered, or not by the requested provider/location) raises ``SessionError``.
12
+ But any failure to *consult* availability — network error, malformed payload,
13
+ empty list — is swallowed: a flaky availability endpoint must never block an
14
+ otherwise-valid job. The API stays the source of truth; this is just a fast,
15
+ friendly pre-flight.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import Any
21
+
22
+ from mimiry.exceptions import SessionError
23
+
24
+
25
+ def check_gpu_offered(
26
+ models: list[dict],
27
+ gpu: str,
28
+ provider: str | None,
29
+ location: str | None,
30
+ ) -> None:
31
+ """Raise ``SessionError`` if ``gpu`` (optionally pinned to ``provider`` /
32
+ ``location``) isn't offered according to the availability ``models`` list.
33
+
34
+ ``gpu`` matches either a model ``name`` (e.g. ``"H100_SXM"``) or ``family``
35
+ (e.g. ``"H100"``). Returns ``None`` when the request is satisfiable.
36
+ """
37
+ matches = [m for m in models if m.get("name") == gpu or m.get("family") == gpu]
38
+ if not matches:
39
+ offered = sorted({m.get("name") for m in models if m.get("name")})
40
+ raise SessionError(
41
+ f"GPU type {gpu!r} is not offered. Available types: "
42
+ f"{', '.join(offered) or 'none'}."
43
+ )
44
+
45
+ available = [m for m in matches if m.get("available")]
46
+ if not available:
47
+ raise SessionError(f"GPU type {gpu!r} is currently unavailable on all providers.")
48
+
49
+ if provider is None:
50
+ return # available somewhere; let the scheduler pick a provider
51
+
52
+ # Collapse the available matches into provider → set(locations).
53
+ prov_locs: dict[str, set[str]] = {}
54
+ for m in available:
55
+ for p in m.get("providers", []):
56
+ name = p.get("provider")
57
+ if name:
58
+ prov_locs.setdefault(name, set()).update(p.get("locations") or [])
59
+
60
+ if provider not in prov_locs:
61
+ offerers = ", ".join(sorted(prov_locs)) or "none"
62
+ raise SessionError(
63
+ f"GPU {gpu!r} is not offered by provider {provider!r}. "
64
+ f"Available providers for {gpu}: {offerers}. "
65
+ f"Pass provider=<one of those>, or omit the provider hint to let "
66
+ f"Mimiry choose."
67
+ )
68
+
69
+ if location is not None and location not in prov_locs[provider]:
70
+ locs = ", ".join(sorted(prov_locs[provider])) or "none"
71
+ raise SessionError(
72
+ f"Provider {provider!r} offers {gpu} but not in location {location!r}. "
73
+ f"Available locations: {locs}."
74
+ )
75
+
76
+
77
+ def preflight_gpu_availability(
78
+ client: Any,
79
+ gpu: str,
80
+ provider: str | None,
81
+ location: str | None = None,
82
+ ) -> None:
83
+ """Best-effort pre-create check. Raises ``SessionError`` on a definitive
84
+ mismatch; silently returns if availability can't be consulted.
85
+
86
+ ``client`` only needs a ``get_availability()`` method (see
87
+ :class:`mimiry._client.MimiryClient`).
88
+ """
89
+ try:
90
+ data = client.get_availability()
91
+ except Exception:
92
+ return # never block submission on an availability-endpoint hiccup
93
+ models = data.get("gpu_models") if isinstance(data, dict) else None
94
+ if not models:
95
+ return # nothing to validate against — defer to the API
96
+ check_gpu_offered(models, gpu, provider, location)
@@ -0,0 +1,177 @@
1
+ """Process-global SDK configuration. Holds auth + API base URL.
2
+
3
+ Key-path resolution precedence (highest first):
4
+
5
+ 1. an explicit ``mimiry.configure(ssh_key_path=...)`` call or the ``--ssh-key``
6
+ CLI flag
7
+ 2. the ``MIMIRY_SSH_KEY`` environment variable
8
+ 3. the on-disk config file written by ``mimiry setup``
9
+ (``$XDG_CONFIG_HOME/mimiry/config.toml``, default ``~/.config/mimiry/config.toml``)
10
+
11
+ The config file stores **only the path** to the SSH key — never the key
12
+ material itself, and never a token. That keeps the file low-sensitivity: the
13
+ real secret stays in ``~/.ssh/mimiry`` behind its own ``0600`` perms. We still
14
+ write the config ``0600`` and refuse to read it if it's group/other-writable,
15
+ since a writable config would be a key-redirection injection vector.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import stat
22
+ import tempfile
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+
26
+ DEFAULT_API_BASE = "https://softlaunch.mimiry.com"
27
+ DEFAULT_TIMEOUT_SECONDS = 1800 # 30 min — must accommodate ~2 min cold start + work
28
+
29
+ # Group/other WRITABLE bits. We reject a config carrying these on read: an
30
+ # attacker who can write the file could repoint the SDK at a key they control.
31
+ # Readability is *not* checked — the file holds only a path, which isn't secret.
32
+ _INSECURE_WRITE_BITS = stat.S_IWGRP | stat.S_IWOTH # 0o022
33
+
34
+
35
+ @dataclass
36
+ class Config:
37
+ ssh_key_path: Path | None = None
38
+ api_base: str = DEFAULT_API_BASE
39
+ timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS
40
+ poll_interval_seconds: float = 5.0
41
+ # Tighter than state polling — the marker-emission → auto_terminate window is
42
+ # only the wrapper's tail sleep (~20s), so we need ~2s cadence to catch it reliably.
43
+ log_poll_interval_seconds: float = 2.0
44
+ extras: dict = field(default_factory=dict)
45
+
46
+
47
+ _config = Config()
48
+
49
+
50
+ # ────────────────────────── on-disk config file ──────────────────────────
51
+
52
+
53
+ def config_path() -> Path:
54
+ """Path to the persisted config file (honours ``$XDG_CONFIG_HOME``)."""
55
+ base = os.environ.get("XDG_CONFIG_HOME")
56
+ root = Path(base).expanduser() if base else Path.home() / ".config"
57
+ return root / "mimiry" / "config.toml"
58
+
59
+
60
+ def save_key_path(ssh_key_path: str | Path, path: Path | None = None) -> Path:
61
+ """Persist the SSH key *path* (never key material) to a ``0600`` config file.
62
+
63
+ The write is atomic — content goes to a temp file in the same directory and
64
+ is ``os.replace``-d into place — so a crash mid-write can't leave a
65
+ truncated config behind. The containing directory is created ``0700``.
66
+ """
67
+ cfg_path = path or config_path()
68
+ cfg_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
69
+
70
+ key_str = str(Path(ssh_key_path).expanduser())
71
+ # TOML-escape backslashes/quotes (defensive — WSL paths are POSIX, but a
72
+ # Windows-style path could carry backslashes).
73
+ escaped = key_str.replace("\\", "\\\\").replace('"', '\\"')
74
+ body = (
75
+ "# Mimiry SDK config — written by `mimiry setup`.\n"
76
+ "# Holds only the path to your SSH key, never the key itself.\n"
77
+ f'ssh_key_path = "{escaped}"\n'
78
+ )
79
+
80
+ fd, tmp_name = tempfile.mkstemp(dir=str(cfg_path.parent), prefix=".config-", suffix=".tmp")
81
+ tmp = Path(tmp_name)
82
+ try:
83
+ os.fchmod(fd, 0o600)
84
+ with os.fdopen(fd, "w") as fh:
85
+ fh.write(body)
86
+ fh.flush()
87
+ os.fsync(fh.fileno())
88
+ os.replace(tmp, cfg_path) # atomic on POSIX
89
+ except BaseException:
90
+ tmp.unlink(missing_ok=True)
91
+ raise
92
+ return cfg_path
93
+
94
+
95
+ def read_key_path(path: Path | None = None) -> Path | None:
96
+ """Return the key path stored in the config file, or ``None`` if absent.
97
+
98
+ Raises ``PermissionError`` if the file is group/other-writable, since a
99
+ writable config is a key-redirection injection vector.
100
+ """
101
+ cfg_path = path or config_path()
102
+ try:
103
+ st = cfg_path.stat()
104
+ except FileNotFoundError:
105
+ return None
106
+ if st.st_mode & _INSECURE_WRITE_BITS:
107
+ raise PermissionError(
108
+ f"{cfg_path} is writable by group/other ({oct(stat.S_IMODE(st.st_mode))}); "
109
+ f"refusing to trust it. Fix with: chmod 600 {cfg_path}"
110
+ )
111
+ value = _load_toml(cfg_path.read_text()).get("ssh_key_path")
112
+ return Path(value).expanduser() if value else None
113
+
114
+
115
+ def _load_toml(text: str) -> dict:
116
+ """Parse the config file, preferring stdlib ``tomllib`` (Python 3.11+)."""
117
+ try:
118
+ import tomllib
119
+ except ModuleNotFoundError: # Python 3.10 — no stdlib TOML parser
120
+ return _parse_simple_toml(text)
121
+ return tomllib.loads(text)
122
+
123
+
124
+ def _parse_simple_toml(text: str) -> dict:
125
+ """Minimal fallback for Python 3.10: top-level ``key = "value"`` scalars only.
126
+
127
+ Sufficient for our schema (a single string key). Not a general TOML parser.
128
+ """
129
+ result: dict[str, str] = {}
130
+ for raw in text.splitlines():
131
+ line = raw.split("#", 1)[0].strip()
132
+ if not line or "=" not in line:
133
+ continue
134
+ key, _, value = line.partition("=")
135
+ value = value.strip()
136
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
137
+ value = value[1:-1].replace('\\"', '"').replace("\\\\", "\\")
138
+ result[key.strip()] = value
139
+ return result
140
+
141
+
142
+ # ────────────────────────── public configuration API ──────────────────────────
143
+
144
+
145
+ def configure(
146
+ ssh_key_path: str | Path | None = None,
147
+ api_base: str | None = None,
148
+ timeout_seconds: int | None = None,
149
+ poll_interval_seconds: float | None = None,
150
+ ) -> Config:
151
+ """Set SDK-wide configuration. Any argument left as ``None`` is unchanged."""
152
+ if ssh_key_path is not None:
153
+ _config.ssh_key_path = Path(ssh_key_path).expanduser()
154
+ if api_base is not None:
155
+ _config.api_base = api_base.rstrip("/")
156
+ if timeout_seconds is not None:
157
+ _config.timeout_seconds = timeout_seconds
158
+ if poll_interval_seconds is not None:
159
+ _config.poll_interval_seconds = poll_interval_seconds
160
+ return _config
161
+
162
+
163
+ def get_config() -> Config:
164
+ """Return the active configuration, resolving the key path on first read.
165
+
166
+ Precedence: an explicit ``configure()`` call (already on ``_config``) wins;
167
+ otherwise ``MIMIRY_SSH_KEY``; otherwise the on-disk config file.
168
+ """
169
+ if _config.ssh_key_path is None:
170
+ env_key = os.environ.get("MIMIRY_SSH_KEY")
171
+ if env_key:
172
+ _config.ssh_key_path = Path(env_key).expanduser()
173
+ else:
174
+ _config.ssh_key_path = read_key_path() # may stay None
175
+ if "MIMIRY_API_BASE" in os.environ:
176
+ _config.api_base = os.environ["MIMIRY_API_BASE"].rstrip("/")
177
+ return _config
@@ -163,8 +163,11 @@ def build_bootstrap_script(image_install_prefix: str = "") -> str:
163
163
  # this is a single-purpose container with a fresh root filesystem — there's
164
164
  # no system Python to break.
165
165
  parts: list[str] = ["set -e"]
166
- if image_install_prefix:
167
- parts.append(image_install_prefix)
166
+ # Ensure python3 + pip FIRST — before the image's install prefix, which often
167
+ # needs pip (e.g. Image.pip_install renders ``python3 -m pip install ...``).
168
+ # Running the prefix before this defeats the whole purpose: on a minimal image
169
+ # (nvidia/cuda runtime) the prefix's pip wouldn't exist yet and `set -e` would
170
+ # abort the container with exit 127 before anything else ran.
168
171
  parts.append(
169
172
  'if ! command -v python3 >/dev/null 2>&1; then '
170
173
  'DEBIAN_FRONTEND=noninteractive apt-get update -qq && '
@@ -180,6 +183,9 @@ def build_bootstrap_script(image_install_prefix: str = "") -> str:
180
183
  '--no-install-recommends python3-pip >/dev/null 2>&1; '
181
184
  'fi'
182
185
  )
186
+ # Now the image's own deps (apt/pip) — pip is guaranteed to exist by here.
187
+ if image_install_prefix:
188
+ parts.append(image_install_prefix)
183
189
  # Install cloudpickle eagerly in the shell so we can fail fast with apt-cache
184
190
  # already warm. ``--break-system-packages`` is harmless on older Ubuntu (pip
185
191
  # ignores it) and required on 24.04+.
@@ -197,3 +197,53 @@ def raise_if_failed(session_payload: dict, client: MimiryClient | None = None) -
197
197
  stop_reason=session_payload.get("stop_reason"),
198
198
  events=events,
199
199
  )
200
+
201
+
202
+ def raise_if_ended_before_result(
203
+ session_payload: dict, client: MimiryClient | None = None
204
+ ) -> None:
205
+ """Raise SessionFailed if the session reached **any** terminal state at a point
206
+ where the container was expected to still be running (e.g. blocking on the
207
+ result/done flag).
208
+
209
+ In v1 the container writes its result and then blocks until the SDK signals
210
+ done, so reaching ``terminated``/``completed``/``failed`` at the just-started
211
+ checkpoint means the command exited prematurely — almost always a bootstrap
212
+ failure (bad image, failed pip install, etc.). We surface the tail of the
213
+ container logs so the caller sees *why* instead of timing out on SSH.
214
+ """
215
+ state = _extract_state(session_payload)
216
+ if state not in TERMINAL_STATES:
217
+ return
218
+
219
+ session_id = session_payload.get("id", "?")
220
+ stop_reason = session_payload.get("stop_reason")
221
+
222
+ tail = ""
223
+ events = None
224
+ if client is not None:
225
+ try:
226
+ resp = client.get_logs(session_id, tail=50)
227
+ if resp.get("_status") == 200:
228
+ tail = (resp.get("logs") or "").strip()
229
+ except Exception:
230
+ pass
231
+ try:
232
+ events = fetch_events(client, session_id)
233
+ except Exception:
234
+ events = None
235
+
236
+ msg = (
237
+ f"session {session_id} ended in state={state} (stop_reason={stop_reason}) "
238
+ f"before the container produced a result — the command likely failed during "
239
+ f"startup"
240
+ )
241
+ if tail:
242
+ msg += f". Last container logs:\n{tail}"
243
+ raise SessionFailed(
244
+ msg,
245
+ session_id=session_id,
246
+ state=state,
247
+ stop_reason=stop_reason,
248
+ events=events,
249
+ )
@@ -4,9 +4,10 @@ A one-time interactive wizard for Mimiry's SSH-JWT auth (there is no API-key
4
4
  flow). The wizard:
5
5
 
6
6
  1. Generates an ed25519 key at ``~/.ssh/mimiry`` if one doesn't already exist.
7
- 2. Shows the public key and opens the portal so the user can register it
8
- (there is no key-registration API — registration is manual in the portal).
9
- 3. Writes ``MIMIRY_SSH_KEY`` to the user's shell rc file (with confirmation).
7
+ 2. Shows the public key so the user can register it in the portal (there is no
8
+ key-registration API — registration is manual).
9
+ 3. Saves the key path to the SDK config file so the SDK works immediately, and
10
+ also exports ``MIMIRY_SSH_KEY`` to the user's shell rc for shell/curl use.
10
11
  4. Runs a balance check to verify the whole chain end-to-end.
11
12
 
12
13
  Everything here is deliberately dependency-free (stdlib only) and degrades
@@ -19,12 +20,11 @@ from __future__ import annotations
19
20
  import os
20
21
  import subprocess
21
22
  import sys
22
- import webbrowser
23
23
  from pathlib import Path
24
24
 
25
25
  from mimiry._auth import get_token
26
26
  from mimiry._client import MimiryClient
27
- from mimiry._config import DEFAULT_API_BASE
27
+ from mimiry._config import DEFAULT_API_BASE, save_key_path
28
28
 
29
29
  DEFAULT_KEY_PATH = Path("~/.ssh/mimiry").expanduser()
30
30
 
@@ -103,12 +103,10 @@ def _register_key(pub_path: Path, api_base: str) -> None:
103
103
  print(" (Mimiry has no key-registration API yet — this step is manual.)")
104
104
 
105
105
  if _is_interactive():
106
- if _confirm("\n Open the portal in your browser now?", default=True):
107
- try:
108
- webbrowser.open(portal_url)
109
- except Exception:
110
- pass # headless / no browser — the URL is printed above anyway
111
- _prompt("\n Press Enter once the key is registered to continue...")
106
+ # Note: we intentionally do not auto-open a browser. `webbrowser.open`
107
+ # shells out to xdg-open on Linux/WSL, which errors noisily (or hangs)
108
+ # when no opener is installed. The URL above is copy-pasteable.
109
+ _prompt("\n Open the URL above, then press Enter once the key is registered...")
112
110
 
113
111
 
114
112
  # ────────────────────────── step 3: write shell rc ──────────────────────────
@@ -150,8 +148,8 @@ def _write_rc(key_path: Path) -> None:
150
148
  needs_nl = existing and not existing.endswith("\n")
151
149
  with rc_path.open("a") as fh:
152
150
  fh.write(("\n" if needs_nl else "") + f"\n{_RC_MARKER}\n{export_line}\n")
153
- print(f" Wrote MIMIRY_SSH_KEY to {rc_path}.")
154
- print(f" Restart your shell or run: source {rc_path}")
151
+ print(f" Also exported MIMIRY_SSH_KEY in {rc_path} (for shell/curl use).")
152
+ print(" That activates in new shells — no restart needed for the SDK itself.")
155
153
 
156
154
 
157
155
  # ────────────────────────── step 4: verify ──────────────────────────
@@ -195,10 +193,15 @@ def run_setup_wizard(
195
193
  _step(2, "Register your key in the portal")
196
194
  _register_key(pub, api_base)
197
195
 
198
- _step(3, "Persist MIMIRY_SSH_KEY")
199
- # Make the key visible to this process so the verification step works even
200
- # before the user reloads their shell.
196
+ _step(3, "Save configuration")
197
+ # Primary mechanism: write the key path to the SDK config file. The SDK
198
+ # reads this directly, so it works in *this* shell and every future one
199
+ # without a restart. (Make it visible to this process too, for the verify
200
+ # step below.)
201
201
  os.environ["MIMIRY_SSH_KEY"] = str(priv)
202
+ cfg_file = save_key_path(priv)
203
+ print(f" Saved key path to {cfg_file} (chmod 600) — the SDK uses this immediately.")
204
+ # Secondary convenience: export the env var for shell/curl workflows too.
202
205
  _write_rc(priv)
203
206
 
204
207
  _step(4, "Verify")
@@ -21,6 +21,7 @@ from pathlib import Path
21
21
  from typing import Any, Callable, Iterable
22
22
 
23
23
  from mimiry._auth import get_token
24
+ from mimiry._availability import preflight_gpu_availability
24
25
  from mimiry._client import MimiryClient
25
26
  from mimiry._config import get_config
26
27
  from mimiry._serialization import (
@@ -30,6 +31,7 @@ from mimiry._serialization import (
30
31
  payload_env_var,
31
32
  )
32
33
  from mimiry._session import (
34
+ raise_if_ended_before_result,
33
35
  raise_if_failed,
34
36
  wait_for_ssh_ready,
35
37
  wait_for_started_or_terminal,
@@ -215,6 +217,11 @@ def _run_remote(fn: Callable, cfg: FunctionConfig, args: tuple, kwargs: dict) ->
215
217
  print(f"[mimiry] {msg}", file=sys.stderr, flush=True)
216
218
 
217
219
  with MimiryClient(token) as client:
220
+ # Fail fast on an impossible gpu/provider combo before paying for a
221
+ # provisioning round-trip. Best-effort — a flaky availability endpoint
222
+ # won't block submission. See _availability.py.
223
+ preflight_gpu_availability(client, cfg.gpu, cfg.provider, cfg.location)
224
+
218
225
  session = client.create_session(session_payload)
219
226
  session_id = session["id"]
220
227
  _log(f"session {session_id} submitted")
@@ -223,7 +230,9 @@ def _run_remote(fn: Callable, cfg: FunctionConfig, args: tuple, kwargs: dict) ->
223
230
  ran_payload, _ = wait_for_started_or_terminal(
224
231
  client, session_id, run_config, on_state_change=lambda s: _log(f"state={s}")
225
232
  )
226
- raise_if_failed(ran_payload, client=client)
233
+ # If the container ended before we could attach, surface its logs now
234
+ # instead of blundering into a 300s SSH timeout.
235
+ raise_if_ended_before_result(ran_payload, client=client)
227
236
 
228
237
  _log("waiting for ssh.host to be populated")
229
238
  ssh_ready = wait_for_ssh_ready(client, session_id, run_config)
@@ -270,7 +279,7 @@ def _run_remote(fn: Callable, cfg: FunctionConfig, args: tuple, kwargs: dict) ->
270
279
  return parse_result(raw)
271
280
  except ResultParseError as e:
272
281
  raise ResultParseError(f"{e} (session {session_id})") from e
273
- except Exception as e:
282
+ except Exception:
274
283
  # Pull events for the failure narrative.
275
284
  try:
276
285
  final = client.get_session(session_id, events_tail=-1)
@@ -57,7 +57,15 @@ class Image:
57
57
  parts.append(f"apt-get update -qq && apt-get install -y -q {quoted} >/dev/null")
58
58
  if self._pip_packages:
59
59
  quoted = " ".join(shlex.quote(p) for p in self._pip_packages)
60
- parts.append(f"pip install --quiet --no-input {quoted}")
60
+ # Invoke pip via ``python3 -m pip`` (a bare ``pip`` is often absent on
61
+ # minimal images, e.g. nvidia/cuda runtimes). ``--break-system-packages``
62
+ # is required on Ubuntu 24.04+ (PEP 668) and ignored by older pip — the
63
+ # bootstrap installs into a single-purpose container, so there's no
64
+ # system Python to protect. The bootstrap guarantees python3 + pip exist
65
+ # before this prefix runs (see build_bootstrap_script ordering).
66
+ parts.append(
67
+ f"python3 -m pip install --break-system-packages --quiet --no-input {quoted}"
68
+ )
61
69
  return " && ".join(parts)
62
70
 
63
71
  @property
@@ -17,9 +17,15 @@ from datetime import datetime
17
17
  from pathlib import Path
18
18
 
19
19
  from mimiry._auth import get_token
20
+ from mimiry._availability import preflight_gpu_availability
20
21
  from mimiry._client import MimiryClient
21
22
  from mimiry._config import Config, get_config
22
- from mimiry._session import raise_if_failed, wait_for_ssh_ready, wait_for_started_or_terminal
23
+ from mimiry._session import (
24
+ raise_if_ended_before_result,
25
+ raise_if_failed,
26
+ wait_for_ssh_ready,
27
+ wait_for_started_or_terminal,
28
+ )
23
29
  from mimiry._ssh import (
24
30
  CONTAINER_HOLD_TIMEOUT_SECONDS,
25
31
  DONE_FLAG,
@@ -146,6 +152,10 @@ def run(
146
152
  print(f"[mimiry] {msg}", file=sys.stderr, flush=True)
147
153
 
148
154
  with MimiryClient(token) as client:
155
+ # Fail fast on an impossible gpu/provider combo before provisioning.
156
+ # Best-effort — see _availability.py.
157
+ preflight_gpu_availability(client, gpu, provider, location)
158
+
149
159
  session = client.create_session(payload)
150
160
  session_id = session["id"]
151
161
  _log(f"session {session_id} submitted")
@@ -154,7 +164,9 @@ def run(
154
164
  ran_payload, _ = wait_for_started_or_terminal(
155
165
  client, session_id, run_config, on_state_change=lambda s: _log(f"state={s}")
156
166
  )
157
- raise_if_failed(ran_payload, client=client)
167
+ # Surface a premature container exit (bad image / failed install) with
168
+ # its logs, rather than timing out on SSH afterwards.
169
+ raise_if_ended_before_result(ran_payload, client=client)
158
170
 
159
171
  _log("waiting for ssh.host to be populated")
160
172
  ssh_ready = wait_for_ssh_ready(client, session_id, run_config)