@simplexai/localmodels-linux-x64 0.1.0-dev.56 → 0.1.0-dev.57
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +36 -35
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/bifrost_admin.py +2 -1
- package/modules/localmodels/bifrost_checks.py +11 -8
- package/modules/localmodels/bifrost_models.py +2 -1
- package/modules/localmodels/catalog.json +10 -8
- package/modules/localmodels/gateway_accept.py +4 -3
- package/modules/localmodels/gateway_bifrost.py +2 -1
- package/modules/localmodels/gateway_cli.py +4 -3
- package/modules/localmodels/gateway_server.py +3 -1
- package/modules/localmodels/harness.py +2 -2
- package/modules/localmodels/hf_repo.py +27 -4
- package/modules/localmodels/remote_ops_download.py +36 -261
- package/modules/localmodels/remote_ops_ranges.py +447 -0
- package/modules/localmodels/runtime_auth.py +2 -1
- package/modules/localmodels/runtime_cli.py +1 -1
- package/modules/localmodels/runtime_install.py +5 -2
- package/modules/localmodels/runtime_io.py +3 -2
- package/modules/localmodels/runtime_pi.py +2 -1
- package/modules/localmodels/runtime_windows_acl.py +39 -0
- package/modules/localmodels/source_byok_probe.py +2 -1
- package/modules/localmodels/stack.py +13 -3
- package/modules/localmodels/stack_cli.py +1 -0
- package/modules/localmodels/stack_events.py +15 -0
- package/modules/localmodels/stack_plan.py +5 -1
- package/modules/localmodels/stack_progress.py +30 -5
- package/modules/localmodels/stack_run.py +117 -0
- package/modules/localmodels/transport.py +1 -0
- package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/RECORD +33 -32
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Parallel byte-range transfer of one file, with connections that rebalance ranges.
|
|
3
|
+
|
|
4
|
+
Part of the remote_ops bundle (transport.BUNDLES): standard library only, Python 3.8+. The
|
|
5
|
+
tunables live in remote_ops_download and are read as ``download.<name>`` at call
|
|
6
|
+
time, so the bundle keeps one patchable surface.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import collections
|
|
12
|
+
import contextlib
|
|
13
|
+
import http.client
|
|
14
|
+
import os
|
|
15
|
+
import socket
|
|
16
|
+
import statistics
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.request
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from localmodels import remote_ops, remote_ops_mirrors
|
|
25
|
+
from localmodels import remote_ops_download as download
|
|
26
|
+
except ImportError: # run as a bare file from this directory
|
|
27
|
+
import remote_ops # type: ignore[import-not-found,no-redef]
|
|
28
|
+
import remote_ops_download as download # type: ignore[import-not-found,no-redef]
|
|
29
|
+
import remote_ops_mirrors # type: ignore[import-not-found,no-redef]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _NoRangeError(Exception):
|
|
33
|
+
"""The source stopped honouring byte ranges; the next source is tried."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def connections_for(source: remote_ops.Source) -> int:
|
|
37
|
+
"""How many parallel ranges to open on ``source`` (a few hosts throttle each connection)."""
|
|
38
|
+
return max(
|
|
39
|
+
1,
|
|
40
|
+
download.SOURCE_CONNECTIONS.get(source.get("source", ""), download.CONNECTIONS),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _split(start: int, end: int, count: int | None = None) -> list[list[int]]:
|
|
45
|
+
"""[start, end, done] segments of [start, end): ``count`` (default CONNECTIONS) of them when
|
|
46
|
+
each gets at least MIN_SEGMENT_BYTES, fewer otherwise, never none for a non-empty range."""
|
|
47
|
+
wanted = download.CONNECTIONS if count is None else count
|
|
48
|
+
count = max(1, min(wanted, (end - start) // download.MIN_SEGMENT_BYTES))
|
|
49
|
+
step = -(-(end - start) // count)
|
|
50
|
+
return [[s, min(end, s + step), s] for s in range(start, end, step)]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _resume_ranges(part: str, size: int, count: int | None = None) -> list[list[int]]:
|
|
54
|
+
"""The segments still to fetch. A plain .part (a single-connection download of an earlier
|
|
55
|
+
version) is a finished prefix; the file is then sized so each range writes in place."""
|
|
56
|
+
segments = download._load_ranges(part, size)
|
|
57
|
+
if segments is None:
|
|
58
|
+
have = os.path.getsize(part) if os.path.exists(part) else 0
|
|
59
|
+
with open(part, "ab") as out:
|
|
60
|
+
out.truncate(size)
|
|
61
|
+
segments = _split(have, size, count) if have < size else []
|
|
62
|
+
download._save_ranges(part, size, segments)
|
|
63
|
+
return segments
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _retryable(exc: BaseException) -> bool:
|
|
67
|
+
"""Permanent HTTP responses (unfollowed redirects such as 308, client errors other than
|
|
68
|
+
408/429) will not turn into the pinned file on retry; move on to the next source at once."""
|
|
69
|
+
if isinstance(exc, urllib.error.HTTPError):
|
|
70
|
+
return exc.code in (408, 429) or exc.code >= 500
|
|
71
|
+
return True
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _Claim:
|
|
75
|
+
"""One connection's hold on a segment, with recent (time, done) marks for its rate."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, segment: list[int], now: float) -> None:
|
|
78
|
+
self.segment, self.since = segment, now
|
|
79
|
+
self.first: float | None = None # when its first bytes were written
|
|
80
|
+
self.marks: collections.deque[tuple[float, int]] = collections.deque([(now, segment[2])])
|
|
81
|
+
self.response: Any = None
|
|
82
|
+
|
|
83
|
+
def mark(self, now: float) -> None:
|
|
84
|
+
if self.first is None:
|
|
85
|
+
self.first = now
|
|
86
|
+
self.marks.append((now, self.segment[2]))
|
|
87
|
+
while len(self.marks) > 2 and now - self.marks[1][0] >= download.CLAIM_RATE_WINDOW_S:
|
|
88
|
+
self.marks.popleft()
|
|
89
|
+
|
|
90
|
+
def rate(self, now: float) -> float | None:
|
|
91
|
+
"""Bytes per second over the last CLAIM_RATE_WINDOW_S; None while unknown (no first
|
|
92
|
+
byte yet, or less than CLAIM_GRACE_S since it), 0 with no first byte after
|
|
93
|
+
CLAIM_STALL_S. A stalled connection adds no marks, so its rate falls towards zero."""
|
|
94
|
+
if self.first is None:
|
|
95
|
+
return 0.0 if now - self.since >= download.CLAIM_STALL_S else None
|
|
96
|
+
if now - self.first < download.CLAIM_GRACE_S:
|
|
97
|
+
return None
|
|
98
|
+
then, before = self.marks[0]
|
|
99
|
+
return (self.segment[2] - before) / max(1e-3, now - then)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _Transfer:
|
|
103
|
+
"""Parallel ranged download of one file. Each connection claims a segment and fetches it
|
|
104
|
+
from its ``done`` offset with retries, then claims another or steals the tail of the one
|
|
105
|
+
that will finish last. ``done`` advances only after the bytes are written and never past
|
|
106
|
+
``end``, so the saved record never claims bytes the file lacks; a thief may rewrite a few
|
|
107
|
+
bytes its victim was writing at the same moment, which are the same bytes."""
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
url: str,
|
|
112
|
+
part: str,
|
|
113
|
+
size: int,
|
|
114
|
+
segments: list[list[int]],
|
|
115
|
+
*,
|
|
116
|
+
attempts: int | None = None,
|
|
117
|
+
connections: int = 1,
|
|
118
|
+
) -> None:
|
|
119
|
+
self.url, self.part, self.size, self.segments = url, part, size, segments
|
|
120
|
+
self.attempts = download.ATTEMPTS if attempts is None else max(1, attempts)
|
|
121
|
+
self.connections = max(1, connections)
|
|
122
|
+
self.lock, self.io_lock = threading.Lock(), threading.Lock()
|
|
123
|
+
self.stop = threading.Event()
|
|
124
|
+
self.errors: list[BaseException] = []
|
|
125
|
+
self.claims: dict[int, _Claim] = {} # id(segment) -> its connection's claim
|
|
126
|
+
self.steals = 0
|
|
127
|
+
self._responses: list[Any] = []
|
|
128
|
+
|
|
129
|
+
def _track_response(self, resp: Any) -> None:
|
|
130
|
+
with self.lock:
|
|
131
|
+
self._responses.append(resp)
|
|
132
|
+
|
|
133
|
+
def _untrack_response(self, resp: Any) -> None:
|
|
134
|
+
with self.lock:
|
|
135
|
+
if resp in self._responses:
|
|
136
|
+
self._responses.remove(resp)
|
|
137
|
+
|
|
138
|
+
def stop_and_close(self) -> None:
|
|
139
|
+
with self.io_lock:
|
|
140
|
+
self.stop.set()
|
|
141
|
+
with self.lock:
|
|
142
|
+
active = list(self._responses)
|
|
143
|
+
for resp in active:
|
|
144
|
+
_close(resp)
|
|
145
|
+
|
|
146
|
+
def remaining(self) -> int:
|
|
147
|
+
with self.lock:
|
|
148
|
+
return sum(end - done for _, end, done in self.segments)
|
|
149
|
+
|
|
150
|
+
def active(self) -> int:
|
|
151
|
+
"""Connections now fetching bytes: claims whose segment still has bytes to fetch."""
|
|
152
|
+
with self.lock:
|
|
153
|
+
return sum(1 for c in self.claims.values() if c.segment[2] < c.segment[1])
|
|
154
|
+
|
|
155
|
+
def snapshot(self) -> list[list[int]]:
|
|
156
|
+
with self.lock:
|
|
157
|
+
return [list(s) for s in self.segments]
|
|
158
|
+
|
|
159
|
+
def connection(self) -> None:
|
|
160
|
+
"""One connection: fetch claimed segments, then steal from the others until every
|
|
161
|
+
range is done."""
|
|
162
|
+
pace: float | None = None
|
|
163
|
+
while not self.stop.is_set():
|
|
164
|
+
claim = self._claim(pace)
|
|
165
|
+
if claim is None:
|
|
166
|
+
if not self.active():
|
|
167
|
+
return
|
|
168
|
+
self.stop.wait(download.STEAL_POLL_S) # stay to take over a range that stalls later
|
|
169
|
+
continue
|
|
170
|
+
try:
|
|
171
|
+
self.worker(claim.segment, claim)
|
|
172
|
+
finally:
|
|
173
|
+
with self.lock:
|
|
174
|
+
pace = claim.rate(time.monotonic())
|
|
175
|
+
self.claims.pop(id(claim.segment), None)
|
|
176
|
+
|
|
177
|
+
def _claim(self, pace: float | None) -> _Claim | None:
|
|
178
|
+
now, victim = time.monotonic(), None
|
|
179
|
+
with self.lock:
|
|
180
|
+
if self.stop.is_set():
|
|
181
|
+
return None
|
|
182
|
+
segment = next(
|
|
183
|
+
(s for s in self.segments if s[2] < s[1] and id(s) not in self.claims), None
|
|
184
|
+
)
|
|
185
|
+
if segment is None:
|
|
186
|
+
segment, victim = self._steal(now, pace)
|
|
187
|
+
if segment is None:
|
|
188
|
+
return None
|
|
189
|
+
claim = self.claims[id(segment)] = _Claim(segment, now)
|
|
190
|
+
response = victim.response if victim is not None else None
|
|
191
|
+
if response is not None: # a stalled victim gave up all of its range: unblock it
|
|
192
|
+
_close(response)
|
|
193
|
+
return claim
|
|
194
|
+
|
|
195
|
+
def _steal(self, now: float, pace: float | None) -> tuple[list[int] | None, _Claim | None]:
|
|
196
|
+
"""Under ``lock``: split off the tail of the claim that will finish last and return it
|
|
197
|
+
(and the victim when it keeps nothing), or (None, None) when no split is worth it."""
|
|
198
|
+
rates = [r for r in (c.rate(now) for c in self.claims.values()) if r]
|
|
199
|
+
peer = statistics.median(rates) if rates else None
|
|
200
|
+
thief = pace if pace else peer # only measured, moving rates
|
|
201
|
+
best: tuple[float, _Claim, int] | None = None
|
|
202
|
+
for claim in self.claims.values():
|
|
203
|
+
left = claim.segment[1] - claim.segment[2]
|
|
204
|
+
share = _share(left, claim.rate(now), thief) if left > 0 else None
|
|
205
|
+
if share is not None and (best is None or share[1] > best[0]):
|
|
206
|
+
best = (share[1], claim, share[0])
|
|
207
|
+
if best is None:
|
|
208
|
+
return None, None
|
|
209
|
+
_, claim, keep = best
|
|
210
|
+
segment = claim.segment
|
|
211
|
+
mid = segment[2] + keep
|
|
212
|
+
stolen = [mid, segment[1], mid]
|
|
213
|
+
segment[1] = mid
|
|
214
|
+
self.segments.append(stolen)
|
|
215
|
+
self.steals += 1
|
|
216
|
+
return stolen, (claim if keep == 0 else None)
|
|
217
|
+
|
|
218
|
+
def _range(self, segment: list[int], claim: _Claim) -> None:
|
|
219
|
+
with self.lock:
|
|
220
|
+
done, end = segment[2], segment[1]
|
|
221
|
+
if done >= end:
|
|
222
|
+
return
|
|
223
|
+
with urllib.request.urlopen(download._ranged_request(self.url, done, end), timeout=60) as r:
|
|
224
|
+
self._track_response(r)
|
|
225
|
+
claim.response = r
|
|
226
|
+
try:
|
|
227
|
+
if self.stop.is_set():
|
|
228
|
+
return
|
|
229
|
+
if getattr(r, "status", 200) != 206 or not str(
|
|
230
|
+
r.headers.get("Content-Range", "")
|
|
231
|
+
).startswith(f"bytes {done}-"):
|
|
232
|
+
raise _NoRangeError()
|
|
233
|
+
read_fn = getattr(r, "read1", r.read)
|
|
234
|
+
with self.io_lock:
|
|
235
|
+
if self.stop.is_set():
|
|
236
|
+
return
|
|
237
|
+
out = open(self.part, "r+b", buffering=0)
|
|
238
|
+
with out:
|
|
239
|
+
out.seek(done)
|
|
240
|
+
while not self.stop.is_set():
|
|
241
|
+
with self.lock:
|
|
242
|
+
end = segment[1] # a thief may have cut the range short
|
|
243
|
+
if done >= end:
|
|
244
|
+
break
|
|
245
|
+
chunk = read_fn(min(download.READ_BYTES, end - done))
|
|
246
|
+
if not chunk:
|
|
247
|
+
break
|
|
248
|
+
with self.io_lock:
|
|
249
|
+
if self.stop.is_set():
|
|
250
|
+
break
|
|
251
|
+
view = memoryview(chunk)
|
|
252
|
+
while view:
|
|
253
|
+
view = view[out.write(view) or 0 :]
|
|
254
|
+
with self.lock:
|
|
255
|
+
done = segment[2] = min(segment[1], done + len(chunk))
|
|
256
|
+
claim.mark(time.monotonic())
|
|
257
|
+
finally:
|
|
258
|
+
claim.response = None
|
|
259
|
+
self._untrack_response(r)
|
|
260
|
+
with self.lock:
|
|
261
|
+
end = segment[1]
|
|
262
|
+
if done < end and not self.stop.is_set():
|
|
263
|
+
raise http.client.IncompleteRead(b"", end - done)
|
|
264
|
+
|
|
265
|
+
def worker(self, segment: list[int], claim: _Claim | None = None) -> None:
|
|
266
|
+
if claim is None:
|
|
267
|
+
claim = _Claim(segment, time.monotonic())
|
|
268
|
+
attempt = 0
|
|
269
|
+
while not self._finished(segment) and not self.stop.is_set():
|
|
270
|
+
try:
|
|
271
|
+
self._range(segment, claim)
|
|
272
|
+
except _NoRangeError as exc:
|
|
273
|
+
self.fail(exc)
|
|
274
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
|
|
275
|
+
if self.stop.is_set() or self._finished(segment):
|
|
276
|
+
return
|
|
277
|
+
attempt += 1
|
|
278
|
+
if not _retryable(exc) or attempt >= self.attempts:
|
|
279
|
+
self.fail(exc)
|
|
280
|
+
return
|
|
281
|
+
self.stop.wait(min(30, 2**attempt))
|
|
282
|
+
except BaseException as exc: # noqa: BLE001 - reported by the main thread
|
|
283
|
+
if not self.stop.is_set() and not self._finished(segment):
|
|
284
|
+
self.fail(exc)
|
|
285
|
+
return
|
|
286
|
+
|
|
287
|
+
def _finished(self, segment: list[int]) -> bool:
|
|
288
|
+
with self.lock:
|
|
289
|
+
return segment[2] >= segment[1]
|
|
290
|
+
|
|
291
|
+
def fail(self, exc: BaseException) -> None:
|
|
292
|
+
with self.lock:
|
|
293
|
+
self.errors.append(exc)
|
|
294
|
+
self.stop_and_close()
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _share(left: int, own: float | None, thief: float | None) -> tuple[int, float] | None:
|
|
298
|
+
"""How many of a victim's ``left`` bytes it keeps when a connection steals from it, and
|
|
299
|
+
the victim's estimated time to finish (larger is robbed first); None when not worth it.
|
|
300
|
+
A stalled victim (rate 0) loses everything. With a rate unknown, large ranges are halved;
|
|
301
|
+
with both known, the split ends both connections together."""
|
|
302
|
+
if own == 0:
|
|
303
|
+
return 0, float("inf")
|
|
304
|
+
if own is None or thief is None:
|
|
305
|
+
keep = left // 2
|
|
306
|
+
return (
|
|
307
|
+
(keep, left / (own or thief or 1e6))
|
|
308
|
+
if left - keep >= download.STEAL_MIN_BYTES
|
|
309
|
+
else None
|
|
310
|
+
)
|
|
311
|
+
keep = int(left * own / (own + thief))
|
|
312
|
+
if keep < download.READ_BYTES:
|
|
313
|
+
keep = 0
|
|
314
|
+
return (keep, left / own) if (left - keep) / thief >= download.STEAL_MIN_S else None
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _close(resp: Any) -> None:
|
|
318
|
+
"""Abort a response another thread may be blocked reading. Closing its buffered reader
|
|
319
|
+
waits for that read to return, so the socket is shut down first (the read then fails at
|
|
320
|
+
once) and the close runs on its own thread."""
|
|
321
|
+
sock = getattr(getattr(getattr(resp, "fp", None), "raw", None), "_sock", None)
|
|
322
|
+
if isinstance(sock, socket.socket):
|
|
323
|
+
with contextlib.suppress(OSError):
|
|
324
|
+
socket.socket.shutdown(sock, socket.SHUT_RDWR) # the TCP stream, under any TLS
|
|
325
|
+
|
|
326
|
+
def close() -> None:
|
|
327
|
+
for target in (resp, getattr(resp, "fp", None)):
|
|
328
|
+
if target is not None:
|
|
329
|
+
with contextlib.suppress(Exception):
|
|
330
|
+
target.close()
|
|
331
|
+
|
|
332
|
+
threading.Thread(target=close, daemon=True).start()
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _finish(job: _Transfer, label: str) -> None:
|
|
336
|
+
if job.errors:
|
|
337
|
+
raise job.errors[0]
|
|
338
|
+
if job.remaining():
|
|
339
|
+
raise RuntimeError(f"{label} download stopped with bytes missing")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _threads(job: _Transfer, ranged: bool) -> list[threading.Thread]:
|
|
343
|
+
if not ranged:
|
|
344
|
+
return [threading.Thread(target=_plain, args=(job,), daemon=True)]
|
|
345
|
+
# a resumed file of one large open range spreads over every connection again
|
|
346
|
+
open_ranges = sum(1 for s in job.segments if s[2] < s[1])
|
|
347
|
+
count = min(job.connections, max(open_ranges, job.remaining() // download.MIN_SEGMENT_BYTES))
|
|
348
|
+
return [
|
|
349
|
+
threading.Thread(target=job.connection, daemon=True)
|
|
350
|
+
for _ in range(max(1, count) if open_ranges else 0)
|
|
351
|
+
]
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _run(
|
|
355
|
+
job: _Transfer,
|
|
356
|
+
source: remote_ops.Source,
|
|
357
|
+
label: str,
|
|
358
|
+
*,
|
|
359
|
+
ranged: bool,
|
|
360
|
+
allow_slow_switch: bool = False,
|
|
361
|
+
) -> None:
|
|
362
|
+
threads = _threads(job, ranged)
|
|
363
|
+
for thread in threads:
|
|
364
|
+
thread.start()
|
|
365
|
+
size = job.size
|
|
366
|
+
mark = time.monotonic()
|
|
367
|
+
initial_done = size - job.remaining()
|
|
368
|
+
meter = remote_ops_mirrors.Rate(mark, initial_done)
|
|
369
|
+
slow_window_start, slow_window_done = mark, initial_done
|
|
370
|
+
while True:
|
|
371
|
+
alive = [t for t in threads if t.is_alive()] # the connections open during this interval
|
|
372
|
+
if not alive or not job.remaining(): # a stalled thief's victim may still be blocked
|
|
373
|
+
break
|
|
374
|
+
for t in alive:
|
|
375
|
+
t.join(timeout=remote_ops._PROGRESS_EVERY_S / len(alive))
|
|
376
|
+
now, done = time.monotonic(), size - job.remaining()
|
|
377
|
+
if allow_slow_switch and not job.stop.is_set():
|
|
378
|
+
window_elapsed = now - slow_window_start
|
|
379
|
+
if window_elapsed >= download.SLOW_WINDOW_S:
|
|
380
|
+
window_rate = int((done - slow_window_done) / max(1e-3, window_elapsed))
|
|
381
|
+
remaining = max(0, size - done)
|
|
382
|
+
near_done = remaining <= download.SLOW_BYTES_PER_S * download.SLOW_MIN_REMAINING_S
|
|
383
|
+
if window_rate < download.SLOW_BYTES_PER_S and not near_done:
|
|
384
|
+
job.fail(download.SlowTransferError(window_rate))
|
|
385
|
+
break
|
|
386
|
+
slow_window_start, slow_window_done = now, done
|
|
387
|
+
if now - mark >= remote_ops._PROGRESS_EVERY_S:
|
|
388
|
+
remote_ops.emit(
|
|
389
|
+
"progress",
|
|
390
|
+
phase="download",
|
|
391
|
+
file=label,
|
|
392
|
+
done=done,
|
|
393
|
+
total=size,
|
|
394
|
+
bytes_per_s=meter.add(now, done),
|
|
395
|
+
source=source["source"],
|
|
396
|
+
connections=max(1, job.active()) if ranged else 1,
|
|
397
|
+
**remote_ops.step_fields(done),
|
|
398
|
+
)
|
|
399
|
+
mark = now
|
|
400
|
+
if ranged:
|
|
401
|
+
download._save_ranges(job.part, size, job.snapshot())
|
|
402
|
+
if job.errors or any(t.is_alive() for t in threads):
|
|
403
|
+
job.stop_and_close()
|
|
404
|
+
deadline = time.monotonic() + 2.0
|
|
405
|
+
for t in threads:
|
|
406
|
+
if t.is_alive():
|
|
407
|
+
t.join(timeout=max(0.0, deadline - time.monotonic()))
|
|
408
|
+
if ranged:
|
|
409
|
+
download._save_ranges(job.part, size, job.snapshot())
|
|
410
|
+
if job.steals:
|
|
411
|
+
remote_ops.emit(
|
|
412
|
+
"log",
|
|
413
|
+
message=f"{label}: {len(threads)} connections, {job.steals} ranges rebalanced",
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _plain(job: _Transfer) -> None:
|
|
418
|
+
"""A single unranged stream (a data: URL or a server without Range support)."""
|
|
419
|
+
segment = job.segments[0]
|
|
420
|
+
try:
|
|
421
|
+
with urllib.request.urlopen(
|
|
422
|
+
urllib.request.Request(job.url, headers={"User-Agent": "localmodels-deploy"}),
|
|
423
|
+
timeout=60,
|
|
424
|
+
) as r:
|
|
425
|
+
job._track_response(r)
|
|
426
|
+
try:
|
|
427
|
+
with job.io_lock:
|
|
428
|
+
if job.stop.is_set():
|
|
429
|
+
return
|
|
430
|
+
out = open(job.part, "wb")
|
|
431
|
+
with out:
|
|
432
|
+
read_fn = getattr(r, "read1", r.read)
|
|
433
|
+
while not job.stop.is_set():
|
|
434
|
+
chunk = read_fn(download.READ_BYTES)
|
|
435
|
+
if not chunk:
|
|
436
|
+
break
|
|
437
|
+
with job.io_lock:
|
|
438
|
+
if job.stop.is_set():
|
|
439
|
+
break
|
|
440
|
+
out.write(chunk)
|
|
441
|
+
with job.lock:
|
|
442
|
+
segment[2] = min(segment[1], segment[2] + len(chunk))
|
|
443
|
+
finally:
|
|
444
|
+
job._untrack_response(r)
|
|
445
|
+
except BaseException as exc: # noqa: BLE001 - reported by the main thread
|
|
446
|
+
if not job.stop.is_set():
|
|
447
|
+
job.fail(exc)
|
|
@@ -23,6 +23,7 @@ from localmodels.runtime_io import (
|
|
|
23
23
|
private_directory,
|
|
24
24
|
private_permissions,
|
|
25
25
|
regular_directories,
|
|
26
|
+
rename_with_retry,
|
|
26
27
|
validate_runtime_root,
|
|
27
28
|
)
|
|
28
29
|
|
|
@@ -459,7 +460,7 @@ def _write_text_private(path: Path, text: str, *, marker: bool = False) -> None:
|
|
|
459
460
|
with os.fdopen(descriptor, "w") as stream:
|
|
460
461
|
stream.write(text)
|
|
461
462
|
private_permissions(staged, created=True)
|
|
462
|
-
|
|
463
|
+
rename_with_retry(staged, path, replace=True)
|
|
463
464
|
finally:
|
|
464
465
|
staged.unlink(missing_ok=True)
|
|
465
466
|
|
|
@@ -600,7 +600,7 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
|
|
|
600
600
|
private_permissions(marker, created=True)
|
|
601
601
|
if replace:
|
|
602
602
|
runtime_pi.retire(target)
|
|
603
|
-
|
|
603
|
+
runtime_install.rename_with_retry(tree, target)
|
|
604
604
|
runtime_install.release_downloads(plan)
|
|
605
605
|
event({"kind": "stage", "stage": "install", "state": "succeeded"})
|
|
606
606
|
return _installed(root, runtime, before_versions)
|
|
@@ -25,6 +25,9 @@ from localmodels.runtime_io import (
|
|
|
25
25
|
private_directory,
|
|
26
26
|
private_permissions,
|
|
27
27
|
)
|
|
28
|
+
from localmodels.runtime_io import (
|
|
29
|
+
rename_with_retry as rename_with_retry,
|
|
30
|
+
)
|
|
28
31
|
|
|
29
32
|
|
|
30
33
|
@contextlib.contextmanager
|
|
@@ -185,7 +188,7 @@ def _place_unpacked(tree: Path, unpacked: list[tuple[int, dict[str, Any], Path]]
|
|
|
185
188
|
for _, artifact, unpack in unpacked:
|
|
186
189
|
if not artifact.get("destination"):
|
|
187
190
|
for entry in unpack.iterdir():
|
|
188
|
-
entry
|
|
191
|
+
rename_with_retry(entry, tree / entry.name)
|
|
189
192
|
modules = sorted(
|
|
190
193
|
(item for item in unpacked if item[1].get("destination")),
|
|
191
194
|
key=lambda item: (len(Path(item[1]["destination"]).parts), item[0]),
|
|
@@ -197,7 +200,7 @@ def _place_unpacked(tree: Path, unpacked: list[tuple[int, dict[str, Any], Path]]
|
|
|
197
200
|
if target.parent not in verified_parents:
|
|
198
201
|
private_directory(target.parent)
|
|
199
202
|
verified_parents.add(target.parent)
|
|
200
|
-
top
|
|
203
|
+
rename_with_retry(top, target)
|
|
201
204
|
|
|
202
205
|
|
|
203
206
|
def install_tree(
|
|
@@ -131,6 +131,7 @@ _windows_api = runtime_windows_acl.api
|
|
|
131
131
|
_windows_private = runtime_windows_acl.private_permissions
|
|
132
132
|
_private_dacl_entries = runtime_windows_acl.private_dacl_entries
|
|
133
133
|
_windows_sid_text = runtime_windows_acl.sid_text
|
|
134
|
+
rename_with_retry = runtime_windows_acl.rename_with_retry
|
|
134
135
|
|
|
135
136
|
|
|
136
137
|
def _safe_member(name: str) -> Path:
|
|
@@ -595,7 +596,7 @@ def _matches(part: Path, artifact: dict[str, Any]) -> bool:
|
|
|
595
596
|
|
|
596
597
|
|
|
597
598
|
def _publish(part: Path, destination: Path) -> None:
|
|
598
|
-
part
|
|
599
|
+
rename_with_retry(part, destination)
|
|
599
600
|
private_permissions(destination)
|
|
600
601
|
|
|
601
602
|
|
|
@@ -709,7 +710,7 @@ def write_private_json(path: Path, value: object) -> None:
|
|
|
709
710
|
stream.flush()
|
|
710
711
|
os.fsync(stream.fileno())
|
|
711
712
|
private_permissions(staged, created=True)
|
|
712
|
-
|
|
713
|
+
rename_with_retry(staged, path, replace=True)
|
|
713
714
|
finally:
|
|
714
715
|
staged.unlink(missing_ok=True)
|
|
715
716
|
|
|
@@ -18,6 +18,7 @@ from localmodels import runtime_process
|
|
|
18
18
|
from localmodels.harness import load_lock
|
|
19
19
|
from localmodels.runtime_discovery import owned_marker as owned_marker
|
|
20
20
|
from localmodels.runtime_install import bootstrap
|
|
21
|
+
from localmodels.runtime_io import rename_with_retry
|
|
21
22
|
from localmodels.runtime_releases import STABLE, version_key
|
|
22
23
|
|
|
23
24
|
|
|
@@ -127,5 +128,5 @@ def retire(target: Path) -> None:
|
|
|
127
128
|
is barely longer than the version's, so no file below it passes Windows' 260 characters
|
|
128
129
|
where the installed one did not."""
|
|
129
130
|
aside = target.with_name(f".old-{secrets.token_hex(2)}")
|
|
130
|
-
target
|
|
131
|
+
rename_with_retry(target, aside)
|
|
131
132
|
shutil.rmtree(aside, ignore_errors=True)
|
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import errno
|
|
5
6
|
import functools
|
|
6
7
|
import os
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Callable, Sequence
|
|
7
11
|
from pathlib import Path
|
|
8
12
|
from typing import Any
|
|
9
13
|
|
|
@@ -294,3 +298,38 @@ def protect(advapi: Any, kernel: Any, path: Path, user_sid: str) -> None:
|
|
|
294
298
|
finally:
|
|
295
299
|
if security.value:
|
|
296
300
|
kernel.LocalFree(security)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
_WINDOWS_RENAME_RETRY_WINERRORS = frozenset({5, 32})
|
|
304
|
+
_WINDOWS_RENAME_RETRY_DELAYS_S = (0.05, 0.1, 0.2, 0.4, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _retryable_windows_rename_error(exc: OSError) -> bool:
|
|
308
|
+
"""True for transient Windows Defender / Search Indexer handle locks on newly written files."""
|
|
309
|
+
if sys.platform != "win32" or not isinstance(exc, PermissionError):
|
|
310
|
+
return False
|
|
311
|
+
winerror = getattr(exc, "winerror", None)
|
|
312
|
+
if winerror is not None:
|
|
313
|
+
return winerror in _WINDOWS_RENAME_RETRY_WINERRORS
|
|
314
|
+
return exc.errno in (None, errno.EACCES)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def rename_with_retry(
|
|
318
|
+
source: Path,
|
|
319
|
+
target: Path,
|
|
320
|
+
*,
|
|
321
|
+
replace: bool = False,
|
|
322
|
+
delays: Sequence[float] = _WINDOWS_RENAME_RETRY_DELAYS_S,
|
|
323
|
+
pause: Callable[[float], None] | None = None,
|
|
324
|
+
) -> Path:
|
|
325
|
+
"""Rename or replace ``source`` into ``target``, retrying transient Windows AV locks
|
|
326
|
+
(WinError 5 Access Denied / WinError 32 Sharing Violation) with bounded backoff."""
|
|
327
|
+
sleep = time.sleep if pause is None else pause
|
|
328
|
+
for delay in delays:
|
|
329
|
+
try:
|
|
330
|
+
return source.replace(target) if replace else source.rename(target)
|
|
331
|
+
except OSError as exc:
|
|
332
|
+
if not _retryable_windows_rename_error(exc):
|
|
333
|
+
raise
|
|
334
|
+
sleep(delay)
|
|
335
|
+
return source.replace(target) if replace else source.rename(target)
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import http.client
|
|
5
6
|
import json
|
|
6
7
|
import time
|
|
7
8
|
import urllib.error
|
|
@@ -83,7 +84,7 @@ def _call(
|
|
|
83
84
|
f"{url} returned HTTP 404: the address or the model was not found.",
|
|
84
85
|
) from None
|
|
85
86
|
raise ByokError("BYOK_UPSTREAM_REJECTED", f"{url} returned HTTP {exc.code}.") from None
|
|
86
|
-
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
87
|
+
except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException) as exc:
|
|
87
88
|
raise ByokError(
|
|
88
89
|
"BYOK_UNREACHABLE", f"Could not reach {url} ({type(exc).__name__})."
|
|
89
90
|
) from None
|
|
@@ -199,7 +199,8 @@ def _deploy(component: str, plan: Plan, key: str, log: Log) -> Component:
|
|
|
199
199
|
)
|
|
200
200
|
if record["ok"]:
|
|
201
201
|
return _ok(component, f"{plan['endpoint']['base_url']} ({plan['service']['name']})")
|
|
202
|
-
|
|
202
|
+
failed_step = record["steps"][-1]["step"] if record["steps"] else None
|
|
203
|
+
return _failed(component, record.get("error", "unknown failure"), step=failed_step)
|
|
203
204
|
|
|
204
205
|
|
|
205
206
|
@dataclass(frozen=True)
|
|
@@ -229,13 +230,22 @@ def _ok(component: str, detail: str, checks: list[gateway.Check] | None = None)
|
|
|
229
230
|
return {"component": component, "status": "ok", "detail": detail, "checks": checks or []}
|
|
230
231
|
|
|
231
232
|
|
|
232
|
-
def _failed(
|
|
233
|
-
|
|
233
|
+
def _failed(
|
|
234
|
+
component: str,
|
|
235
|
+
detail: str,
|
|
236
|
+
checks: list[gateway.Check] | None = None,
|
|
237
|
+
*,
|
|
238
|
+
step: str | None = None,
|
|
239
|
+
) -> Component:
|
|
240
|
+
failed: Component = {
|
|
234
241
|
"component": component,
|
|
235
242
|
"status": "failed",
|
|
236
243
|
"detail": detail[-600:],
|
|
237
244
|
"checks": checks or [],
|
|
238
245
|
}
|
|
246
|
+
if step:
|
|
247
|
+
failed["step"] = step
|
|
248
|
+
return failed
|
|
239
249
|
|
|
240
250
|
|
|
241
251
|
# Apply re-plans an approved plan from this computer's state and refuses one that changed. A busy
|
|
@@ -208,6 +208,7 @@ def apply_cli(
|
|
|
208
208
|
((c["component"], c["status"]) for c in record["components"]),
|
|
209
209
|
profile=record.get("profile"),
|
|
210
210
|
cause=failure[1][0] if failure else None,
|
|
211
|
+
reasons=stack_run.component_reasons(record) if failure else None,
|
|
211
212
|
)
|
|
212
213
|
return report(record, timing=shown.timing() if shown else None)
|
|
213
214
|
|
|
@@ -52,6 +52,21 @@ COMPONENTS = frozenset(
|
|
|
52
52
|
)
|
|
53
53
|
STEPS = frozenset({"engine", "download", "install", "start", "verify"})
|
|
54
54
|
PHASES = frozenset({"download", "verify", "loading"})
|
|
55
|
+
# Safe, closed-set public sub-reasons for a failing stack component (WHI-1002):
|
|
56
|
+
# never raw stderr, paths, hostnames, or exception text.
|
|
57
|
+
COMPONENT_REASON_CODES = frozenset(
|
|
58
|
+
{
|
|
59
|
+
"CHECKSUM_MISMATCH",
|
|
60
|
+
"DISK_FULL",
|
|
61
|
+
"OUT_OF_MEMORY",
|
|
62
|
+
"HEALTH_TIMEOUT",
|
|
63
|
+
"PORT_IN_USE",
|
|
64
|
+
"PERMISSION_DENIED",
|
|
65
|
+
"DOWNLOAD_FAILED",
|
|
66
|
+
"ENGINE_START_FAILED",
|
|
67
|
+
"ACCEPTANCE_FAILED",
|
|
68
|
+
}
|
|
69
|
+
)
|
|
55
70
|
|
|
56
71
|
|
|
57
72
|
SOURCES = frozenset({"huggingface", "modelscope", "custom"})
|