euler-connector 0.1.0__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 (39) hide show
  1. euler_connector-0.1.0/LICENSE +21 -0
  2. euler_connector-0.1.0/PKG-INFO +123 -0
  3. euler_connector-0.1.0/README.md +96 -0
  4. euler_connector-0.1.0/euler_connector/__init__.py +39 -0
  5. euler_connector-0.1.0/euler_connector/_log.py +33 -0
  6. euler_connector-0.1.0/euler_connector/channel.py +119 -0
  7. euler_connector-0.1.0/euler_connector/connector.py +181 -0
  8. euler_connector-0.1.0/euler_connector/env.py +130 -0
  9. euler_connector-0.1.0/euler_connector/envelope.py +115 -0
  10. euler_connector-0.1.0/euler_connector/identity.py +59 -0
  11. euler_connector-0.1.0/euler_connector/integrations/__init__.py +1 -0
  12. euler_connector-0.1.0/euler_connector/integrations/tqdm.py +57 -0
  13. euler_connector-0.1.0/euler_connector/progress.py +268 -0
  14. euler_connector-0.1.0/euler_connector/py.typed +0 -0
  15. euler_connector-0.1.0/euler_connector/throttle.py +39 -0
  16. euler_connector-0.1.0/euler_connector/transports/__init__.py +17 -0
  17. euler_connector-0.1.0/euler_connector/transports/base.py +35 -0
  18. euler_connector-0.1.0/euler_connector/transports/callback.py +24 -0
  19. euler_connector-0.1.0/euler_connector/transports/file.py +74 -0
  20. euler_connector-0.1.0/euler_connector/transports/http.py +213 -0
  21. euler_connector-0.1.0/euler_connector/transports/memory.py +39 -0
  22. euler_connector-0.1.0/euler_connector.egg-info/PKG-INFO +123 -0
  23. euler_connector-0.1.0/euler_connector.egg-info/SOURCES.txt +37 -0
  24. euler_connector-0.1.0/euler_connector.egg-info/dependency_links.txt +1 -0
  25. euler_connector-0.1.0/euler_connector.egg-info/requires.txt +7 -0
  26. euler_connector-0.1.0/euler_connector.egg-info/top_level.txt +1 -0
  27. euler_connector-0.1.0/pyproject.toml +41 -0
  28. euler_connector-0.1.0/setup.cfg +4 -0
  29. euler_connector-0.1.0/tests/test_channel.py +60 -0
  30. euler_connector-0.1.0/tests/test_connector.py +89 -0
  31. euler_connector-0.1.0/tests/test_env.py +56 -0
  32. euler_connector-0.1.0/tests/test_envelope.py +63 -0
  33. euler_connector-0.1.0/tests/test_file_transport.py +36 -0
  34. euler_connector-0.1.0/tests/test_http_transport.py +179 -0
  35. euler_connector-0.1.0/tests/test_identity.py +21 -0
  36. euler_connector-0.1.0/tests/test_progress.py +123 -0
  37. euler_connector-0.1.0/tests/test_protocol_contract.py +66 -0
  38. euler_connector-0.1.0/tests/test_throttle.py +25 -0
  39. euler_connector-0.1.0/tests/test_tqdm.py +31 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daniel Rothenpieler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: euler-connector
