modal 1.6.5.dev3__py3-none-any.whl → 1.6.5.dev4__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.
modal/_audit_logs/list.py CHANGED
@@ -1,6 +1,7 @@
1
1
  # Copyright Modal Labs 2026
2
2
  from __future__ import annotations
3
3
 
4
+ import math
4
5
  from collections.abc import AsyncGenerator
5
6
  from contextlib import aclosing
6
7
 
@@ -50,6 +51,34 @@ async def _fetch_bucket(
50
51
  return entries
51
52
 
52
53
 
54
+ async def fetch_newest_audit_logs(
55
+ q: str,
56
+ oldest_ms: int,
57
+ newest_ms: int,
58
+ count: int,
59
+ *,
60
+ client: _Client | None = None,
61
+ config: api_pb2.AuditLogSettingsGetResponse,
62
+ ) -> list[api_pb2.AuditLogEntry]:
63
+ """Read the newest `count` entries in the range, oldest to newest.
64
+
65
+ A count larger than one page fetches only the newest buckets that cover it, concurrently.
66
+ """
67
+ if client is None:
68
+ client = await _Client.from_env()
69
+ if count <= config.page_size:
70
+ resp = await _rpcs.list_page(client, q, oldest_ms, newest_ms, count, config)
71
+ return list(reversed(resp.items))
72
+ buckets = await get_bucket_cursors(client, q, oldest_ms, newest_ms, config)
73
+ # Buckets are cut from the newest entry, so all but the oldest hold exactly `bucket_size` entries.
74
+ newest_buckets = buckets[-math.ceil(count / config.bucket_size) :]
75
+ entries: list[api_pb2.AuditLogEntry] = []
76
+ async with aclosing(_stream_buckets(client, q, oldest_ms, newest_ms, config, newest_buckets)) as stream:
77
+ async for entry in stream:
78
+ entries.append(entry)
79
+ return entries[-count:]
80
+
81
+
53
82
  async def fetch_audit_logs(
54
83
  q: str,
55
84
  oldest_ms: int,
@@ -68,7 +97,19 @@ async def fetch_audit_logs(
68
97
  if client is None:
69
98
  client = await _Client.from_env()
70
99
  buckets = await get_bucket_cursors(client, q, oldest_ms, newest_ms, config)
100
+ async with aclosing(_stream_buckets(client, q, oldest_ms, newest_ms, config, buckets)) as stream:
101
+ async for entry in stream:
102
+ yield entry
103
+
71
104
 
105
+ async def _stream_buckets(
106
+ client: _Client,
107
+ q: str,
108
+ oldest_ms: int,
109
+ newest_ms: int,
110
+ config: api_pb2.AuditLogSettingsGetResponse,
111
+ buckets: list[Bucket],
112
+ ) -> AsyncGenerator[api_pb2.AuditLogEntry]:
72
113
  async def bucket_stream() -> AsyncGenerator[Bucket]:
73
114
  for bucket in buckets:
74
115
  yield bucket
modal/_serialization.py CHANGED
@@ -378,16 +378,12 @@ def serialize_data_format(obj: Any, data_format: int) -> bytes:
378
378
  raise InvalidError("CBOR support requires the 'cbor2' package to be installed.")
379
379
  try:
380
380
  return cbor2.dumps(obj)
381
- except cbor2.CBOREncodeError:
382
- try:
383
- typename = f"{type(obj).__module__}.{type(obj).__name__}"
384
- except Exception:
385
- typename = str(type(obj))
381
+ except cbor2.CBOREncodeError as exc:
386
382
  raise SerializationError(
387
383
  # TODO (elias): add documentation link for more information on this
388
- f"Can not serialize type {typename} as cbor. If you need to use a custom data type, "
384
+ f"CBOR payload serialization failed: {exc}. If you need to use a custom data type, "
389
385
  "try to serialize it yourself e.g. by using pickle.dumps(my_data)"
390
- )
386
+ ) from exc
391
387
  else:
392
388
  raise InvalidError(f"Unknown data format {data_format!r}")
393
389
 
modal/_workspace.py CHANGED
@@ -1,8 +1,9 @@
1
1
  # Copyright Modal Labs 2025
2
2
  import builtins
3
3
  import warnings
4
- from collections.abc import Mapping
5
- from datetime import datetime, timezone
4
+ from collections.abc import AsyncGenerator, Mapping
5
+ from contextlib import aclosing
6
+ from datetime import datetime, timedelta, timezone
6
7
  from decimal import Decimal
7
8
  from typing import Optional
8
9
 
@@ -12,12 +13,16 @@ from modal.exception import DeprecationError, InvalidError, NotFoundError
12
13
  from modal.types import MemberTokenInfo, ServiceUserInfo
13
14
  from modal_proto import api_pb2
14
15
 
16
+ from ._audit_logs import _rpcs
17
+ from ._audit_logs.count import count_audit_logs
18
+ from ._audit_logs.list import fetch_audit_logs, fetch_newest_audit_logs
15
19
  from ._load_context import LoadContext
16
20
  from ._object import _Object
17
21
  from ._resolver import Resolver
18
- from ._utils.time_utils import is_utc_month_aligned, parse_billing_cycle, timestamp_to_localized_dt
22
+ from ._utils.time_utils import is_utc_month_aligned, locale_tz, parse_billing_cycle, timestamp_to_localized_dt
19
23
  from .client import _Client
20
24
  from .types import (
25
+ AuditEvent,
21
26
  BillingReportItem,
22
27
  ProxyTokenInfo,
23
28
  TokenData,
@@ -26,6 +31,9 @@ from .types import (
26
31
  WorkspaceSettings,
27
32
  )
28
33
 
34
+ _AUDIT_LOG_DEFAULT_LIMIT = 100
35
+ _AUDIT_LOG_DEFAULT_WINDOW = timedelta(days=7)
36
+
29
37
 
30
38
  def _member_role_from_proto(proto_value: int) -> str:
31
39
  match proto_value:
@@ -87,6 +95,11 @@ class _Workspace(_Object, type_prefixes=("ac",)):
87
95
  """Namespace with methods for managing the membership of a Workspace."""
88
96
  return _WorkspaceMembersManager(self)
89
97
 
98
+ @property
99
+ def audit_logs(self) -> "_WorkspaceAuditLogsManager":
100
+ """Namespace for reading [Workspace audit logs](https://modal.com/docs/guide/audit-logs)."""
101
+ return _WorkspaceAuditLogsManager(self)
102
+
90
103
  @staticmethod
91
104
  def from_context(*, client: Optional[_Client] = None) -> "_Workspace":
92
105
  """Look up the Workspace associated with the current context.
@@ -145,6 +158,157 @@ class _Workspace(_Object, type_prefixes=("ac",)):
145
158
  return _WorkspaceMemberTokenManager(self)
146
159
 
147
160
 
161
+ class _WorkspaceAuditLogsManager:
162
+ """mdmd:namespace"""
163
+
164
+ def __init__(self, workspace: _Workspace):
165
+ """mdmd:hidden"""
166
+ self._workspace = workspace
167
+
168
+ @staticmethod
169
+ def _range(since: datetime | None, until: datetime | None) -> tuple[int, int]:
170
+ until = until or datetime.now(timezone.utc)
171
+ if until.tzinfo is None:
172
+ until = until.replace(tzinfo=locale_tz())
173
+ until = until.astimezone(timezone.utc)
174
+ if since is None:
175
+ since = until - _AUDIT_LOG_DEFAULT_WINDOW
176
+ elif since.tzinfo is None:
177
+ since = since.replace(tzinfo=locale_tz())
178
+ since = since.astimezone(timezone.utc)
179
+ return int(since.timestamp() * 1000), int(until.timestamp() * 1000)
180
+
181
+ async def fetch(
182
+ self,
183
+ query: str = "",
184
+ *,
185
+ since: datetime | None = None,
186
+ until: datetime | None = None,
187
+ limit: int | None = None,
188
+ ) -> AsyncGenerator[AuditEvent, None]:
189
+ """Fetch the Workspace's audit events, oldest-first.
190
+
191
+ Audit events record the sensitive actions that change a Workspace's state: who did
192
+ what, when, to which resource, and from where. Reading them requires the Enterprise
193
+ plan and either a Workspace Owner or Manager role, or a role that grants audit log
194
+ read access. See [the guide](https://modal.com/docs/guide/audit-logs) for more
195
+ information.
196
+
197
+ With no arguments, return the latest 100 events in the past seven days,
198
+ ordered oldest-first. Workspaces with fewer than 100 events in that window
199
+ return only those events.
200
+
201
+ A `since` or `until` datetime without a timezone is treated as local time. The range
202
+ between them is limited by the server, currently to seven days.
203
+
204
+ Args:
205
+ query: Query selecting which events to return, e.g.
206
+ `action:environment.create -status:failure`. Defaults to an empty string,
207
+ which matches all events.
208
+ See the query guide [here](https://modal.com/docs/guide/audit-logs#filtering).
209
+ since: Inclusive start time. Defaults to seven days before `until`.
210
+ until: Exclusive end time. Defaults to now.
211
+ limit: Return the newest `limit` matching events in the interval; must be
212
+ positive if provided. Defaults to 100 when `since` is omitted, or no
213
+ limit (every event in the interval) when `since` is provided.
214
+
215
+ Examples:
216
+ ```python notest
217
+ from datetime import datetime, timezone
218
+
219
+ ws = modal.Workspace.from_context()
220
+ latest_events = list(ws.audit_logs.fetch()) # defaults to latest 100 from past week
221
+ latest_500_events = list(ws.audit_logs.fetch(limit=500)) # latest 500 from past week
222
+
223
+ # latest 100 environment creations from past week, excluding failed attempts
224
+ environment_creation_events = list(ws.audit_logs.fetch("action:environment.create -status:failure"))
225
+
226
+ # latest 100 environment creations or deletions from past week
227
+ environment_change_events = list(ws.audit_logs.fetch("action:(environment.create OR environment.delete)"))
228
+
229
+ # return every event in range
230
+ start = datetime(2026, 10, 1, tzinfo=timezone.utc)
231
+ end = datetime(2026, 10, 8, tzinfo=timezone.utc)
232
+ first_week_of_october_events = list(ws.audit_logs.fetch(since=start, until=end))
233
+ ```
234
+ """
235
+ oldest_ms, newest_ms = self._range(since, until)
236
+ if limit is not None and limit < 1:
237
+ raise InvalidError("limit must be positive.")
238
+ await self._workspace.hydrate()
239
+ client = self._workspace.client
240
+ config = await _rpcs.get_settings(client)
241
+ if since is None or limit is not None:
242
+ entries = await fetch_newest_audit_logs(
243
+ query, oldest_ms, newest_ms, limit or _AUDIT_LOG_DEFAULT_LIMIT, client=client, config=config
244
+ )
245
+ for entry in entries:
246
+ yield AuditEvent._from_proto(entry)
247
+ return
248
+ stream = fetch_audit_logs(
249
+ query,
250
+ oldest_ms,
251
+ newest_ms,
252
+ client=client,
253
+ config=config,
254
+ )
255
+ async with aclosing(stream):
256
+ async for entry in stream:
257
+ yield AuditEvent._from_proto(entry)
258
+
259
+ async def count(
260
+ self,
261
+ query: str = "",
262
+ *,
263
+ since: datetime,
264
+ until: datetime | None = None,
265
+ ) -> int:
266
+ """Count the Workspace's audit events.
267
+
268
+ Audit events record the sensitive actions that change a Workspace's state: who did
269
+ what, when, to which resource, and from where. Reading them requires the Enterprise
270
+ plan and either a Workspace Owner or Manager role, or a role that grants audit log
271
+ read access. See [the guide](https://modal.com/docs/guide/audit-logs) for more
272
+ information.
273
+
274
+ An explicit `since` is required to select the start of the time range.
275
+
276
+ A `since` or `until` datetime without a timezone is treated as local time. The range
277
+ between them is limited by the server, currently to seven days.
278
+
279
+ Args:
280
+ query: Query selecting which events to return, e.g.
281
+ `action:environment.create -status:failure`. Defaults to an empty string,
282
+ which matches all events.
283
+ See the query guide [here](https://modal.com/docs/guide/audit-logs#filtering).
284
+ since: Inclusive start time (required).
285
+ until: Exclusive end time. Defaults to now.
286
+
287
+ Examples:
288
+ ```python notest
289
+ from datetime import datetime, timedelta, timezone
290
+
291
+ ws = modal.Workspace.from_context()
292
+ start = datetime.now(timezone.utc) - timedelta(days=7)
293
+ past_week_count = ws.audit_logs.count(since=start)
294
+
295
+ # environments created or deleted in the past week
296
+ environment_change_count = ws.audit_logs.count(
297
+ "action:(environment.create OR environment.delete)", since=start
298
+ )
299
+
300
+ start = datetime(2026, 10, 1, tzinfo=timezone.utc)
301
+ end = datetime(2026, 10, 8, tzinfo=timezone.utc)
302
+ first_week_of_october_count = ws.audit_logs.count(since=start, until=end)
303
+ ```
304
+ """
305
+ oldest_ms, newest_ms = self._range(since, until)
306
+ await self._workspace.hydrate()
307
+ client = self._workspace.client
308
+ config = await _rpcs.get_settings(client)
309
+ return await count_audit_logs(client, query, oldest_ms, newest_ms, config)
310
+
311
+
148
312
  class _WorkspaceProxyTokenManager:
149
313
  """mdmd:namespace"""
150
314
 
modal/cli/volume.py CHANGED
@@ -24,8 +24,6 @@ volume_cli = ModalGroup(
24
24
  name="volume",
25
25
  help="""
26
26
  Read and edit `modal.Volume` volumes.
27
-
28
- Note: users of `modal.NetworkFileSystem` should use the `modal nfs` command instead.
29
27
  """,
30
28
  )
31
29
 
modal/client.pyi CHANGED
@@ -85,7 +85,7 @@ class _Client:
85
85
  server_url: str,
86
86
  client_type: int,
87
87
  credentials: typing.Optional[tuple[str, str]],
88
- version: str = "1.6.5.dev3",
88
+ version: str = "1.6.5.dev4",
89
89
  *,
90
90
  oauth_credentials: typing.Optional[_OAuthCredentials] = None,
91
91
  ):
@@ -310,7 +310,7 @@ class Client:
310
310
  server_url: str,
311
311
  client_type: int,
312
312
  credentials: typing.Optional[tuple[str, str]],
313
- version: str = "1.6.5.dev3",
313
+ version: str = "1.6.5.dev4",
314
314
  *,
315
315
  oauth_credentials: typing.Optional[_OAuthCredentials] = None,
316
316
  ):
modal/sandbox/_sandbox.py CHANGED
@@ -272,7 +272,9 @@ class _Sandbox(_Object, type_prefixes=("sb",)):
272
272
  proxy: Reference to a Modal Proxy to use in front of this Sandbox.
273
273
  include_oidc_identity_token:
274
274
  If True, the sandbox will receive a MODAL_IDENTITY_TOKEN env var for OIDC-based auth.
275
- readiness_probe: Probe used to determine when the sandbox has become ready.
275
+ readiness_probe:
276
+ Probe used to determine when the Sandbox is ready.
277
+ If not configured, the Sandbox is ready when it starts.
276
278
  verbose: Enable verbose logging for sandbox operations.
277
279
  experimental_options: Experimental options to pass to the sandbox.
278
280
  _experimental_enable_snapshot: Enable memory snapshots.
@@ -971,9 +973,10 @@ class _Sandbox(_Object, type_prefixes=("sb",)):
971
973
  await self._impl.wait(raise_on_termination)
972
974
 
973
975
  async def wait_until_ready(self, *, timeout: int = 300) -> None:
974
- """Wait for the Sandbox readiness probe to report that the Sandbox is ready.
976
+ """Wait until the Sandbox is ready.
975
977
 
976
- The Sandbox must be configured with a `readiness_probe` in order to use this method.
978
+ A Sandbox with a readiness probe is ready once the probe passes;
979
+ a Sandbox without one is ready once it starts.
977
980
 
978
981
  Args:
979
982
  timeout: Maximum time in seconds to wait for readiness.
@@ -812,7 +812,10 @@ class TaskCommandRouterClient:
812
812
  )
813
813
 
814
814
  async def sandbox_wait_until_ready(self, task_id: str, timeout: float) -> sr_pb2.SandboxWaitUntilReadyTcrResponse:
815
- """Wait until the sandbox's readiness probe reports ready.
815
+ """Wait until the Sandbox is ready.
816
+
817
+ A Sandbox with a readiness probe is ready once the probe passes;
818
+ a Sandbox without one is ready once it starts.
816
819
 
817
820
  Args:
818
821
  task_id: The task ID hosting the sandbox.
modal/sandbox/sandbox.pyi CHANGED
@@ -1421,7 +1421,9 @@ class Sandbox(modal.object.Object):
1421
1421
  proxy: Reference to a Modal Proxy to use in front of this Sandbox.
1422
1422
  include_oidc_identity_token:
1423
1423
  If True, the sandbox will receive a MODAL_IDENTITY_TOKEN env var for OIDC-based auth.
1424
- readiness_probe: Probe used to determine when the sandbox has become ready.
1424
+ readiness_probe:
1425
+ Probe used to determine when the Sandbox is ready.
1426
+ If not configured, the Sandbox is ready when it starts.
1425
1427
  verbose: Enable verbose logging for sandbox operations.
1426
1428
  experimental_options: Experimental options to pass to the sandbox.
1427
1429
  _experimental_enable_snapshot: Enable memory snapshots.
@@ -1546,7 +1548,9 @@ class Sandbox(modal.object.Object):
1546
1548
  proxy: Reference to a Modal Proxy to use in front of this Sandbox.
1547
1549
  include_oidc_identity_token:
1548
1550
  If True, the sandbox will receive a MODAL_IDENTITY_TOKEN env var for OIDC-based auth.
1549
- readiness_probe: Probe used to determine when the sandbox has become ready.
1551
+ readiness_probe:
1552
+ Probe used to determine when the Sandbox is ready.
1553
+ If not configured, the Sandbox is ready when it starts.
1550
1554
  verbose: Enable verbose logging for sandbox operations.
1551
1555
  experimental_options: Experimental options to pass to the sandbox.
1552
1556
  _experimental_enable_snapshot: Enable memory snapshots.
@@ -2528,9 +2532,10 @@ class Sandbox(modal.object.Object):
2528
2532
 
2529
2533
  class __wait_until_ready_spec(typing_extensions.Protocol):
2530
2534
  def __call__(self, /, *, timeout: int = 300) -> None:
2531
- """Wait for the Sandbox readiness probe to report that the Sandbox is ready.
2535
+ """Wait until the Sandbox is ready.
2532
2536
 
2533
- The Sandbox must be configured with a `readiness_probe` in order to use this method.
2537
+ A Sandbox with a readiness probe is ready once the probe passes;
2538
+ a Sandbox without one is ready once it starts.
2534
2539
 
2535
2540
  Args:
2536
2541
  timeout: Maximum time in seconds to wait for readiness.
@@ -2550,9 +2555,10 @@ class Sandbox(modal.object.Object):
2550
2555
  ...
2551
2556
 
2552
2557
  async def aio(self, /, *, timeout: int = 300) -> None:
2553
- """Wait for the Sandbox readiness probe to report that the Sandbox is ready.
2558
+ """Wait until the Sandbox is ready.
2554
2559
 
2555
- The Sandbox must be configured with a `readiness_probe` in order to use this method.
2560
+ A Sandbox with a readiness probe is ready once the probe passes;
2561
+ a Sandbox without one is ready once it starts.
2556
2562
 
2557
2563
  Args:
2558
2564
  timeout: Maximum time in seconds to wait for readiness.
modal/types.py CHANGED
@@ -2,6 +2,8 @@
2
2
  """Public data types returned by Modal APIs."""
3
3
 
4
4
  import enum
5
+ import ipaddress
6
+ import json
5
7
  from collections.abc import Iterator, Mapping
6
8
  from dataclasses import FrozenInstanceError, dataclass, field
7
9
  from datetime import datetime, timedelta, timezone
@@ -11,6 +13,74 @@ from typing import Any, Iterable, Literal, Optional, TypedDict
11
13
  from modal_proto import api_pb2
12
14
 
13
15
 
16
+ @dataclass(frozen=True)
17
+ class AuditEvent:
18
+ """An audit event. Metadata is the decoded JSON object, or the original text if it cannot be decoded."""
19
+
20
+ @dataclass(frozen=True)
21
+ class Actor:
22
+ """The actor responsible for an audit log event."""
23
+
24
+ type: str
25
+ id: str
26
+ name: str
27
+ email: str
28
+
29
+ @dataclass(frozen=True)
30
+ class Target:
31
+ """An object affected by an audit log event."""
32
+
33
+ type: str
34
+ id: str
35
+
36
+ @dataclass(frozen=True)
37
+ class Context:
38
+ """The workspace and request context of an audit log event."""
39
+
40
+ workspace_id: str
41
+ environment_id: str
42
+ source: str
43
+ ip_address: ipaddress.IPv4Address | ipaddress.IPv6Address | None
44
+ """The caller's IP address, or `None` if it was not recorded or could not be parsed."""
45
+ environment_name: str
46
+
47
+ id: str
48
+ timestamp: datetime
49
+ action: str
50
+ status: str
51
+ actor: Actor
52
+ targets: list[Target]
53
+ context: Context
54
+ metadata: dict[str, Any] | str
55
+
56
+ @classmethod
57
+ def _from_proto(cls, entry: api_pb2.AuditLogEntry) -> "AuditEvent":
58
+ try:
59
+ metadata = json.loads(entry.metadata_json) if entry.metadata_json else {}
60
+ except ValueError:
61
+ metadata = entry.metadata_json
62
+ try:
63
+ ip_address = ipaddress.ip_address(entry.context.ip_address)
64
+ except ValueError:
65
+ ip_address = None
66
+ return cls(
67
+ id=entry.id,
68
+ timestamp=entry.event_at_timestamp.ToDatetime(tzinfo=timezone.utc),
69
+ action=entry.action,
70
+ status=entry.status,
71
+ actor=cls.Actor(type=entry.actor.type, id=entry.actor.id, name=entry.actor.name, email=entry.actor.email),
72
+ targets=[cls.Target(type=t.type, id=t.id) for t in entry.targets],
73
+ context=cls.Context(
74
+ workspace_id=entry.context.workspace_id,
75
+ environment_id=entry.context.environment_id,
76
+ environment_name=entry.context.environment_name,
77
+ source=entry.context.source,
78
+ ip_address=ip_address,
79
+ ),
80
+ metadata=metadata,
81
+ )
82
+
83
+
14
84
  @dataclass(frozen=True)
15
85
  class TimeSeriesPoint:
16
86
  """A metric sample at a UTC bucket start. A missing observation has value None."""
modal/workspace.py CHANGED
@@ -1,11 +1,13 @@
1
1
  # Copyright Modal Labs 2025
2
2
  from ._utils.async_utils import synchronize_api
3
3
  from ._workspace import (
4
+ AuditEvent,
4
5
  ProxyTokenInfo,
5
6
  TokenData,
6
7
  WorkspaceMemberInfo,
7
8
  WorkspaceSettings,
8
9
  _Workspace,
10
+ _WorkspaceAuditLogsManager,
9
11
  _WorkspaceBillingManager,
10
12
  _WorkspaceMembersManager,
11
13
  _WorkspaceMemberTokenManager,
@@ -15,6 +17,7 @@ from ._workspace import (
15
17
  )
16
18
 
17
19
  Workspace = synchronize_api(_Workspace, target_module=__name__)
20
+ WorkspaceAuditLogsManager = synchronize_api(_WorkspaceAuditLogsManager, target_module=__name__)
18
21
  WorkspaceMembersManager = synchronize_api(_WorkspaceMembersManager, target_module=__name__)
19
22
  WorkspaceBillingManager = synchronize_api(_WorkspaceBillingManager, target_module=__name__)
20
23
  WorkspaceProxyTokenManager = synchronize_api(_WorkspaceProxyTokenManager, target_module=__name__)
@@ -23,9 +26,11 @@ WorkspaceServiceUserManager = synchronize_api(_WorkspaceServiceUserManager, targ
23
26
  WorkspaceMemberTokenManager = synchronize_api(_WorkspaceMemberTokenManager, target_module=__name__)
24
27
 
25
28
  __all__ = [
29
+ "AuditEvent",
26
30
  "ProxyTokenInfo",
27
31
  "TokenData",
28
32
  "Workspace",
33
+ "WorkspaceAuditLogsManager",
29
34
  "WorkspaceMemberInfo",
30
35
  "WorkspaceMembersManager",
31
36
  "WorkspaceMemberTokenManager",