modal 1.0.6.dev58__py3-none-any.whl → 1.2.3.dev7__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.

Potentially problematic release.


This version of modal might be problematic. Click here for more details.

Files changed (147) hide show
  1. modal/__main__.py +3 -4
  2. modal/_billing.py +80 -0
  3. modal/_clustered_functions.py +7 -3
  4. modal/_clustered_functions.pyi +4 -2
  5. modal/_container_entrypoint.py +41 -49
  6. modal/_functions.py +424 -195
  7. modal/_grpc_client.py +171 -0
  8. modal/_load_context.py +105 -0
  9. modal/_object.py +68 -20
  10. modal/_output.py +58 -45
  11. modal/_partial_function.py +36 -11
  12. modal/_pty.py +7 -3
  13. modal/_resolver.py +21 -35
  14. modal/_runtime/asgi.py +4 -3
  15. modal/_runtime/container_io_manager.py +301 -186
  16. modal/_runtime/container_io_manager.pyi +70 -61
  17. modal/_runtime/execution_context.py +18 -2
  18. modal/_runtime/execution_context.pyi +4 -1
  19. modal/_runtime/gpu_memory_snapshot.py +170 -63
  20. modal/_runtime/user_code_imports.py +28 -58
  21. modal/_serialization.py +57 -1
  22. modal/_utils/async_utils.py +33 -12
  23. modal/_utils/auth_token_manager.py +2 -5
  24. modal/_utils/blob_utils.py +110 -53
  25. modal/_utils/function_utils.py +49 -42
  26. modal/_utils/grpc_utils.py +80 -50
  27. modal/_utils/mount_utils.py +26 -1
  28. modal/_utils/name_utils.py +17 -3
  29. modal/_utils/task_command_router_client.py +536 -0
  30. modal/_utils/time_utils.py +34 -6
  31. modal/app.py +219 -83
  32. modal/app.pyi +229 -56
  33. modal/billing.py +5 -0
  34. modal/{requirements → builder}/2025.06.txt +1 -0
  35. modal/{requirements → builder}/PREVIEW.txt +1 -0
  36. modal/cli/_download.py +19 -3
  37. modal/cli/_traceback.py +3 -2
  38. modal/cli/app.py +4 -4
  39. modal/cli/cluster.py +15 -7
  40. modal/cli/config.py +5 -3
  41. modal/cli/container.py +7 -6
  42. modal/cli/dict.py +22 -16
  43. modal/cli/entry_point.py +12 -5
  44. modal/cli/environment.py +5 -4
  45. modal/cli/import_refs.py +3 -3
  46. modal/cli/launch.py +102 -5
  47. modal/cli/network_file_system.py +9 -13
  48. modal/cli/profile.py +3 -2
  49. modal/cli/programs/launch_instance_ssh.py +94 -0
  50. modal/cli/programs/run_jupyter.py +1 -1
  51. modal/cli/programs/run_marimo.py +95 -0
  52. modal/cli/programs/vscode.py +1 -1
  53. modal/cli/queues.py +57 -26
  54. modal/cli/run.py +58 -16
  55. modal/cli/secret.py +48 -22
  56. modal/cli/utils.py +3 -4
  57. modal/cli/volume.py +28 -25
  58. modal/client.py +13 -116
  59. modal/client.pyi +9 -91
  60. modal/cloud_bucket_mount.py +5 -3
  61. modal/cloud_bucket_mount.pyi +5 -1
  62. modal/cls.py +130 -102
  63. modal/cls.pyi +45 -85
  64. modal/config.py +29 -10
  65. modal/container_process.py +291 -13
  66. modal/container_process.pyi +95 -32
  67. modal/dict.py +282 -63
  68. modal/dict.pyi +423 -73
  69. modal/environments.py +15 -27
  70. modal/environments.pyi +5 -15
  71. modal/exception.py +8 -0
  72. modal/experimental/__init__.py +143 -38
  73. modal/experimental/flash.py +247 -78
  74. modal/experimental/flash.pyi +137 -9
  75. modal/file_io.py +14 -28
  76. modal/file_io.pyi +2 -2
  77. modal/file_pattern_matcher.py +25 -16
  78. modal/functions.pyi +134 -61
  79. modal/image.py +255 -86
  80. modal/image.pyi +300 -62
  81. modal/io_streams.py +436 -126
  82. modal/io_streams.pyi +236 -171
  83. modal/mount.py +62 -157
  84. modal/mount.pyi +45 -172
  85. modal/network_file_system.py +30 -53
  86. modal/network_file_system.pyi +16 -76
  87. modal/object.pyi +42 -8
  88. modal/parallel_map.py +821 -113
  89. modal/parallel_map.pyi +134 -0
  90. modal/partial_function.pyi +4 -1
  91. modal/proxy.py +16 -7
  92. modal/proxy.pyi +10 -2
  93. modal/queue.py +263 -61
  94. modal/queue.pyi +409 -66
  95. modal/runner.py +112 -92
  96. modal/runner.pyi +45 -27
  97. modal/sandbox.py +451 -124
  98. modal/sandbox.pyi +513 -67
  99. modal/secret.py +291 -67
  100. modal/secret.pyi +425 -19
  101. modal/serving.py +7 -11
  102. modal/serving.pyi +7 -8
  103. modal/snapshot.py +11 -8
  104. modal/token_flow.py +4 -4
  105. modal/volume.py +344 -98
  106. modal/volume.pyi +464 -68
  107. {modal-1.0.6.dev58.dist-info → modal-1.2.3.dev7.dist-info}/METADATA +9 -8
  108. modal-1.2.3.dev7.dist-info/RECORD +195 -0
  109. modal_docs/mdmd/mdmd.py +11 -1
  110. modal_proto/api.proto +399 -67
  111. modal_proto/api_grpc.py +241 -1
  112. modal_proto/api_pb2.py +1395 -1000
  113. modal_proto/api_pb2.pyi +1239 -79
  114. modal_proto/api_pb2_grpc.py +499 -4
  115. modal_proto/api_pb2_grpc.pyi +162 -14
  116. modal_proto/modal_api_grpc.py +175 -160
  117. modal_proto/sandbox_router.proto +145 -0
  118. modal_proto/sandbox_router_grpc.py +105 -0
  119. modal_proto/sandbox_router_pb2.py +149 -0
  120. modal_proto/sandbox_router_pb2.pyi +333 -0
  121. modal_proto/sandbox_router_pb2_grpc.py +203 -0
  122. modal_proto/sandbox_router_pb2_grpc.pyi +75 -0
  123. modal_proto/task_command_router.proto +144 -0
  124. modal_proto/task_command_router_grpc.py +105 -0
  125. modal_proto/task_command_router_pb2.py +149 -0
  126. modal_proto/task_command_router_pb2.pyi +333 -0
  127. modal_proto/task_command_router_pb2_grpc.py +203 -0
  128. modal_proto/task_command_router_pb2_grpc.pyi +75 -0
  129. modal_version/__init__.py +1 -1
  130. modal-1.0.6.dev58.dist-info/RECORD +0 -183
  131. modal_proto/modal_options_grpc.py +0 -3
  132. modal_proto/options.proto +0 -19
  133. modal_proto/options_grpc.py +0 -3
  134. modal_proto/options_pb2.py +0 -35
  135. modal_proto/options_pb2.pyi +0 -20
  136. modal_proto/options_pb2_grpc.py +0 -4
  137. modal_proto/options_pb2_grpc.pyi +0 -7
  138. /modal/{requirements → builder}/2023.12.312.txt +0 -0
  139. /modal/{requirements → builder}/2023.12.txt +0 -0
  140. /modal/{requirements → builder}/2024.04.txt +0 -0
  141. /modal/{requirements → builder}/2024.10.txt +0 -0
  142. /modal/{requirements → builder}/README.md +0 -0
  143. /modal/{requirements → builder}/base-images.json +0 -0
  144. {modal-1.0.6.dev58.dist-info → modal-1.2.3.dev7.dist-info}/WHEEL +0 -0
  145. {modal-1.0.6.dev58.dist-info → modal-1.2.3.dev7.dist-info}/entry_points.txt +0 -0
  146. {modal-1.0.6.dev58.dist-info → modal-1.2.3.dev7.dist-info}/licenses/LICENSE +0 -0
  147. {modal-1.0.6.dev58.dist-info → modal-1.2.3.dev7.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,536 @@
1
+ # Copyright Modal Labs 2025
2
+ import asyncio
3
+ import base64
4
+ import json
5
+ import ssl
6
+ import time
7
+ import urllib.parse
8
+ from typing import AsyncIterator, Optional
9
+
10
+ import grpclib.client
11
+ import grpclib.config
12
+ import grpclib.events
13
+ from grpclib import GRPCError, Status
14
+ from grpclib.exceptions import StreamTerminatedError
15
+
16
+ from modal.config import config, logger
17
+ from modal.exception import ExecTimeoutError
18
+ from modal_proto import api_pb2, task_command_router_pb2 as sr_pb2
19
+ from modal_proto.task_command_router_grpc import TaskCommandRouterStub
20
+
21
+ from .grpc_utils import RETRYABLE_GRPC_STATUS_CODES, connect_channel
22
+
23
+
24
+ def _b64url_decode(data: str) -> bytes:
25
+ """Decode a base64url string with missing padding tolerated."""
26
+ padding = "=" * (-len(data) % 4)
27
+ return base64.urlsafe_b64decode(data + padding)
28
+
29
+
30
+ def _parse_jwt_expiration(jwt_token: str) -> Optional[float]:
31
+ """Parse exp from a JWT without verification. Returns UNIX time seconds or None.
32
+
33
+ This is best-effort; if parsing fails or claim missing, returns None.
34
+ """
35
+ try:
36
+ parts = jwt_token.split(".")
37
+ if len(parts) != 3:
38
+ return None
39
+ payload_b = _b64url_decode(parts[1])
40
+ payload = json.loads(payload_b)
41
+ exp = payload.get("exp")
42
+ if isinstance(exp, (int, float)):
43
+ return float(exp)
44
+ except Exception:
45
+ # Avoid raising on malformed tokens; fall back to server-driven refresh logic.
46
+ logger.warning("Failed to parse JWT expiration")
47
+ return None
48
+ return None
49
+
50
+
51
+ async def call_with_retries_on_transient_errors(
52
+ func,
53
+ *,
54
+ base_delay_secs: float = 0.01,
55
+ delay_factor: float = 2,
56
+ max_retries: Optional[int] = 10,
57
+ ):
58
+ """Call func() with transient error retries and exponential backoff.
59
+
60
+ Authentication retries are expected to be handled by the caller.
61
+ """
62
+ delay_secs = base_delay_secs
63
+ num_retries = 0
64
+
65
+ async def sleep_and_update_delay_and_num_retries_remaining(e: Exception):
66
+ nonlocal delay_secs, num_retries
67
+ logger.debug(f"Retrying RPC with delay {delay_secs}s due to error: {e}")
68
+ await asyncio.sleep(delay_secs)
69
+ delay_secs *= delay_factor
70
+ num_retries += 1
71
+
72
+ while True:
73
+ try:
74
+ return await func()
75
+ except GRPCError as e:
76
+ if (max_retries is None or num_retries < max_retries) and e.status in RETRYABLE_GRPC_STATUS_CODES:
77
+ await sleep_and_update_delay_and_num_retries_remaining(e)
78
+ else:
79
+ raise e
80
+ except AttributeError as e:
81
+ # StreamTerminatedError are not properly raised in grpclib<=0.4.7
82
+ # fixed in https://github.com/vmagamedov/grpclib/issues/185
83
+ # TODO: update to newer version (>=0.4.8) once stable
84
+ if (max_retries is None or num_retries < max_retries) and "_write_appdata" in str(e):
85
+ await sleep_and_update_delay_and_num_retries_remaining(e)
86
+ else:
87
+ raise e
88
+ except StreamTerminatedError as e:
89
+ if max_retries is None or num_retries < max_retries:
90
+ await sleep_and_update_delay_and_num_retries_remaining(e)
91
+ else:
92
+ raise e
93
+ except (OSError, asyncio.TimeoutError) as e:
94
+ if max_retries is None or num_retries < max_retries:
95
+ await sleep_and_update_delay_and_num_retries_remaining(e)
96
+ else:
97
+ raise ConnectionError(str(e))
98
+
99
+
100
+ async def fetch_command_router_access(server_client, task_id: str) -> api_pb2.TaskGetCommandRouterAccessResponse:
101
+ """Fetch direct command router access info from Modal server."""
102
+ return await server_client.stub.TaskGetCommandRouterAccess(
103
+ api_pb2.TaskGetCommandRouterAccessRequest(task_id=task_id),
104
+ )
105
+
106
+
107
+ class TaskCommandRouterClient:
108
+ """
109
+ Client used to talk directly to TaskCommandRouter service on worker hosts.
110
+
111
+ A new instance should be created per task.
112
+ """
113
+
114
+ @classmethod
115
+ async def try_init(
116
+ cls,
117
+ server_client,
118
+ task_id: str,
119
+ ) -> Optional["TaskCommandRouterClient"]:
120
+ """Attempt to initialize a TaskCommandRouterClient by fetching direct access.
121
+
122
+ Returns None if command router access is not enabled (FAILED_PRECONDITION).
123
+ """
124
+ try:
125
+ resp = await fetch_command_router_access(server_client, task_id)
126
+ except GRPCError as exc:
127
+ if exc.status == Status.FAILED_PRECONDITION:
128
+ logger.debug(f"Command router access is not enabled for task {task_id}")
129
+ return None
130
+ raise
131
+
132
+ logger.debug(f"Using command router access for task {task_id}")
133
+
134
+ # Build and connect a channel to the task command router now that we have access info.
135
+ o = urllib.parse.urlparse(resp.url)
136
+ if o.scheme != "https":
137
+ raise ValueError(f"Task router URL must be https, got: {resp.url}")
138
+
139
+ host, _, port_str = o.netloc.partition(":")
140
+ port = int(port_str) if port_str else 443
141
+ ssl_context = ssl.create_default_context()
142
+
143
+ # Allow insecure TLS when explicitly enabled via config.
144
+ if config["task_command_router_insecure"]:
145
+ logger.warning("Using insecure TLS for task command router due to MODAL_TASK_COMMAND_ROUTER_INSECURE")
146
+ ssl_context.check_hostname = False
147
+ ssl_context.verify_mode = ssl.CERT_NONE
148
+
149
+ channel = grpclib.client.Channel(
150
+ host,
151
+ port,
152
+ ssl=ssl_context,
153
+ config=grpclib.config.Configuration(
154
+ http2_connection_window_size=64 * 1024 * 1024, # 64 MiB
155
+ http2_stream_window_size=64 * 1024 * 1024, # 64 MiB
156
+ ),
157
+ )
158
+
159
+ await connect_channel(channel)
160
+
161
+ return cls(server_client, task_id, resp.url, resp.jwt, channel)
162
+
163
+ def __init__(
164
+ self,
165
+ server_client,
166
+ task_id: str,
167
+ server_url: str,
168
+ jwt: str,
169
+ channel: grpclib.client.Channel,
170
+ *,
171
+ stream_stdio_retry_delay_secs: float = 0.01,
172
+ stream_stdio_retry_delay_factor: float = 2,
173
+ stream_stdio_max_retries: int = 10,
174
+ ) -> None:
175
+ """Callers should not use this directly. Use TaskCommandRouterClient.try_init() instead."""
176
+ # Attach bearer token on all requests to the worker-side router service.
177
+ self._server_client = server_client
178
+ self._task_id = task_id
179
+ self._server_url = server_url
180
+ self._jwt = jwt
181
+ self._channel = channel
182
+ # Retry configuration for stdio streaming
183
+ self.stream_stdio_retry_delay_secs = stream_stdio_retry_delay_secs
184
+ self.stream_stdio_retry_delay_factor = stream_stdio_retry_delay_factor
185
+ self.stream_stdio_max_retries = stream_stdio_max_retries
186
+
187
+ # JWT refresh coordination
188
+ self._jwt_exp: Optional[float] = _parse_jwt_expiration(jwt)
189
+ self._jwt_refresh_lock = asyncio.Lock()
190
+ self._jwt_refresh_event = asyncio.Event()
191
+ self._closed = False
192
+
193
+ # Start background task to eagerly refresh JWT 30s before expiration.
194
+ self._jwt_refresh_task = asyncio.create_task(self._jwt_refresh_loop())
195
+
196
+ async def send_request(event: grpclib.events.SendRequest) -> None:
197
+ # This will get the most recent JWT for every request. No need to
198
+ # lock _jwt_refresh_lock: reads and writes happen on the
199
+ # single-threaded event loop and variable assignment is atomic.
200
+ event.metadata["authorization"] = f"Bearer {self._jwt}"
201
+
202
+ grpclib.events.listen(self._channel, grpclib.events.SendRequest, send_request)
203
+
204
+ self._stub = TaskCommandRouterStub(self._channel)
205
+
206
+ def __del__(self) -> None:
207
+ """Clean up the client when it's garbage collected."""
208
+ if self._closed:
209
+ return
210
+
211
+ self._jwt_refresh_task.cancel()
212
+
213
+ try:
214
+ self._channel.close()
215
+ except Exception:
216
+ pass
217
+
218
+ async def close(self) -> None:
219
+ """Close the client and stop the background JWT refresh task."""
220
+ if self._closed:
221
+ return
222
+
223
+ self._closed = True
224
+ self._jwt_refresh_task.cancel()
225
+ try:
226
+ logger.debug(f"Waiting for JWT refresh task to complete for exec with task ID {self._task_id}")
227
+ await self._jwt_refresh_task
228
+ except asyncio.CancelledError:
229
+ pass
230
+ self._channel.close()
231
+
232
+ async def exec_start(self, request: sr_pb2.TaskExecStartRequest) -> sr_pb2.TaskExecStartResponse:
233
+ """Start an exec'd command, properly retrying on transient errors."""
234
+ return await call_with_retries_on_transient_errors(
235
+ lambda: self._call_with_auth_retry(self._stub.TaskExecStart, request)
236
+ )
237
+
238
+ async def exec_stdio_read(
239
+ self,
240
+ task_id: str,
241
+ exec_id: str,
242
+ # Quotes around the type required for protobuf 3.19.
243
+ file_descriptor: "api_pb2.FileDescriptor.ValueType",
244
+ deadline: Optional[float] = None,
245
+ ) -> AsyncIterator[sr_pb2.TaskExecStdioReadResponse]:
246
+ """Stream stdout/stderr batches from the task, properly retrying on transient errors.
247
+
248
+ Args:
249
+ task_id: The task ID of the task running the exec'd command.
250
+ exec_id: The execution ID of the command to read from.
251
+ file_descriptor: The file descriptor to read from.
252
+ deadline: The deadline by which all output must be streamed. If
253
+ None, wait forever. If the deadline is exceeded, raises an
254
+ ExecTimeoutError.
255
+ Returns:
256
+ AsyncIterator[sr_pb2.TaskExecStdioReadResponse]: A stream of stdout/stderr batches.
257
+ Raises:
258
+ ExecTimeoutError: If the deadline is exceeded.
259
+ Other errors: If retries are exhausted on transient errors or if there's an error
260
+ from the RPC itself.
261
+ """
262
+ if file_descriptor == api_pb2.FILE_DESCRIPTOR_STDOUT:
263
+ sr_fd = sr_pb2.TASK_EXEC_STDIO_FILE_DESCRIPTOR_STDOUT
264
+ elif file_descriptor == api_pb2.FILE_DESCRIPTOR_STDERR:
265
+ sr_fd = sr_pb2.TASK_EXEC_STDIO_FILE_DESCRIPTOR_STDERR
266
+ elif file_descriptor == api_pb2.FILE_DESCRIPTOR_INFO or file_descriptor == api_pb2.FILE_DESCRIPTOR_UNSPECIFIED:
267
+ raise ValueError(f"Unsupported file descriptor: {file_descriptor}")
268
+ else:
269
+ raise ValueError(f"Invalid file descriptor: {file_descriptor}")
270
+
271
+ async for item in self._stream_stdio(task_id, exec_id, sr_fd, deadline):
272
+ yield item
273
+
274
+ async def exec_stdin_write(
275
+ self, task_id: str, exec_id: str, offset: int, data: bytes, eof: bool
276
+ ) -> sr_pb2.TaskExecStdinWriteResponse:
277
+ """Write to the stdin stream of an exec'd command, properly retrying on transient errors.
278
+
279
+ Args:
280
+ task_id: The task ID of the task running the exec'd command.
281
+ exec_id: The execution ID of the command to write to.
282
+ offset: The offset to start writing to.
283
+ data: The data to write to the stdin stream.
284
+ eof: Whether to close the stdin stream after writing the data.
285
+ Raises:
286
+ Other errors: If retries are exhausted on transient errors or if there's an error
287
+ from the RPC itself.
288
+ """
289
+ request = sr_pb2.TaskExecStdinWriteRequest(task_id=task_id, exec_id=exec_id, offset=offset, data=data, eof=eof)
290
+ return await call_with_retries_on_transient_errors(
291
+ lambda: self._call_with_auth_retry(self._stub.TaskExecStdinWrite, request)
292
+ )
293
+
294
+ async def exec_poll(
295
+ self, task_id: str, exec_id: str, deadline: Optional[float] = None
296
+ ) -> sr_pb2.TaskExecPollResponse:
297
+ """Poll for the exit status of an exec'd command, properly retrying on transient errors.
298
+
299
+ Args:
300
+ task_id: The task ID of the task running the exec'd command.
301
+ exec_id: The execution ID of the command to poll on.
302
+ Returns:
303
+ sr_pb2.TaskExecPollResponse: The exit status of the command if it has completed.
304
+
305
+ Raises:
306
+ ExecTimeoutError: If the deadline is exceeded.
307
+ Other errors: If retries are exhausted on transient errors or if there's an error
308
+ from the RPC itself.
309
+ """
310
+ request = sr_pb2.TaskExecPollRequest(task_id=task_id, exec_id=exec_id)
311
+ # The timeout here is really a backstop in the event of a hang contacting
312
+ # the command router. Poll should usually be instantaneous.
313
+ timeout = deadline - time.monotonic() if deadline is not None else None
314
+ if timeout is not None and timeout <= 0:
315
+ raise ExecTimeoutError(f"Deadline exceeded while polling for exec {exec_id}")
316
+ try:
317
+ return await asyncio.wait_for(
318
+ call_with_retries_on_transient_errors(
319
+ lambda: self._call_with_auth_retry(self._stub.TaskExecPoll, request)
320
+ ),
321
+ timeout=timeout,
322
+ )
323
+ except asyncio.TimeoutError:
324
+ raise ExecTimeoutError(f"Deadline exceeded while polling for exec {exec_id}")
325
+
326
+ async def exec_wait(
327
+ self,
328
+ task_id: str,
329
+ exec_id: str,
330
+ deadline: Optional[float] = None,
331
+ ) -> sr_pb2.TaskExecWaitResponse:
332
+ """Wait for an exec'd command to exit and return the exit code, properly retrying on transient errors.
333
+
334
+ Args:
335
+ task_id: The task ID of the task running the exec'd command.
336
+ exec_id: The execution ID of the command to wait on.
337
+ Returns:
338
+ Optional[sr_pb2.TaskExecWaitResponse]: The exit code of the command.
339
+ Raises:
340
+ ExecTimeoutError: If the deadline is exceeded.
341
+ Other errors: If there's an error from the RPC itself.
342
+ """
343
+ request = sr_pb2.TaskExecWaitRequest(task_id=task_id, exec_id=exec_id)
344
+ timeout = deadline - time.monotonic() if deadline is not None else None
345
+ if timeout is not None and timeout <= 0:
346
+ raise ExecTimeoutError(f"Deadline exceeded while waiting for exec {exec_id}")
347
+ try:
348
+ return await asyncio.wait_for(
349
+ call_with_retries_on_transient_errors(
350
+ # We set a 60s timeout here to avoid waiting forever if there's an unanticipated hang
351
+ # due to a networking issue. call_with_retries_on_transient_errors will retry if the
352
+ # timeout is exceeded, so we'll retry every 60s until the command exits.
353
+ #
354
+ # Safety:
355
+ # * If just the task shuts down, the task command router will return a NOT_FOUND error,
356
+ # and we'll stop retrying.
357
+ # * If the task shut down AND the worker shut down, this could
358
+ # infinitely retry. For callers without an exec deadline, this
359
+ # could hang indefinitely.
360
+ lambda: self._call_with_auth_retry(self._stub.TaskExecWait, request, timeout=60),
361
+ base_delay_secs=1, # Retry after 1s since total time is expected to be long.
362
+ delay_factor=1, # Fixed delay.
363
+ max_retries=None, # Retry forever.
364
+ ),
365
+ timeout=timeout,
366
+ )
367
+ except asyncio.TimeoutError:
368
+ raise ExecTimeoutError(f"Deadline exceeded while waiting for exec {exec_id}")
369
+
370
+ async def _refresh_jwt(self) -> None:
371
+ """Refresh JWT from the server and update internal state.
372
+
373
+ Concurrency-safe: only one refresh runs at a time.
374
+ """
375
+ async with self._jwt_refresh_lock:
376
+ if self._closed:
377
+ return
378
+
379
+ # If the current JWT expiration is already far enough in the future, don't refresh.
380
+ if self._jwt_exp is not None and self._jwt_exp - time.time() > 30:
381
+ # This can happen if multiple concurrent requests to the task command router
382
+ # get UNAUTHENTICATED errors and all refresh at the same time - one of them
383
+ # will win and the others will not refresh.
384
+ logger.debug(
385
+ f"Skipping JWT refresh for exec with task ID {self._task_id} "
386
+ "because its expiration is already far enough in the future"
387
+ )
388
+ return
389
+
390
+ resp = await fetch_command_router_access(self._server_client, self._task_id)
391
+ # Ensure the server URL remains stable for the lifetime of this client.
392
+ assert resp.url == self._server_url, "Task router URL changed during session"
393
+ self._jwt = resp.jwt
394
+ self._jwt_exp = _parse_jwt_expiration(resp.jwt)
395
+ # Wake up the background loop to recompute its next sleep.
396
+ self._jwt_refresh_event.set()
397
+
398
+ async def _call_with_auth_retry(self, func, *args, **kwargs):
399
+ try:
400
+ return await func(*args, **kwargs)
401
+ except GRPCError as exc:
402
+ if exc.status == Status.UNAUTHENTICATED:
403
+ await self._refresh_jwt()
404
+ # Retry with the original arguments preserved
405
+ return await func(*args, **kwargs)
406
+ raise
407
+
408
+ async def _jwt_refresh_loop(self) -> None:
409
+ """Background task that refreshes JWT 30 seconds before expiration.
410
+
411
+ Uses an event to wake early when a manual refresh happens or token changes.
412
+ """
413
+ while not self._closed:
414
+ try:
415
+ exp = self._jwt_exp
416
+ now = time.time()
417
+ if exp is None:
418
+ # Unknown expiration: re-check periodically or until event wakes us.
419
+ sleep_s = 60.0
420
+ else:
421
+ refresh_at = exp - 30.0
422
+ sleep_s = max(refresh_at - now, 0.0)
423
+
424
+ self._jwt_refresh_event.clear()
425
+ if sleep_s > 0:
426
+ try:
427
+ logger.debug(f"Waiting for JWT refresh for {sleep_s}s for exec with task ID {self._task_id}")
428
+ # Wait until it's time to refresh, unless woken early.
429
+ await asyncio.wait_for(self._jwt_refresh_event.wait(), timeout=sleep_s)
430
+ logger.debug(f"Stopped waiting for JWT refresh for exec with task ID {self._task_id}")
431
+ # Event fired (e.g., token changed) -> recompute timings.
432
+ continue
433
+ except asyncio.TimeoutError:
434
+ logger.debug(f"Done waiting for JWT refresh for exec with task ID {self._task_id}")
435
+ pass
436
+
437
+ # Time to refresh.
438
+ logger.debug(f"Refreshing JWT for exec with task ID {self._task_id}")
439
+ await self._refresh_jwt()
440
+ except asyncio.CancelledError:
441
+ logger.debug(f"Cancelled JWT refresh loop for exec with task ID {self._task_id}")
442
+ break
443
+ except Exception as e:
444
+ # Exceptions here can stem from non-transient errors against the server sending
445
+ # the TaskGetCommandRouterAccess RPC, for instance, if the task has finished.
446
+ logger.debug(f"Background JWT refresh failed for exec with task ID {self._task_id}: {e}")
447
+ break
448
+
449
+ async def _stream_stdio(
450
+ self,
451
+ task_id: str,
452
+ exec_id: str,
453
+ # Quotes around the type required for protobuf 3.19.
454
+ file_descriptor: "sr_pb2.TaskExecStdioFileDescriptor.ValueType",
455
+ deadline: Optional[float] = None,
456
+ ) -> AsyncIterator[sr_pb2.TaskExecStdioReadResponse]:
457
+ """Stream stdio from the task, properly updating the offset and retrying on transient errors.
458
+ Raises ExecTimeoutError if the deadline is exceeded.
459
+ """
460
+ offset = 0
461
+ delay_secs = self.stream_stdio_retry_delay_secs
462
+ delay_factor = self.stream_stdio_retry_delay_factor
463
+ num_retries_remaining = self.stream_stdio_max_retries
464
+ num_auth_retries = 0
465
+
466
+ async def sleep_and_update_delay_and_num_retries_remaining(e: Exception):
467
+ nonlocal delay_secs, num_retries_remaining
468
+ logger.debug(f"Retrying stdio read with delay {delay_secs}s due to error: {e}")
469
+ if deadline is not None and deadline - time.monotonic() <= delay_secs:
470
+ raise ExecTimeoutError(f"Deadline exceeded while streaming stdio for exec {exec_id}")
471
+
472
+ await asyncio.sleep(delay_secs)
473
+ delay_secs *= delay_factor
474
+ num_retries_remaining -= 1
475
+
476
+ while True:
477
+ timeout = max(0, deadline - time.monotonic()) if deadline is not None else None
478
+ try:
479
+ stream = self._stub.TaskExecStdioRead.open(timeout=timeout)
480
+ async with stream as s:
481
+ req = sr_pb2.TaskExecStdioReadRequest(
482
+ task_id=task_id,
483
+ exec_id=exec_id,
484
+ offset=offset,
485
+ file_descriptor=file_descriptor,
486
+ )
487
+
488
+ # Scope auth retry strictly to the initial send (where headers/auth are sent).
489
+ try:
490
+ await s.send_message(req, end=True)
491
+ except GRPCError as exc:
492
+ if exc.status == Status.UNAUTHENTICATED and num_auth_retries < 1:
493
+ await self._refresh_jwt()
494
+ num_auth_retries += 1
495
+ continue
496
+ raise
497
+
498
+ # We successfully authenticated, reset the auth retry count.
499
+ num_auth_retries = 0
500
+
501
+ async for item in s:
502
+ # Reset retry backoff after any successful chunk.
503
+ delay_secs = self.stream_stdio_retry_delay_secs
504
+ offset += len(item.data)
505
+ yield item
506
+
507
+ # We successfully streamed all output.
508
+ return
509
+ except GRPCError as e:
510
+ if num_retries_remaining > 0 and e.status in RETRYABLE_GRPC_STATUS_CODES:
511
+ await sleep_and_update_delay_and_num_retries_remaining(e)
512
+ else:
513
+ raise e
514
+ except AttributeError as e:
515
+ # StreamTerminatedError are not properly raised in grpclib<=0.4.7
516
+ # fixed in https://github.com/vmagamedov/grpclib/issues/185
517
+ # TODO: update to newer version (>=0.4.8) once stable
518
+ if num_retries_remaining > 0 and "_write_appdata" in str(e):
519
+ await sleep_and_update_delay_and_num_retries_remaining(e)
520
+ else:
521
+ raise e
522
+ except StreamTerminatedError as e:
523
+ if num_retries_remaining > 0:
524
+ await sleep_and_update_delay_and_num_retries_remaining(e)
525
+ else:
526
+ raise e
527
+ except asyncio.TimeoutError as e:
528
+ if num_retries_remaining > 0:
529
+ await sleep_and_update_delay_and_num_retries_remaining(e)
530
+ else:
531
+ raise ConnectionError(str(e))
532
+ except OSError as e:
533
+ if num_retries_remaining > 0:
534
+ await sleep_and_update_delay_and_num_retries_remaining(e)
535
+ else:
536
+ raise ConnectionError(str(e))
@@ -1,15 +1,43 @@
1
1
  # Copyright Modal Labs 2025
2
- from datetime import datetime
3
- from typing import Optional
2
+ from datetime import datetime, tzinfo
3
+ from typing import Optional, Union
4
4
 
5
5
 
6
- def timestamp_to_local(ts: float, isotz: bool = True) -> Optional[str]:
6
+ def locale_tz() -> tzinfo:
7
+ return datetime.now().astimezone().tzinfo
8
+
9
+
10
+ def as_timestamp(arg: Optional[Union[datetime, str]]) -> float:
11
+ """Coerce a user-provided argument to a timestamp.
12
+
13
+ An argument provided without timezone information will be treated as local time.
14
+
15
+ When the argument is null, returns the current time.
16
+ """
17
+ if arg is None:
18
+ dt = datetime.now().astimezone()
19
+ elif isinstance(arg, str):
20
+ dt = datetime.fromisoformat(arg)
21
+ elif isinstance(arg, datetime):
22
+ dt = arg
23
+ else:
24
+ raise TypeError(f"Invalid argument: {arg}")
25
+
26
+ if dt.tzinfo is None:
27
+ dt = dt.replace(tzinfo=locale_tz())
28
+ return dt.timestamp()
29
+
30
+
31
+ def timestamp_to_localized_dt(ts: float) -> datetime:
32
+ return datetime.fromtimestamp(ts, tz=locale_tz())
33
+
34
+
35
+ def timestamp_to_localized_str(ts: float, isotz: bool = True) -> Optional[str]:
7
36
  if ts > 0:
8
- locale_tz = datetime.now().astimezone().tzinfo
9
- dt = datetime.fromtimestamp(ts, tz=locale_tz)
37
+ dt = timestamp_to_localized_dt(ts)
10
38
  if isotz:
11
39
  return dt.isoformat(sep=" ", timespec="seconds")
12
40
  else:
13
- return f"{datetime.strftime(dt, '%Y-%m-%d %H:%M')} {locale_tz.tzname(dt)}"
41
+ return f"{dt:%Y-%m-%d %H:%M %Z}"
14
42
  else:
15
43
  return None