dlboard-client 0.2.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.
dlboard/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """DLBoard main entrypoint."""
dlboard/_batching.py ADDED
@@ -0,0 +1,153 @@
1
+ """
2
+ Drain a queue into batches and ship each one somewhere that can fail.
3
+
4
+ Shared by the client's metric/artifact shipping processes (`dlboard_logger.py`) and every blob
5
+ artifact store's ref-ingest thread (`plugins/data_stores/_blob_store.py`) -- both batch items off a
6
+ queue towards a destination that can fail transiently (a server, a locked database), and both must
7
+ never lose a batch to a failure that a retry would have survived.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import random
14
+ import time
15
+ from queue import Empty
16
+ from typing import TYPE_CHECKING, NamedTuple, Protocol, TypeVar
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable
20
+ from multiprocessing.synchronize import Event as MPEvent
21
+
22
+ _log = logging.getLogger(__name__)
23
+
24
+ T = TypeVar("T")
25
+ """Pre-3.12 `TypeVar` style (the client's floor is 3.10): the kind of item `ship_batches` moves."""
26
+
27
+ _T_co = TypeVar("_T_co", covariant=True)
28
+ """`Receiver`'s own type parameter -- covariant, since it only ever appears in a return position."""
29
+
30
+ _MAX_BACKOFF_FACTOR: int = 6
31
+ """Caps retry backoff at `wait_sec * 2**6` (64x) -- a dead server shouldn't make the next retry wait
32
+ arbitrarily long, just long enough to stop hammering it."""
33
+
34
+ _JITTER_FRACTION: float = 0.25
35
+ """+/- this fraction of the computed backoff, so many shipping processes retrying the same outage
36
+ don't all land on the server in lockstep."""
37
+
38
+
39
+ class BatchParams(NamedTuple):
40
+ """How `ship_batches` batches, plus the events it reports through."""
41
+
42
+ flush_size: int
43
+ wait_sec: float
44
+ ready: MPEvent
45
+ flushed: MPEvent
46
+
47
+
48
+ class Receiver(Protocol[_T_co]):
49
+ """The one queue method `ship_batches` needs -- both `multiprocessing` and `queue` queues have it."""
50
+
51
+ def get(self, block: bool = True, timeout: float | None = None) -> _T_co: ... # noqa: FBT001, FBT002
52
+
53
+
54
+ def _split_oversized(
55
+ ship: Callable[[list[T]], None],
56
+ batch: list[T],
57
+ *,
58
+ is_permanent: Callable[[Exception], bool],
59
+ is_oversized: Callable[[Exception], bool],
60
+ ) -> list[T]:
61
+ """
62
+ Ship `batch` in two halves, recursing into a half that's still too large, down to one item each.
63
+
64
+ Returns whatever's left unshipped: a permanently-rejected chunk is dropped (and so absent from
65
+ the result), but one that fails for some other transient reason comes back in it, for
66
+ `ship_batches` to retry (at its own pace, with backoff) on a later pass -- never lost, and never
67
+ re-sent on top of a chunk that already landed. A chunk of exactly one item that's still too
68
+ large has nothing left to split into, so it's treated as permanent either way: resending the
69
+ same single oversized item can never succeed.
70
+ """
71
+ mid = len(batch) // 2
72
+ leftover: list[T] = []
73
+ for chunk in (batch[:mid], batch[mid:]):
74
+ try:
75
+ ship(chunk)
76
+ except Exception as exc: # noqa: BLE001 -- nothing may kill the shipping loop
77
+ if is_oversized(exc) and len(chunk) > 1:
78
+ leftover.extend(
79
+ _split_oversized(ship, chunk, is_permanent=is_permanent, is_oversized=is_oversized)
80
+ )
81
+ elif is_permanent(exc):
82
+ _log.exception("A sub-batch of %s was rejected, dropping it", len(chunk))
83
+ else:
84
+ leftover.extend(chunk) # transient; retry (with backoff) on a later pass
85
+ return leftover
86
+
87
+
88
+ def ship_batches(
89
+ q: Receiver[T | None],
90
+ ship: Callable[[list[T]], None],
91
+ params: BatchParams,
92
+ *,
93
+ is_permanent: Callable[[Exception], bool],
94
+ is_oversized: Callable[[Exception], bool] = lambda _exc: False,
95
+ ) -> None:
96
+ """
97
+ Forever drain `q` into batches, shipping one once it's full, `wait_sec` old, or a flush asks for it.
98
+
99
+ A batch whose failure `is_permanent` is dropped: resending it can never succeed, and keeping it
100
+ would wedge every later item behind it. A batch whose failure `is_oversized` is instead split in
101
+ half and each half attempted once right away (`_split_oversized`) -- resending the exact same
102
+ oversized batch could never succeed either, but a batch that only grew this large because the
103
+ server was briefly unreachable shouldn't be dropped just because it doesn't fit in one request
104
+ once it's reachable again. Any other failure is transient -- the batch is kept, keeps growing
105
+ with whatever arrives meanwhile, and is retried after an exponentially growing backoff (reset
106
+ the moment a batch ships successfully) rather than hammering a server that's still down. A
107
+ `None` queued in place of an item requests a flush, acknowledged (`params.flushed`) only once
108
+ everything queued before it is gone. Returns once `q` itself is closed (e.g. at interpreter
109
+ shutdown) -- nothing more can ever arrive through it.
110
+ """
111
+ params.ready.set()
112
+ batch: list[T] = []
113
+ flush_requested = False
114
+ last_attempt = time.perf_counter()
115
+ consecutive_failures = 0
116
+ while True:
117
+ try:
118
+ item = q.get(timeout=params.wait_sec / 10)
119
+ if item is None:
120
+ flush_requested = True
121
+ else:
122
+ batch.append(item)
123
+ except Empty:
124
+ pass
125
+ except (OSError, ValueError): # a closed `multiprocessing` queue raises one or the other
126
+ return
127
+ due = flush_requested or len(batch) >= params.flush_size
128
+ if batch and (due or time.perf_counter() - last_attempt > params.wait_sec):
129
+ try:
130
+ ship(batch)
131
+ batch = []
132
+ consecutive_failures = 0
133
+ except Exception as exc: # noqa: BLE001 -- nothing may kill the shipping loop
134
+ if is_oversized(exc) and len(batch) > 1:
135
+ _log.warning("A batch of %s was too large for one request, splitting it", len(batch))
136
+ batch = _split_oversized(
137
+ ship, batch, is_permanent=is_permanent, is_oversized=is_oversized
138
+ )
139
+ consecutive_failures = 0
140
+ elif is_permanent(exc):
141
+ _log.exception("A batch of %s was rejected, dropping it", len(batch))
142
+ batch = []
143
+ consecutive_failures = 0
144
+ else:
145
+ _log.exception("Failed to ship a batch of %s, retrying", len(batch))
146
+ backoff = params.wait_sec * 2 ** min(consecutive_failures, _MAX_BACKOFF_FACTOR)
147
+ jitter = backoff * _JITTER_FRACTION
148
+ time.sleep(backoff + random.uniform(-jitter, jitter))
149
+ consecutive_failures += 1
150
+ last_attempt = time.perf_counter()
151
+ if flush_requested and not batch:
152
+ flush_requested = False
153
+ params.flushed.set()
dlboard/_compat.py ADDED
@@ -0,0 +1,31 @@
1
+ """
2
+ Backports for stdlib `typing`/`enum` members not available on the client's floor (Python 3.10).
3
+
4
+ Nothing here is dlboard-specific; it exists only because the client supports 3.10+ while the
5
+ syntax/stdlib members below landed later. Every model/client module that needs one of these
6
+ imports it from here instead of `enum` directly, so there's exactly one place that cares which
7
+ Python version is actually running.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import TYPE_CHECKING
13
+
14
+ if TYPE_CHECKING:
15
+ # Pyright always sees the real `enum.StrEnum` -- this repo's own dev/CI env always has 3.12+.
16
+ # The try/except below is the runtime-only fallback, for an actual 3.10/3.11 interpreter.
17
+ from enum import StrEnum
18
+ else:
19
+ try:
20
+ from enum import StrEnum
21
+ except ImportError: # Python < 3.11 (PEP 663 landed in 3.11)
22
+ from enum import Enum
23
+
24
+ class StrEnum(str, Enum):
25
+ """A `str`-valued `Enum` whose `str()` is its value, not `ClassName.MEMBER`."""
26
+
27
+ def __str__(self) -> str:
28
+ return str(self.value)
29
+
30
+
31
+ __all__ = ["StrEnum"]
dlboard/_identity.py ADDED
@@ -0,0 +1,48 @@
1
+ """
2
+ Best-effort resolution of "who is running this" for attribution purposes.
3
+
4
+ This is an identity helper, not authentication -- nothing here is a security boundary, and nothing
5
+ here proves a caller actually is who they claim. It exists so a local, single-user dlboard install
6
+ can attribute projects/experiments/runs to *someone* with zero configuration, the same way `git`
7
+ picks up `user.name` from the environment. Used by both the client (`dlboard.client`, to label
8
+ what it logs) and the server (schema migrations, to pick a name for the one-time bootstrap admin).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import getpass
14
+
15
+ from pydantic_settings import BaseSettings
16
+ from structlog.stdlib import get_logger
17
+
18
+ _log = get_logger(__name__)
19
+
20
+ ANONYMOUS: str = "anonymous"
21
+
22
+
23
+ class _IdentitySettings(BaseSettings):
24
+ """Reads the `DLBOARD_USER` env var `resolve_username` checks first."""
25
+
26
+ dlboard_user: str = ""
27
+
28
+
29
+ def resolve_username() -> str:
30
+ """
31
+ Resolve a username via a best-effort chain: the `DLBOARD_USER` env var, then the OS login name, then `"anonymous"`.
32
+
33
+ Every step is wrapped so a failure (e.g. `getpass.getuser()` raising in a sandboxed container
34
+ with no passwd entry) falls through to the next step instead of raising.
35
+ """
36
+ env_value = _IdentitySettings().dlboard_user.strip()
37
+ if env_value:
38
+ return env_value
39
+
40
+ try:
41
+ os_username = getpass.getuser().strip()
42
+ except Exception: # noqa: BLE001
43
+ _log.debug("Could not resolve an OS username, falling back to %s", ANONYMOUS)
44
+ else:
45
+ if os_username:
46
+ return os_username
47
+
48
+ return ANONYMOUS
dlboard/_mp_context.py ADDED
@@ -0,0 +1,15 @@
1
+ """
2
+ Shared multiprocessing context for dlboard's background worker processes.
3
+
4
+ `DLBoardLogger` (client-side metric/artifact shipping) and `BlobArtifactStore` (server-side blob
5
+ writes) each spawn a worker process off a `multiprocessing.Queue`; both need the same "spawn"
6
+ context (never "fork", which can deadlock a process that already has threads running -- both of
7
+ these do, e.g. Flask's/Dash's request-handling threads on the server side). Sharing one context
8
+ instance keeps that choice in exactly one place instead of two independent literal `"spawn"` calls.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from multiprocessing import get_context
14
+
15
+ SPAWN_CONTEXT = get_context("spawn")
dlboard/_version.py ADDED
@@ -0,0 +1,17 @@
1
+ """
2
+ The single source of dlboard's version.
3
+
4
+ Both `client/pyproject.toml` and `server/pyproject.toml` read `__version__` from here via hatch's
5
+ dynamic `[tool.hatch.version]` (see their own `path` setting), instead of each hardcoding its own
6
+ `version` field -- which is how the two distributions drifted out of lockstep before this existed:
7
+ nothing kept `dlboard-client`'s version and `dlboard`'s `dlboard-client==...` pin pointed at the same
8
+ release. Bump this one file to cut a release; neither `pyproject.toml`'s `version` is ever edited
9
+ directly.
10
+
11
+ Also read at runtime -- `Identity.server_version` (see `dlboard._wire`) is what a client's `whoami`
12
+ handshake actually sees.
13
+ """
14
+
15
+ # No type annotation -- hatchling's default `regex` version source (`[tool.hatch.version]` in both
16
+ # `pyproject.toml`s) matches `__version__ *= *"..."` literally and wouldn't see this past a `: str`.
17
+ __version__ = "0.2.0"
dlboard/_wire.py ADDED
@@ -0,0 +1,111 @@
1
+ """
2
+ The REST wire contract: path shapes and request/response bodies, shared by client and server.
3
+
4
+ Neither `dlboard.client` nor `dlboard.plugins.backend.basic_rest_backend` (the server side) is a
5
+ parent package of the other, so this lives at the top level rather than inside either -- importing
6
+ a submodule always runs its parent package's `__init__.py` first, and the server importing
7
+ anything nested under `dlboard.client` would mean importing the server needs whatever
8
+ `dlboard/client/__init__.py` eagerly imports (`DLBoardLogger`, and so `torch`), for a module that
9
+ never actually touches either. Pure `pydantic`/`typing` -- no heavy dependency on either side.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Final
15
+
16
+ from pydantic import BaseModel
17
+
18
+ from dlboard import models
19
+ from dlboard._compat import StrEnum
20
+
21
+ API_VERSION: Final = 1
22
+ """
23
+ The REST API major this version of dlboard speaks (see `Identity.api_version`). Bumped only for a
24
+ breaking change to an existing path's request/response shape or status-code semantics -- an
25
+ additive change (a new optional field, a new path) doesn't need one, since `extra="ignore"` on
26
+ every model here is what makes those safe to skip across.
27
+ """
28
+
29
+ API_PREFIX: Final = f"api/v{API_VERSION}"
30
+ """Every REST path lives under this, so a path never again depends on a Python class's `__name__`
31
+ the way it used to -- see `Resource`."""
32
+
33
+ METADATA_PART_SUFFIX: Final = ".json"
34
+ """Appended to an artifact file's multipart part name to name the part carrying its `NewArtifact` JSON."""
35
+
36
+ WHOAMI_PATH: Final = f"{API_PREFIX}/whoami"
37
+
38
+ DLBOARD_USER_HEADER: Final = "X-Dlboard-User"
39
+ """Carries the client's best-effort identity (see `dlboard._identity.resolve_username`).
40
+
41
+ Never trusted blindly -- a missing/blank header falls back to the same best-effort resolution the
42
+ client itself falls back to. This is attribution, not authentication: nothing here proves a caller
43
+ actually is who the header claims. Read server-side by `dlboard.plugins.auth.anonymous`, the one
44
+ provider that doesn't verify identity another way.
45
+ """
46
+
47
+ DLBOARD_CLIENT_VERSION_HEADER: Final = "X-Dlboard-Client-Version"
48
+ """The installed `dlboard` client distribution's version -- attribution only, like `DLBOARD_USER_HEADER`;
49
+ the server doesn't gate on it. See `Identity.server_version`/`api_version` for the direction a
50
+ client actually acts on."""
51
+
52
+
53
+ class Resource(StrEnum):
54
+ """
55
+ Every REST resource's path segment under `API_PREFIX`.
56
+
57
+ The plural noun shared by a resource's "create" path (`.../<resource>`) and its "one existing
58
+ entity" path (`.../<resource>/<id>`). Spelled out as literal strings, not derived from a
59
+ model's `__name__`: a path changing because a model got renamed in a refactor would be a
60
+ breaking change nobody intended.
61
+ """
62
+
63
+ PROJECTS = "projects"
64
+ EXPERIMENTS = "experiments"
65
+ RUNS = "runs"
66
+ ARTIFACTS = "artifacts"
67
+ ARTIFACT_LINKS = "artifact-links"
68
+ METRICS = "metrics"
69
+ HYPERPARAMS = "hyperparams"
70
+
71
+
72
+ def create_path(resource: Resource, base_url: str = "/") -> str:
73
+ """The REST path to create a new `resource`, e.g. `api/v1/projects`."""
74
+ return f"{base_url}/{API_PREFIX}/{resource}".strip("/")
75
+
76
+
77
+ def entity_path(resource: Resource, entity_id: str = "<int:entity_id>", base_url: str = "/") -> str:
78
+ """The REST path for an action on one existing `resource`, e.g. `api/v1/projects/<id>`."""
79
+ return f"{base_url}/{API_PREFIX}/{resource}/{entity_id}".strip("/")
80
+
81
+
82
+ def get_or_create_path(resource: Resource, base_url: str = "/") -> str:
83
+ """The REST path for the get-or-create-by-name idiom, e.g. `api/v1/projects/get-or-create`."""
84
+ return f"{base_url}/{API_PREFIX}/{resource}/get-or-create".strip("/")
85
+
86
+
87
+ class Identity(BaseModel, frozen=True, extra="ignore"):
88
+ """Who the server authenticated a request as, plus enough to let a client self-diagnose -- what `whoami` returns."""
89
+
90
+ id: int
91
+ username: str
92
+ server_version: str
93
+ """The running server's `dlboard` version -- e.g. for an error message, never parsed by the client."""
94
+ api_version: int = API_VERSION
95
+ """The REST API major this server speaks. A client that doesn't recognize it should refuse to
96
+ proceed rather than guess -- see `DLBoardLogger.__init__`."""
97
+
98
+
99
+ class GetOrCreateProject(BaseModel, frozen=True, extra="ignore"):
100
+ """Request body: find a project by name, creating it (with `description`) if it's missing."""
101
+
102
+ name: str
103
+ description: str = ""
104
+
105
+
106
+ class GetOrCreateExperiment(BaseModel, frozen=True, extra="ignore"):
107
+ """Request body: find an experiment by name within a project, creating it if it's missing."""
108
+
109
+ project_id: int
110
+ name: str = "default"
111
+ source: models.ExperimentSource | None = None
@@ -0,0 +1,10 @@
1
+ """
2
+ Client-side objects in dlboard for use with training.
3
+
4
+ No re-exports here on purpose: `dlboard_logger.py` needs `pytorch_lightning` (the `[lightning]`
5
+ extra) at import time, to subclass its `Logger`. Re-exporting `DLBoardLogger` from this package's
6
+ own `__init__.py` would mean every client install needs lightning just to reach anything else
7
+ under `dlboard.client` (or `dlboard.client.artifacts`) -- importing any submodule always runs its
8
+ parent's `__init__.py` first. Import it from its own module instead:
9
+ `from dlboard.client.dlboard_logger import DLBoardLogger`.
10
+ """