3
+ Version: 0.1.0
4
+ Summary: How the euler-* packages talk to euler-view: the launch environment, records, transports and structured progress
5
+ License-Expression: MIT
6
+ Keywords: euler-view,slurm,progress,telemetry,machine-learning
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Operating System :: POSIX
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: tqdm
22
+ Requires-Dist: tqdm>=4.62; extra == "tqdm"
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7; extra == "dev"
25
+ Requires-Dist: tqdm>=4.62; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # euler-connector
29
+
30
+ How the euler-* packages talk to [euler-view](https://github.com/d-rothen): one source of truth for the connection.
31
+
32
+ When euler-view launches a job, it tells the job's processes where they belong and how they may reach it. A package reports through `euler_connector` and never handles that connection itself.
33
+
34
+ - **Transports.** Records go to a file on the shared filesystem, which euler-view reads over SSH and which works on every cluster. Where compute nodes reach euler-view, they are also posted over HTTP.
35
+ - **Who speaks.** Only rank 0 speaks for a job. Forked workers stay silent.
36
+ - **Safety.** Nothing ever blocks or breaks the run: no exceptions, no unbounded queues, and a daemon thread for the network.
37
+ - **Dependencies.** None beyond the standard library (Python ≥ 3.9). `tqdm` is optional.
38
+
39
+ The first channel is **structured progress**. A record says what a counter counts (the whole run, one task, one epoch) and where the run is (task i of n, epoch e of E). euler-view can therefore show one overall percentage and ETA for training, inference and evaluation alike.
40
+
41
+ ## Install
42
+
43
+ ```sh
44
+ pip install euler-connector # or: euler-connector[tqdm]
45
+ ```
46
+
47
+ ## Report progress
48
+
49
+ ```python
50
+ from euler_connector import progress
51
+
52
+ p = progress.start("inference") # train | inference | eval | preprocess | other
53
+
54
+ # A tqdm bar that also reports (same arguments as tqdm, plus `scope`):
55
+ for sample in progress.tqdm(samples, desc="Inference", scope="overall", unit="sample"):
56
+ ...
57
+
58
+ p.close() # done; a failed run calls p.close(done=False)
59
+ ```
60
+
61
+ Without a bar:
62
+
63
+ ```python
64
+ p = progress.start("train")
65
+ for epoch in range(num_epochs):
66
+ p.set_epoch(epoch + 1, num_epochs) # 1-based
67
+ for step, batch in enumerate(loader, 1):
68
+ ...
69
+ p.update(step, len(loader), scope="epoch", unit="step")
70
+ p.close()
71
+ ```
72
+
73
+ Nested work, e.g. evaluating several datasets:
74
+
75
+ ```python
76
+ p = progress.start("eval")
77
+ for d, dataset in enumerate(datasets, 1):
78
+ p.set_level("dataset", d, len(datasets), dataset.name)
79
+ for t, task in enumerate(tasks_of(dataset), 1):
80
+ p.set_task(t, None, task.name) # the count may be unknown
81
+ for sample in progress.tqdm(task.samples, desc=task.label): # scope="task"
82
+ ...
83
+ ```
84
+
85
+ Records are written at most every 10 s. A new task, epoch or level is written at once, at most once per second.
86
+
87
+ ## The launch environment
88
+
89
+ euler-view sets these variables for every launch; outside euler-view nothing is sent.
90
+
91
+ | Variable | Meaning |
92
+ |---|---|
93
+ | `EULER_LAUNCH_ID` | the launch |
94
+ | `EULER_CONNECTOR_DIR` | where the file transport writes `<channel>.json`; it also holds the HTTP token |
95
+ | `EULER_VIEW_BASE_URL` | set only where compute nodes reach euler-view: enables HTTP |
96
+ | `EULER_CONNECTOR_MODE` | `auto` (default), `file`, `http`, `off` |
97
+ | `EULER_CONNECTOR_INTERVAL` | seconds between records of one channel (default 10) |
98
+
99
+ [`docs/protocol.md`](docs/protocol.md) is the full protocol: the envelope, both transports, throttling, the `progress` schema, and how to add a channel.
100
+
101
+ ## For more uses
102
+
103
+ Progress is one domain module on a general base:
104
+
105
+ - `Connector`: the process's connection, from the environment;
106
+ - channels: named, each with a versioned payload schema;
107
+ - transports: file, HTTP, memory, callback.
108
+
109
+ A new use (a heartbeat, a status, metrics from inference) adds a channel and a small module next to `progress`, and the package code stays one call. See "Adding a channel" in the protocol.
110
+
111
+ ```python
112
+ from euler_connector import connect
113
+
114
+ connector = connect()
115
+ print(connector.describe()) # enabled, launch, rank, transports and their health (no secrets)
116
+ ```
117
+
118
+ ## Development
119
+
120
+ ```sh
121
+ uv sync --extra dev
122
+ uv run pytest
123
+ ```
@@ -0,0 +1,96 @@
1
+ # euler-connector
2
+
3
+ How the euler-* packages talk to [euler-view](https://github.com/d-rothen): one source of truth for the connection.
4
+
5
+ When euler-view launches a job, it tells the job's processes where they belong and how they may reach it. A package reports through `euler_connector` and never handles that connection itself.
6
+
7
+ - **Transports.** Records go to a file on the shared filesystem, which euler-view reads over SSH and which works on every cluster. Where compute nodes reach euler-view, they are also posted over HTTP.
8
+ - **Who speaks.** Only rank 0 speaks for a job. Forked workers stay silent.
9
+ - **Safety.** Nothing ever blocks or breaks the run: no exceptions, no unbounded queues, and a daemon thread for the network.
10
+ - **Dependencies.** None beyond the standard library (Python ≥ 3.9). `tqdm` is optional.
11
+
12
+ The first channel is **structured progress**. A record says what a counter counts (the whole run, one task, one epoch) and where the run is (task i of n, epoch e of E). euler-view can therefore show one overall percentage and ETA for training, inference and evaluation alike.
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ pip install euler-connector # or: euler-connector[tqdm]
18
+ ```
19
+
20
+ ## Report progress
21
+
22
+ ```python
23
+ from euler_connector import progress
24
+
25
+ p = progress.start("inference") # train | inference | eval | preprocess | other
26
+
27
+ # A tqdm bar that also reports (same arguments as tqdm, plus `scope`):
28
+ for sample in progress.tqdm(samples, desc="Inference", scope="overall", unit="sample"):
29
+ ...
30
+
31
+ p.close() # done; a failed run calls p.close(done=False)
32
+ ```
33
+
34
+ Without a bar:
35
+
36
+ ```python
37
+ p = progress.start("train")
38
+ for epoch in range(num_epochs):
39
+ p.set_epoch(epoch + 1, num_epochs) # 1-based
40
+ for step, batch in enumerate(loader, 1):
41
+ ...
42
+ p.update(step, len(loader), scope="epoch", unit="step")
43
+ p.close()
44
+ ```
45
+
46
+ Nested work, e.g. evaluating several datasets:
47
+
48
+ ```python
49
+ p = progress.start("eval")
50
+ for d, dataset in enumerate(datasets, 1):
51
+ p.set_level("dataset", d, len(datasets), dataset.name)
52
+ for t, task in enumerate(tasks_of(dataset), 1):
53
+ p.set_task(t, None, task.name) # the count may be unknown
54
+ for sample in progress.tqdm(task.samples, desc=task.label): # scope="task"
55
+ ...
56
+ ```
57
+
58
+ Records are written at most every 10 s. A new task, epoch or level is written at once, at most once per second.
59
+
60
+ ## The launch environment
61
+
62
+ euler-view sets these variables for every launch; outside euler-view nothing is sent.
63
+
64
+ | Variable | Meaning |
65
+ |---|---|
66
+ | `EULER_LAUNCH_ID` | the launch |
67
+ | `EULER_CONNECTOR_DIR` | where the file transport writes `<channel>.json`; it also holds the HTTP token |
68
+ | `EULER_VIEW_BASE_URL` | set only where compute nodes reach euler-view: enables HTTP |
69
+ | `EULER_CONNECTOR_MODE` | `auto` (default), `file`, `http`, `off` |
70
+ | `EULER_CONNECTOR_INTERVAL` | seconds between records of one channel (default 10) |
71
+
72
+ [`docs/protocol.md`](docs/protocol.md) is the full protocol: the envelope, both transports, throttling, the `progress` schema, and how to add a channel.
73
+
74
+ ## For more uses
75
+
76
+ Progress is one domain module on a general base:
77
+
78
+ - `Connector`: the process's connection, from the environment;
79
+ - channels: named, each with a versioned payload schema;
80
+ - transports: file, HTTP, memory, callback.
81
+
82
+ A new use (a heartbeat, a status, metrics from inference) adds a channel and a small module next to `progress`, and the package code stays one call. See "Adding a channel" in the protocol.
83
+
84
+ ```python
85
+ from euler_connector import connect
86
+
87
+ connector = connect()
88
+ print(connector.describe()) # enabled, launch, rank, transports and their health (no secrets)
89
+ ```
90
+
91
+ ## Development
92
+
93
+ ```sh
94
+ uv sync --extra dev
95
+ uv run pytest
96
+ ```
@@ -0,0 +1,39 @@
1
+ """euler-connector — how the euler-* packages talk to euler-view.
2
+
3
+ One source of truth for the connection: the launch environment euler-view
4
+ sets, which process speaks for a job, the record envelope, and the
5
+ transports that carry records (a file on the shared filesystem everywhere;
6
+ HTTP where compute nodes reach the app). Domain modules build on it:
7
+
8
+ * ``euler_connector.progress`` — structured progress of a run (schema 1).
9
+
10
+ The protocol is in ``docs/protocol.md``.
11
+ """
12
+
13
+ from importlib.metadata import PackageNotFoundError as _PackageNotFoundError
14
+ from importlib.metadata import version as _version
15
+
16
+ try:
17
+ __version__ = _version("euler-connector")
18
+ except _PackageNotFoundError: # an unpacked source tree
19
+ __version__ = "0+unknown"
20
+
21
+ from .channel import StateChannel # noqa: E402
22
+ from .connector import Connector, connect, current, set_current # noqa: E402
23
+ from .env import LaunchEnvironment # noqa: E402
24
+ from .envelope import PROTOCOL_VERSION, Envelope, EnvelopeError # noqa: E402
25
+ from .identity import ProcessIdentity # noqa: E402
26
+
27
+ __all__ = [
28
+ "PROTOCOL_VERSION",
29
+ "Connector",
30
+ "Envelope",
31
+ "EnvelopeError",
32
+ "LaunchEnvironment",
33
+ "ProcessIdentity",
34
+ "StateChannel",
35
+ "__version__",
36
+ "connect",
37
+ "current",
38
+ "set_current",
39
+ ]
@@ -0,0 +1,33 @@
1
+ """Quiet, bounded diagnostics: the connector must never flood a job's log."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import threading
7
+ import time
8
+ from typing import Dict
9
+
10
+ logger = logging.getLogger("euler_connector")
11
+
12
+ _lock = threading.Lock()
13
+ _seen: Dict[str, float] = {}
14
+ #: The same message is repeated at most once per this many seconds.
15
+ REPEAT_AFTER_SEC = 300.0
16
+
17
+
18
+ def warn_once(message: str, *, key: str = "", repeat_after: float = REPEAT_AFTER_SEC) -> None:
19
+ """Log a warning, but the same ``key`` (default: the message) at most once per ``repeat_after`` seconds."""
20
+ marker = key or message
21
+ now = time.monotonic()
22
+ with _lock:
23
+ last = _seen.get(marker)
24
+ if last is not None and now - last < repeat_after:
25
+ return
26
+ _seen[marker] = now
27
+ logger.warning("euler-connector: %s", message)
28
+
29
+
30
+ def reset() -> None:
31
+ """Forget what was logged (tests)."""
32
+ with _lock:
33
+ _seen.clear()
@@ -0,0 +1,119 @@
1
+ """Channels: named streams of records, each with its own payload schema.
2
+
3
+ A ``StateChannel`` carries a value whose *latest* state is what matters
4
+ (progress today; a status or a heartbeat later). Further kinds (an event
5
+ channel that keeps every record) can sit next to it on the same transports.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import threading
12
+ import time
13
+ from typing import Any, Callable, Hashable, Mapping, Optional, Sequence
14
+
15
+ from ._log import warn_once
16
+ from .envelope import Envelope, utc_timestamp, validate_channel_name
17
+ from .identity import ProcessIdentity
18
+ from .throttle import Throttle
19
+ from .transports.base import Transport
20
+
21
+ _UNSET = object()
22
+
23
+
24
+ class StateChannel:
25
+ """The latest value of something, published to every transport, throttled.
26
+
27
+ ``publish(data, key=…)`` sends ``data`` when the throttle allows: at most
28
+ one record per interval, and at once (after a short gap) when ``key``
29
+ changes, i.e. at a boundary such as the next task or epoch. A value the
30
+ throttle holds back is not lost: ``close()`` writes the last one.
31
+
32
+ Thread-safe. A no-op once closed and in a forked child (the parent owns
33
+ the transports).
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ name: str,
39
+ *,
40
+ schema: int,
41
+ transports: Sequence[Transport],
42
+ identity: ProcessIdentity,
43
+ launch_id: Optional[str],
44
+ interval: float,
45
+ clock: Callable[[], float] = time.monotonic,
46
+ ) -> None:
47
+ self.name = validate_channel_name(name)
48
+ self.schema = schema
49
+ self._transports = list(transports)
50
+ self._identity = identity
51
+ self._launch_id = launch_id
52
+ self._throttle = Throttle(interval)
53
+ self._clock = clock
54
+ self._lock = threading.Lock()
55
+ self._seq = 0
56
+ self._key: Any = _UNSET
57
+ self._held: Optional[Mapping[str, Any]] = None
58
+ self._closed = False
59
+ self._pid = os.getpid()
60
+
61
+ @property
62
+ def enabled(self) -> bool:
63
+ return bool(self._transports) and not self._closed and os.getpid() == self._pid
64
+
65
+ @property
66
+ def interval(self) -> float:
67
+ return self._throttle.interval
68
+
69
+ def publish(self, data: Mapping[str, Any], *, key: Hashable = None, force: bool = False) -> bool:
70
+ """Offer the channel's new value; True when it was written now."""
71
+ if not self.enabled:
72
+ return False
73
+ try:
74
+ with self._lock:
75
+ if self._closed:
76
+ return False
77
+ now = self._clock()
78
+ boundary = key != self._key
79
+ self._key = key
80
+ if not self._throttle.should_write(now, boundary=boundary, force=force):
81
+ self._held = data
82
+ return False
83
+ self._write(data, now)
84
+ return True
85
+ except Exception as error: # noqa: BLE001 - publishing never breaks the run
86
+ warn_once(f"{self.name}: cannot publish: {error}", key=f"publish:{self.name}")
87
+ return False
88
+
89
+ def close(self, final: Optional[Mapping[str, Any]] = None) -> None:
90
+ """Write ``final`` (else the last value the throttle held back), then stop. Idempotent."""
91
+ if os.getpid() != self._pid:
92
+ return
93
+ with self._lock:
94
+ if self._closed:
95
+ return
96
+ data = final if final is not None else self._held
97
+ try:
98
+ if data is not None and self._transports:
99
+ self._write(data, self._clock())
100
+ except Exception as error: # noqa: BLE001
101
+ warn_once(f"{self.name}: cannot write the final record: {error}", key=f"close:{self.name}")
102
+ self._closed = True
103
+
104
+ def _write(self, data: Mapping[str, Any], now: float) -> None:
105
+ self._seq += 1
106
+ envelope = Envelope(
107
+ channel=self.name,
108
+ schema=self.schema,
109
+ seq=self._seq,
110
+ ts=utc_timestamp(),
111
+ data=dict(data),
112
+ launch_id=self._launch_id,
113
+ attempt=self._identity.attempt,
114
+ rank=self._identity.rank,
115
+ )
116
+ self._held = None
117
+ self._throttle.mark_written(now)
118
+ for transport in self._transports:
119
+ transport.publish(envelope)
@@ -0,0 +1,181 @@
1
+ """The connector: one per process, the single way an euler-* package talks to euler-view.
2
+
3
+ It reads the launch environment once, knows which process speaks (only
4
+ rank 0 does), owns the transports and hands out channels. Packages use a
5
+ domain module on top (``euler_connector.progress``) rather than channels.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import atexit
11
+ import os
12
+ import threading
13
+ import time
14
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence
15
+
16
+ from . import __version__
17
+ from .channel import StateChannel
18
+ from .env import LaunchEnvironment
19
+ from .identity import ProcessIdentity
20
+ from .transports.base import Transport
21
+ from .transports.file import FileTransport
22
+ from .transports.http import HttpTransport
23
+
24
+
25
+ class Connector:
26
+ def __init__(
27
+ self,
28
+ *,
29
+ environment: LaunchEnvironment,
30
+ identity: ProcessIdentity,
31
+ transports: Sequence[Transport],
32
+ clock: Callable[[], float] = time.monotonic,
33
+ ) -> None:
34
+ self.environment = environment
35
+ self.identity = identity
36
+ # Only the global rank 0 speaks for a job.
37
+ self._transports: List[Transport] = list(transports) if identity.is_primary else []
38
+ self._clock = clock
39
+ self._channels: Dict[str, StateChannel] = {}
40
+ self._lock = threading.Lock()
41
+ self._closed = False
42
+ self._pid = os.getpid()
43
+
44
+ @classmethod
45
+ def from_environment(
46
+ cls,
47
+ environ: Optional[Mapping[str, str]] = None,
48
+ *,
49
+ extra_transports: Sequence[Transport] = (),
50
+ ) -> "Connector":
51
+ """The transports the launch environment allows (none outside euler-view)."""
52
+ environment = LaunchEnvironment.from_environ(environ)
53
+ identity = ProcessIdentity.detect(environ)
54
+ transports: List[Transport] = []
55
+ if environment.mode != "off":
56
+ if environment.file_enabled and environment.connector_dir is not None:
57
+ transports.append(FileTransport(environment.connector_dir))
58
+ if environment.http_enabled and environment.base_url and environment.token:
59
+ transports.append(
60
+ HttpTransport(environment.base_url, environment.token, user_agent=f"euler-connector/{__version__}")
61
+ )
62
+ transports.extend(extra_transports)
63
+ return cls(environment=environment, identity=identity, transports=transports)
64
+
65
+ @classmethod
66
+ def disabled(cls) -> "Connector":
67
+ """A connector that accepts every call and sends nothing."""
68
+ return cls(environment=LaunchEnvironment(mode="off"), identity=ProcessIdentity.detect(), transports=[])
69
+
70
+ @property
71
+ def enabled(self) -> bool:
72
+ return bool(self._transports) and not self._closed and os.getpid() == self._pid
73
+
74
+ @property
75
+ def launch_id(self) -> Optional[str]:
76
+ return self.environment.launch_id
77
+
78
+ @property
79
+ def transports(self) -> tuple:
80
+ return tuple(self._transports)
81
+
82
+ def state_channel(self, name: str, *, schema: int = 1, interval: Optional[float] = None) -> StateChannel:
83
+ """The state channel ``name`` (one per name and process)."""
84
+ with self._lock:
85
+ channel = self._channels.get(name)
86
+ if channel is None:
87
+ channel = StateChannel(
88
+ name,
89
+ schema=schema,
90
+ transports=self._transports if self.enabled else [],
91
+ identity=self.identity,
92
+ launch_id=self.launch_id,
93
+ interval=self.environment.interval_sec if interval is None else interval,
94
+ clock=self._clock,
95
+ )
96
+ self._channels[name] = channel
97
+ elif channel.schema != schema:
98
+ raise ValueError(f"channel {name!r} is open with schema {channel.schema}, not {schema}")
99
+ return channel
100
+
101
+ def describe(self) -> Dict[str, Any]:
102
+ """What this connector does (diagnostics; no secrets)."""
103
+ return {
104
+ "version": __version__,
105
+ "enabled": self.enabled,
106
+ "launchId": self.launch_id,
107
+ "rank": self.identity.rank,
108
+ "attempt": self.identity.attempt,
109
+ "mode": self.environment.mode,
110
+ "transports": [{"name": t.name, "healthy": t.healthy} for t in self._transports],
111
+ "channels": sorted(self._channels),
112
+ }
113
+
114
+ def close(self, timeout: float = 2.0) -> None:
115
+ """Write every channel's last value and deliver what is left, waiting at most ``timeout`` seconds."""
116
+ if os.getpid() != self._pid:
117
+ return
118
+ with self._lock:
119
+ if self._closed:
120
+ return
121
+ channels = list(self._channels.values())
122
+ self._closed = True
123
+ for channel in channels:
124
+ channel.close()
125
+ deadline = self._clock() + max(0.0, timeout)
126
+ for transport in self._transports:
127
+ transport.close(max(0.0, deadline - self._clock()))
128
+
129
+
130
+ # ---------------------------------------------------------------------------
131
+ # The process's connector
132
+
133
+ _current: Optional[Connector] = None
134
+ _current_lock = threading.Lock()
135
+ #: True in a process forked from one that imported the connector (a DataLoader worker).
136
+ _forked_child = False
137
+
138
+
139
+ def connect(environ: Optional[Mapping[str, str]] = None) -> Connector:
140
+ """The process's connector, created from the environment on first use.
141
+
142
+ A forked child gets a disabled connector: its parent speaks for the job.
143
+ """
144
+ global _current
145
+ with _current_lock:
146
+ if _current is None:
147
+ _current = Connector.disabled() if _forked_child else Connector.from_environment(environ)
148
+ return _current
149
+
150
+
151
+ def current() -> Connector:
152
+ return connect()
153
+
154
+
155
+ def set_current(connector: Optional[Connector]) -> Optional[Connector]:
156
+ """Replace the process's connector (tests, applications that build their own); returns the previous one."""
157
+ global _current
158
+ with _current_lock:
159
+ previous, _current = _current, connector
160
+ return previous
161
+
162
+
163
+ def _close_current() -> None:
164
+ connector = _current
165
+ if connector is not None:
166
+ connector.close(timeout=2.0)
167
+
168
+
169
+ def _after_fork_in_child() -> None:
170
+ # A forked child (a DataLoader worker) must not reuse the parent's
171
+ # transports or threads, nor build its own: it stays disabled. The lock
172
+ # is replaced, as another thread may have held it at the fork.
173
+ global _current, _current_lock, _forked_child
174
+ _forked_child = True
175
+ _current_lock = threading.Lock()
176
+ _current = Connector.disabled()
177
+
178
+
179
+ atexit.register(_close_current)
180
+ if hasattr(os, "register_at_fork"):
181
+ os.register_at_fork(after_in_child=_after_fork_in_child)