fair-agentbox 0.0.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.
agentbox/__init__.py ADDED
@@ -0,0 +1,96 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AgentBox: shells, files, and containers on Monarch workers."""
16
+
17
+ from importlib.metadata import PackageNotFoundError, version
18
+
19
+ # Public names are imported from their owning modules so each symbol has a
20
+ # single home. All imports must follow ensure_short_tmpdir() above (noqa E402).
21
+ from agentbox.actors import (
22
+ AgentBoxManager, # noqa: E402
23
+ ApptainerNotFoundError,
24
+ ApptainerOptions,
25
+ await_for_pool,
26
+ BindMount,
27
+ Container,
28
+ ExecutionTarget,
29
+ HealthCheckResult,
30
+ LocalResourceManager,
31
+ Machine,
32
+ PoolExhaustedError,
33
+ PoolStatus,
34
+ ResourceHandle,
35
+ ResourceManager,
36
+ SlurmAllocation,
37
+ SlurmResourceManager,
38
+ wait_for_pool,
39
+ WorkerConnectionError,
40
+ )
41
+
42
+ # macOS: point TMPDIR at a short, $HOME-rooted dir before Monarch loads so its
43
+ # Unix-domain sockets stay under the SUN_LEN limit and temp dirs are visible
44
+ # inside the Lima VM. No-op on Linux. Must run before importing
45
+ # agentbox.actors (which imports monarch).
46
+ from agentbox.env import bound_native_heap, ensure_short_tmpdir
47
+ from agentbox.remote.file_transfer import FileCopyError # noqa: E402
48
+ from agentbox.remote.pty import PtyProcess # noqa: E402
49
+ from agentbox.remote.subprocess import ( # noqa: E402
50
+ CalledProcessError,
51
+ CompletedProcess,
52
+ Popen,
53
+ TimeoutExpired,
54
+ )
55
+
56
+
57
+ ensure_short_tmpdir()
58
+ bound_native_heap()
59
+
60
+
61
+ def _get_version() -> str:
62
+ try:
63
+ return version("fair-agentbox")
64
+ except PackageNotFoundError:
65
+ return "0.0.0"
66
+
67
+
68
+ __version__ = _get_version()
69
+
70
+ __all__ = [
71
+ "__version__",
72
+ "AgentBoxManager",
73
+ "ApptainerNotFoundError",
74
+ "ApptainerOptions",
75
+ "BindMount",
76
+ "CalledProcessError",
77
+ "CompletedProcess",
78
+ "Container",
79
+ "ExecutionTarget",
80
+ "FileCopyError",
81
+ "HealthCheckResult",
82
+ "LocalResourceManager",
83
+ "Machine",
84
+ "PoolExhaustedError",
85
+ "PoolStatus",
86
+ "Popen",
87
+ "PtyProcess",
88
+ "ResourceHandle",
89
+ "ResourceManager",
90
+ "SlurmAllocation",
91
+ "SlurmResourceManager",
92
+ "TimeoutExpired",
93
+ "WorkerConnectionError",
94
+ "await_for_pool",
95
+ "wait_for_pool",
96
+ ]
@@ -0,0 +1,70 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Resource manager actors and machine abstractions for distributed execution."""
16
+
17
+ from agentbox.actors.connector import (
18
+ connect,
19
+ Connector,
20
+ ConnectResult,
21
+ DefaultConnector,
22
+ WorkerConnectionError,
23
+ )
24
+ from agentbox.actors.container import (
25
+ ApptainerNotFoundError,
26
+ ApptainerOptions,
27
+ BindMount,
28
+ Container,
29
+ )
30
+ from agentbox.actors.machine import Machine
31
+ from agentbox.actors.manager import AgentBoxManager
32
+ from agentbox.actors.resource_managers import (
33
+ await_for_pool,
34
+ HealthCheckResult,
35
+ LocalResourceManager,
36
+ PoolExhaustedError,
37
+ PoolStatus,
38
+ ResourceHandle,
39
+ ResourceManager,
40
+ SlurmAllocation,
41
+ SlurmResourceManager,
42
+ wait_for_pool,
43
+ )
44
+ from agentbox.actors.target import ExecutionTarget
45
+
46
+
47
+ __all__ = [
48
+ "AgentBoxManager",
49
+ "ApptainerNotFoundError",
50
+ "ApptainerOptions",
51
+ "BindMount",
52
+ "ConnectResult",
53
+ "Connector",
54
+ "Container",
55
+ "DefaultConnector",
56
+ "ExecutionTarget",
57
+ "HealthCheckResult",
58
+ "LocalResourceManager",
59
+ "Machine",
60
+ "PoolExhaustedError",
61
+ "PoolStatus",
62
+ "ResourceHandle",
63
+ "ResourceManager",
64
+ "SlurmAllocation",
65
+ "SlurmResourceManager",
66
+ "WorkerConnectionError",
67
+ "await_for_pool",
68
+ "connect",
69
+ "wait_for_pool",
70
+ ]
@@ -0,0 +1,184 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Connector protocol and default implementation for ResourceHandle → ProcMesh bridging.
16
+
17
+ Provides a pluggable abstraction for connecting to acquired resources
18
+ without backend-specific knowledge. The :func:`connect` convenience
19
+ function covers the common case; custom :class:`Connector` implementations
20
+ can add TLS, retry logic, or alternative CA configurations. Connecting
21
+ yields a :class:`ConnectResult` carrying both the :class:`ProcMesh` and the
22
+ owned :class:`~monarch.actor.HostMesh` that backs it, so callers can tear the
23
+ connection down cleanly.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import logging
29
+ import time
30
+ from dataclasses import dataclass
31
+ from typing import Protocol, runtime_checkable, TYPE_CHECKING
32
+
33
+ from agentbox.actors.mesh_schema import make_name
34
+ from agentbox.actors.resource_managers import ResourceHandle
35
+ from monarch._src.actor.bootstrap import attach_to_workers
36
+ from monarch.actor import ProcMesh
37
+
38
+
39
+ if TYPE_CHECKING:
40
+ from monarch.actor import HostMesh
41
+
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ __all__ = [
46
+ "ConnectResult",
47
+ "Connector",
48
+ "DefaultConnector",
49
+ "WorkerConnectionError",
50
+ "connect",
51
+ ]
52
+
53
+
54
+ class WorkerConnectionError(RuntimeError):
55
+ """Raised when all connection attempts to worker addresses are exhausted."""
56
+
57
+ def __init__(
58
+ self, addresses: list[str], attempts: int, last_error: Exception
59
+ ) -> None:
60
+ self.addresses = addresses
61
+ self.attempts = attempts
62
+ self.last_error = last_error
63
+ super().__init__(
64
+ f"Failed to connect to workers at {addresses} after {attempts} attempt(s): {last_error}"
65
+ )
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class ConnectResult:
70
+ """A connected :class:`ProcMesh` plus the owned host mesh that backs it.
71
+
72
+ ``host_mesh`` is the OWNED :class:`~monarch.actor.HostMesh` returned by
73
+ ``attach_to_workers`` — the handle a caller must ``.stop()`` to tear the
74
+ connection down. Ownership is carried explicitly here because
75
+ ``proc_mesh.host_mesh`` is only a *slice* (reference) of that mesh, which
76
+ monarch refuses to stop (``"cannot stop `HostMesh` that is a reference
77
+ instead of owned"``). A connector that does not own a separate host mesh
78
+ (e.g. one spawning procs on ``this_host()``) may leave it ``None``.
79
+ """
80
+
81
+ proc_mesh: ProcMesh
82
+ host_mesh: "HostMesh | None" = None
83
+
84
+
85
+ @runtime_checkable
86
+ class Connector(Protocol):
87
+ """Protocol for connecting a :class:`ResourceHandle` to a :class:`ConnectResult`."""
88
+
89
+ def connect(self, handle: ResourceHandle) -> ConnectResult: ...
90
+
91
+
92
+ def _stop_host_mesh_quietly(host_mesh: object | None) -> None:
93
+ """Best-effort teardown of a host mesh that failed mid-connect (errors logged)."""
94
+ if host_mesh is None:
95
+ return
96
+ try:
97
+ host_mesh.stop().get() # type: ignore[attr-defined]
98
+ except Exception:
99
+ logger.debug("Error stopping partially-connected host mesh", exc_info=True)
100
+
101
+
102
+ class DefaultConnector:
103
+ """Default connector that bridges :class:`ResourceHandle` → :class:`ProcMesh`.
104
+
105
+ Uses ``handle.addresses`` (falling back to ``handle.hostnames``) to
106
+ call :func:`~monarch._src.actor.bootstrap.attach_to_workers`.
107
+
108
+ Args:
109
+ mesh_name: Name for the Monarch host mesh.
110
+ max_retries: Maximum number of connection attempts (default: 3).
111
+ retry_delay: Seconds between retries (default: 5).
112
+ """
113
+
114
+ def __init__(
115
+ self,
116
+ mesh_name: str | None = None,
117
+ max_retries: int = 3,
118
+ retry_delay: float = 5.0,
119
+ ) -> None:
120
+ if max_retries < 1:
121
+ raise ValueError("max_retries must be >= 1")
122
+ self._mesh_name = mesh_name or make_name("worker")
123
+ self._max_retries = max_retries
124
+ self._retry_delay = retry_delay
125
+
126
+ def connect(self, handle: ResourceHandle) -> ConnectResult:
127
+ """Connect to the workers described by *handle* and return a :class:`ConnectResult`.
128
+
129
+ Retries on **any** connection failure (not just ``ValueError``/``OSError``)
130
+ since Slurm workers may not be fully ready when their port is first
131
+ registered, and Monarch surfaces connection problems as its own exception
132
+ types. If ``attach_to_workers`` succeeds but ``spawn_procs`` fails, the
133
+ partially-connected host mesh is torn down before the next attempt so it
134
+ is not leaked.
135
+
136
+ The returned :class:`ConnectResult` carries the owned ``host_mesh`` so
137
+ the caller can stop it on teardown; see that class for why ownership
138
+ cannot be rederived from ``proc_mesh.host_mesh``.
139
+ """
140
+ addrs = handle.addresses or handle.hostnames
141
+ last_error: Exception | None = None
142
+
143
+ for attempt in range(1, self._max_retries + 1):
144
+ host_mesh = None
145
+ try:
146
+ logger.debug(
147
+ "Connection attempt %d/%d to %s",
148
+ attempt,
149
+ self._max_retries,
150
+ addrs,
151
+ )
152
+ host_mesh = attach_to_workers(
153
+ name=self._mesh_name,
154
+ ca="trust_all_connections",
155
+ workers=addrs,
156
+ )
157
+ proc_mesh = host_mesh.spawn_procs()
158
+ logger.info("Connected to workers at %s", addrs)
159
+ return ConnectResult(proc_mesh=proc_mesh, host_mesh=host_mesh)
160
+ except Exception as e:
161
+ last_error = e
162
+ # Record each failed attempt as a span event so retries are visible.
163
+ # Tear down a host mesh that attached but failed at spawn_procs,
164
+ # so a partial connection isn't leaked across retries / on failure.
165
+ _stop_host_mesh_quietly(host_mesh)
166
+ if attempt < self._max_retries:
167
+ logger.warning(
168
+ "Connection attempt %d/%d failed (%s), retrying in %.0fs...",
169
+ attempt,
170
+ self._max_retries,
171
+ e,
172
+ self._retry_delay,
173
+ )
174
+ time.sleep(self._retry_delay)
175
+
176
+ assert last_error is not None
177
+ raise WorkerConnectionError(
178
+ addrs, self._max_retries, last_error
179
+ ) from last_error
180
+
181
+
182
+ def connect(handle: ResourceHandle, *, mesh_name: str | None = None) -> ConnectResult:
183
+ """Convenience: connect to a :class:`ResourceHandle` using :class:`DefaultConnector`."""
184
+ return DefaultConnector(mesh_name=mesh_name).connect(handle)