@simplexai/localmodels-linux-arm64 0.1.0-dev.110 → 0.1.0-dev.111

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 (46) hide show
  1. package/README.md +1 -1
  2. package/bootstrap.identity +1 -1
  3. package/bootstrap.sha256 +44 -44
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/catalog.json +430 -75
  6. package/modules/localmodels/custom_hub.py +66 -2
  7. package/modules/localmodels/custom_hub_http.py +18 -0
  8. package/modules/localmodels/deploy.py +65 -5
  9. package/modules/localmodels/download-mirrors.json +70 -0
  10. package/modules/localmodels/engine_adapters/strata_poly.py +20 -4
  11. package/modules/localmodels/engine_adapters/suite_plan.py +3 -0
  12. package/modules/localmodels/engines-strata-poly-0.2.20-poly.10.json +132 -0
  13. package/modules/localmodels/http_local.py +46 -0
  14. package/modules/localmodels/library_custom.py +73 -0
  15. package/modules/localmodels/library_jobs.py +0 -12
  16. package/modules/localmodels/library_poly.py +11 -5
  17. package/modules/localmodels/library_presentation.py +28 -0
  18. package/modules/localmodels/library_serve.py +30 -21
  19. package/modules/localmodels/library_smoke.py +1 -1
  20. package/modules/localmodels/library_state.py +20 -1
  21. package/modules/localmodels/library_status.py +46 -55
  22. package/modules/localmodels/mirrors.py +217 -21
  23. package/modules/localmodels/npm_transport.py +46 -35
  24. package/modules/localmodels/plan_envelope.py +8 -1
  25. package/modules/localmodels/region.py +91 -20
  26. package/modules/localmodels/remote_ops_common.py +1 -0
  27. package/modules/localmodels/remote_ops_download.py +574 -126
  28. package/modules/localmodels/remote_ops_prepare.py +8 -2
  29. package/modules/localmodels/remote_ops_ranges.py +80 -44
  30. package/modules/localmodels/remote_ops_redirect.py +3 -1
  31. package/modules/localmodels/remote_ops_remove.py +4 -2
  32. package/modules/localmodels/runtime_index.py +3 -1
  33. package/modules/localmodels/stack.py +1 -6
  34. package/modules/localmodels/stack_suite.py +1 -1
  35. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.9.txt → strata-poly-serve-0.2.20-poly.10.txt} +1 -1
  36. package/modules/localmodels/suite.py +80 -3
  37. package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/METADATA +1 -1
  38. package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/RECORD +40 -40
  39. package/package.json +1 -1
  40. package/tool.json +1 -1
  41. package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +0 -132
  42. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/WHEEL +0 -0
  43. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/entry_points.txt +0 -0
  44. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/licenses/LICENSE +0 -0
  45. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/licenses/NOTICE +0 -0
  46. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -10,12 +10,16 @@ bundle strictly acyclic.
10
10
  from __future__ import annotations
11
11
 
12
12
  import contextlib
13
+ import contextvars
13
14
  import http.client
14
15
  import os
15
16
  import shutil
17
+ import socket
18
+ import ssl
16
19
  import threading
17
20
  import time
18
21
  import urllib.error
22
+ import urllib.parse
19
23
  from typing import Iterator, Tuple
20
24
 
21
25
  try:
@@ -46,8 +50,18 @@ PROBE_SAMPLE_S = 3.0 # once sampled for 3s, stop reading slow mirrors instead o
46
50
  # also probe the opposite region's mirrors so a misclassified region or throttled upstream
47
51
  # immediately yields to a faster mirror (e.g., 880 KB/s Tsinghua beating 39 KB/s official PyPI).
48
52
  CROSS_REGION_PROBE_BPS = 2_000_000
53
+ PROBE_RETRY_S = 0.2
54
+ PROBE_EARLY_GRACE_S = 0.5
55
+ HEAL_COOLDOWN_S = 40.0
56
+ HEAL_MAX_PROBES = 2
57
+ HEAL_MIN_REMAINING_S = 60.0
49
58
  LONE_SMALL_BYTES = 1 << 20
50
59
  RATE_WINDOW_S = remote_ops_mirrors.RATE_WINDOW_S
60
+ _HF_MIRROR_HOSTS = ("hf-mirror.com",)
61
+ _GLOBAL_HF_HOSTS = ("huggingface.co", "hf.co")
62
+ _PROMOTE: contextvars.ContextVar[object] = contextvars.ContextVar(
63
+ "localmodels_download_promote", default=None
64
+ )
51
65
 
52
66
  # Public re-exports from lower bundle modules so existing callers keep one import surface.
53
67
  SLOW_WINDOW_S = remote_ops_ranges.SLOW_WINDOW_S
@@ -109,54 +123,215 @@ def _range_total(response: object) -> int | None:
109
123
  return int(total) if value.startswith("bytes ") and total.isdigit() else None
110
124
 
111
125
 
112
- def probe(url: str, size: int) -> tuple[float, bool] | None:
113
- """Read up to PROBE_BYTES (or for PROBE_SAMPLE_S on slow links) of ``url``: returns
114
- (bytes per second, whether it serves byte ranges), or None when it fails or names another
115
- size (so it cannot be the pinned file)."""
126
+ class PromoteTransferError(Exception):
127
+ """A demoted high-priority mirror recovered; resume the kept ranges from it."""
128
+
129
+ def __init__(self, source: remote_ops_common.Source, ranged: bool) -> None:
130
+ self.source = source
131
+ self.ranged = ranged
132
+ super().__init__(source.get("source", "mirror"))
133
+
134
+
135
+ def _host(url: str) -> str:
136
+ return (urllib.parse.urlsplit(url).hostname or "").lower().rstrip(".")
137
+
138
+
139
+ def _host_is(host: str, names: tuple[str, ...]) -> bool:
140
+ return any(host == name or host.endswith("." + name) for name in names)
141
+
142
+
143
+ def hf_mirror_bounced(original_url: str, final_url: str) -> bool:
144
+ """True when an hf-mirror.com request landed on huggingface.co or a *.hf.co CDN."""
145
+ original = _host(original_url)
146
+ final = _host(final_url)
147
+ if not _host_is(original, _HF_MIRROR_HOSTS) or original == final:
148
+ return False
149
+ return _host_is(final, _GLOBAL_HF_HOSTS)
150
+
151
+
152
+ def _independent_for_region(url: str, region: str) -> bool:
153
+ """A source whose failure may flip the region. hf-mirror is not an independent CN source."""
154
+ if side(url) != region:
155
+ return False
156
+ return not (region == "cn" and source_name(url) == "hf-mirror")
157
+
158
+
159
+ _TRANSIENT_HTTP = frozenset({502, 503, 504})
160
+ _TRANSIENT_SSL_TEXT = ("EOF", "RESET", "TIMEOUT", "TIMED OUT")
161
+
162
+
163
+ class _ProbePending:
164
+ """A probe that had not finished when ranking stopped waiting."""
165
+
166
+
167
+ _PENDING = _ProbePending()
168
+
169
+
170
+ def _ssl_text_transient(exc: BaseException) -> bool:
171
+ text = str(exc).upper()
172
+ return any(token in text for token in _TRANSIENT_SSL_TEXT)
173
+
174
+
175
+ def _transient_probe_error(exc: BaseException) -> bool:
176
+ if isinstance(exc, urllib.error.HTTPError):
177
+ return exc.code in _TRANSIENT_HTTP
178
+ if isinstance(
179
+ exc,
180
+ (
181
+ ssl.SSLEOFError,
182
+ ConnectionResetError,
183
+ TimeoutError,
184
+ socket.timeout,
185
+ http.client.IncompleteRead,
186
+ ConnectionAbortedError,
187
+ ),
188
+ ):
189
+ return True
190
+ if isinstance(exc, ssl.SSLError):
191
+ return _ssl_text_transient(exc)
192
+ if isinstance(exc, urllib.error.URLError):
193
+ reason = getattr(exc, "reason", None)
194
+ return reason is not None and _transient_probe_error(reason)
195
+ return False
196
+
197
+
198
+ def _probe_once(url: str, size: int, timeout_s: float) -> tuple[float, bool] | None:
116
199
  want = min(size, PROBE_BYTES)
117
200
  start, got = time.monotonic(), 0
118
- try:
119
- with remote_ops_common.open_url(
120
- remote_ops_common.build_request(url, 0, want), timeout=PROBE_TIMEOUT_S
121
- ) as r:
122
- status = getattr(r, "status", 200)
123
- length = str(r.headers.get("Content-Length", ""))
124
- ranged = status == 206 and _range_total(r) == size
125
- if status == 206 and not ranged:
126
- return None
127
- if status != 206 and length.isdigit() and int(length) != size:
128
- return None
129
- read_fn = getattr(r, "read1", r.read)
130
- while got < want:
131
- elapsed = time.monotonic() - start
132
- if elapsed >= PROBE_TIMEOUT_S:
133
- break
134
- if got > 0 and elapsed >= PROBE_SAMPLE_S:
135
- break
136
- chunk = read_fn(min(1 << 20, want - got))
137
- if not chunk:
138
- break
139
- got += len(chunk)
140
- except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
141
- return None
201
+ ranged = False
202
+ eof = False
203
+ with remote_ops_common.open_url(
204
+ remote_ops_common.build_request(url, 0, want), timeout=max(0.1, timeout_s)
205
+ ) as r:
206
+ final = url
207
+ geturl = getattr(r, "geturl", None)
208
+ if callable(geturl):
209
+ try:
210
+ final = str(geturl() or url)
211
+ except (TypeError, ValueError):
212
+ final = url
213
+ if hf_mirror_bounced(url, final):
214
+ return None
215
+ status = getattr(r, "status", 200)
216
+ length = str(r.headers.get("Content-Length", ""))
217
+ ranged = status == 206 and _range_total(r) == size
218
+ if status == 206 and not ranged:
219
+ return None
220
+ if status != 206 and length.isdigit() and int(length) != size:
221
+ return None
222
+ ctype = str(r.headers.get("Content-Type", "")).lower()
223
+ if status != 206 and ("text/html" in ctype or "application/xhtml" in ctype):
224
+ return None
225
+ read_fn = getattr(r, "read1", r.read)
226
+ sock = getattr(getattr(getattr(r, "fp", None), "raw", None), "_sock", None)
227
+ while got < want:
228
+ elapsed = time.monotonic() - start
229
+ remaining = timeout_s - elapsed
230
+ if remaining <= 0:
231
+ break
232
+ if got > 0 and elapsed >= PROBE_SAMPLE_S:
233
+ break
234
+ if sock is not None:
235
+ with contextlib.suppress(OSError):
236
+ sock.settimeout(max(0.05, remaining))
237
+ chunk = read_fn(min(1 << 20, want - got))
238
+ if not chunk:
239
+ eof = True
240
+ break
241
+ got += len(chunk)
142
242
  if got <= 0 and want > 0:
143
243
  return None
244
+ if status != 206 and eof and got < want:
245
+ return None
144
246
  return got / max(1e-3, time.monotonic() - start), ranged
145
247
 
146
248
 
249
+ def probe(url: str, size: int) -> tuple[float, bool] | None:
250
+ """Read up to PROBE_BYTES (or for PROBE_SAMPLE_S on slow links) of ``url``: returns
251
+ (bytes per second, whether it serves byte ranges), or None when it fails, names another
252
+ size, or an hf-mirror request bounced to Hugging Face. One transient TLS/connect error is
253
+ retried once inside the probe budget."""
254
+ deadline = time.monotonic() + PROBE_TIMEOUT_S
255
+ retried = False
256
+ while True:
257
+ remaining = deadline - time.monotonic()
258
+ if remaining <= 0:
259
+ return None
260
+ try:
261
+ return _probe_once(url, size, remaining)
262
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
263
+ if isinstance(exc, urllib.error.HTTPError):
264
+ with contextlib.suppress(Exception):
265
+ exc.close()
266
+ if retried or not _transient_probe_error(exc):
267
+ return None
268
+ retried = True
269
+ if deadline - time.monotonic() <= 0:
270
+ return None
271
+ pause = min(PROBE_RETRY_S, max(0.0, deadline - time.monotonic()))
272
+ if pause > 0:
273
+ time.sleep(pause)
274
+
275
+
276
+ def _preferred_fast(
277
+ sources: list[remote_ops_common.Source],
278
+ results: list[tuple[float, bool] | None],
279
+ region: str | None,
280
+ ) -> bool:
281
+ if region == "cn":
282
+ want_source = "modelscope"
283
+ elif region == "global":
284
+ want_source = "huggingface"
285
+ else:
286
+ return False
287
+ for src, result in zip(sources, results):
288
+ if (
289
+ src.get("source") == want_source
290
+ and result is not None
291
+ and result[0] >= CROSS_REGION_PROBE_BPS
292
+ ):
293
+ return True
294
+ return False
295
+
296
+
147
297
  def _probe_many(
148
298
  sources: list[remote_ops_common.Source],
149
299
  size: int,
150
- ) -> list[tuple[remote_ops_common.Source, tuple[float, bool] | None]]:
151
- """Probe ``sources`` concurrently so multi-mirror ranking completes in one RTT window."""
300
+ *,
301
+ region: str | None = None,
302
+ ) -> list[tuple[remote_ops_common.Source, tuple[float, bool] | None | _ProbePending]]:
303
+ """Probe ``sources`` concurrently so multi-mirror ranking completes in one RTT window.
304
+
305
+ In ``cn`` (ModelScope) and ``global`` (Hugging Face), once the preferred primary source has
306
+ already cleared ``CROSS_REGION_PROBE_BPS``, slow or bouncing siblings get
307
+ ``PROBE_EARLY_GRACE_S`` and then are no longer awaited. Only that early-exit return marks
308
+ unfinished threads ``_PENDING``; if the overall deadline expires instead, unfinished probes
309
+ are recorded as ``None`` (failed) so fallback and self-healing still activate.
310
+ """
152
311
  if not sources:
153
312
  return []
154
313
  if len(sources) == 1:
155
314
  return [(sources[0], probe(sources[0]["url"], size))]
156
315
  results: list[tuple[float, bool] | None] = [None] * len(sources)
316
+ finished = [False] * len(sources)
317
+ lock = threading.Lock()
157
318
 
158
319
  def run_one(idx: int, src: remote_ops_common.Source) -> None:
159
- results[idx] = probe(src["url"], size)
320
+ outcome = probe(src["url"], size)
321
+ with lock:
322
+ results[idx] = outcome
323
+ finished[idx] = True
324
+
325
+ def snapshot(
326
+ *, pending_as_skipped: bool
327
+ ) -> list[tuple[remote_ops_common.Source, tuple[float, bool] | None | _ProbePending]]:
328
+ with lock:
329
+ missing: tuple[float, bool] | None | _ProbePending = (
330
+ _PENDING if pending_as_skipped else None
331
+ )
332
+ return [
333
+ (sources[i], results[i] if finished[i] else missing) for i in range(len(sources))
334
+ ]
160
335
 
161
336
  threads = [
162
337
  threading.Thread(target=run_one, args=(i, s), daemon=True) for i, s in enumerate(sources)
@@ -164,9 +339,20 @@ def _probe_many(
164
339
  for t in threads:
165
340
  t.start()
166
341
  deadline = time.monotonic() + PROBE_TIMEOUT_S + 2.0
167
- for t in threads:
168
- t.join(timeout=max(0.0, deadline - time.monotonic()))
169
- return list(zip(sources, results))
342
+ grace_at: float | None = None
343
+ for thread in threads:
344
+ while thread.is_alive() and time.monotonic() < deadline:
345
+ with lock:
346
+ fast = _preferred_fast(sources, results, region)
347
+ if fast:
348
+ if grace_at is None:
349
+ grace_at = time.monotonic() + PROBE_EARLY_GRACE_S
350
+ if time.monotonic() >= grace_at:
351
+ return snapshot(pending_as_skipped=True)
352
+ thread.join(timeout=0.05)
353
+ if time.monotonic() >= deadline:
354
+ break
355
+ return snapshot(pending_as_skipped=False)
170
356
 
171
357
 
172
358
  def rank(
@@ -185,7 +371,12 @@ def rank(
185
371
  measured: list[tuple[float, int, _Ranked]] = []
186
372
  failed: list[_Ranked] = []
187
373
  notes = []
374
+ pending: list[_Ranked] = []
188
375
  for i, (source, result) in enumerate(_probe_many(sources, size)):
376
+ if isinstance(result, _ProbePending):
377
+ pending.append((source, _web(source)))
378
+ notes.append(source["source"] + " not waited")
379
+ continue
189
380
  if result is None: # try ranges anyway: a resumed .part must not restart on a hiccup
190
381
  failed.append((source, _web(source)))
191
382
  notes.append(source["source"] + " unreachable")
@@ -198,7 +389,7 @@ def rank(
198
389
  remote_ops_common.emit(
199
390
  "log", message="download sources for {}: {}".format(label, ", ".join(notes))
200
391
  )
201
- return [r for _, _, r in sorted(measured)] + failed
392
+ return [r for _, _, r in sorted(measured)] + pending + failed
202
393
 
203
394
 
204
395
  def _probe_batch(
@@ -211,9 +402,15 @@ def _probe_batch(
211
402
  notes: list[str],
212
403
  scored: list[tuple[float, int, int, int, _Ranked]],
213
404
  probe_speeds: dict[str, float] | None,
405
+ skipped: list[remote_ops_common.Source] | None = None,
214
406
  ) -> float:
215
407
  best = 0.0
216
- for idx, (src, res) in enumerate(_probe_many(batch, size)):
408
+ for idx, (src, res) in enumerate(_probe_many(batch, size, region=region)):
409
+ if isinstance(res, _ProbePending):
410
+ notes.append(src["source"] + " not waited")
411
+ if skipped is not None:
412
+ skipped.append(src)
413
+ continue
217
414
  if res is None:
218
415
  notes.append(src["source"] + " unreachable")
219
416
  failed.append(src)
@@ -229,6 +426,13 @@ def _probe_batch(
229
426
  return best
230
427
 
231
428
 
429
+ def _heal_source(src: remote_ops_common.Source, region: str) -> bool:
430
+ """A demoted independent mirror worth one later re-probe (cn: ModelScope, not hf-mirror)."""
431
+ if not _independent_for_region(src["url"], region):
432
+ return False
433
+ return cn_rank(src) <= 1
434
+
435
+
232
436
  def _ordered_public(
233
437
  own: list[remote_ops_common.Source],
234
438
  public_s: list[remote_ops_common.Source],
@@ -237,6 +441,7 @@ def _ordered_public(
237
441
  region: str,
238
442
  failed: list[remote_ops_common.Source],
239
443
  probe_speeds: dict[str, float] | None,
444
+ heal_sources: list[remote_ops_common.Source] | None = None,
240
445
  ) -> Iterator[_Ranked]:
241
446
  public_probe = [s for s in public_s if not s.get("member")]
242
447
  public_member = [s for s in public_s if s.get("member")]
@@ -259,18 +464,29 @@ def _ordered_public(
259
464
  notes: list[str] = []
260
465
  scored: list[tuple[float, int, int, int, _Ranked]] = []
261
466
  demoted: list[remote_ops_common.Source] = []
467
+ skipped: list[remote_ops_common.Source] = []
262
468
  best_primary = (
263
- _probe_batch(primary, size, region, 0, failed, demoted, notes, scored, probe_speeds)
469
+ _probe_batch(
470
+ primary, size, region, 0, failed, demoted, notes, scored, probe_speeds, skipped
471
+ )
264
472
  if primary
265
473
  else 0.0
266
474
  )
267
475
  cross_probed = bool(secondary and (not primary or best_primary < CROSS_REGION_PROBE_BPS))
268
476
  if cross_probed:
269
- _probe_batch(secondary, size, region, 1, failed, demoted, notes, scored, probe_speeds)
477
+ _probe_batch(
478
+ secondary, size, region, 1, failed, demoted, notes, scored, probe_speeds, skipped
479
+ )
270
480
  if notes:
271
481
  remote_ops_common.emit(
272
482
  "log", message=f"download sources for {label} (region {region}): {', '.join(notes)}"
273
483
  )
484
+ if heal_sources is not None:
485
+ for src in demoted:
486
+ if _heal_source(src, region) and all(
487
+ item["url"] != src["url"] for item in heal_sources
488
+ ):
489
+ heal_sources.append(src)
274
490
 
275
491
  scored.sort(key=lambda entry: (entry[0], entry[1], entry[2], entry[3]))
276
492
  for _, _, _, _, ranked_entry in scored:
@@ -282,6 +498,7 @@ def _ordered_public(
282
498
  yield from ((s, False) for s in tail_members[1])
283
499
  if region != "cn" and not cross_probed:
284
500
  yield from ((s, _web(s)) for s in secondary)
501
+ yield from ((s, _web(s)) for s in skipped)
285
502
  yield from ((s, _web(s)) for s in demoted)
286
503
 
287
504
 
@@ -292,6 +509,7 @@ def ordered(
292
509
  region: str | None,
293
510
  failed: list[remote_ops_common.Source],
294
511
  probe_speeds: dict[str, float] | None = None,
512
+ heal_sources: list[remote_ops_common.Source] | None = None,
295
513
  ) -> Iterator[_Ranked]:
296
514
  """Dynamic speed-first source ordering with tiered cross-region probing."""
297
515
  own, extra = candidates(sources, region)
@@ -308,7 +526,9 @@ def ordered(
308
526
  yield from rank(local_probe, size, label, failed)
309
527
  yield from ((s, False) for s in local_s if s.get("member"))
310
528
  if public_s:
311
- yield from _ordered_public(own, public_s, size, label, region, failed, probe_speeds)
529
+ yield from _ordered_public(
530
+ own, public_s, size, label, region, failed, probe_speeds, heal_sources
531
+ )
312
532
 
313
533
 
314
534
  def transfer(
@@ -320,6 +540,7 @@ def transfer(
320
540
  *,
321
541
  attempts: int | None = None,
322
542
  allow_slow_switch: bool = False,
543
+ promote: object = None,
323
544
  ) -> None:
324
545
  """Fill ``part`` with all ``size`` bytes from ``source``, reporting progress events; raises
325
546
  on failure with the kept ranges saved so the next call (or source) resumes them. A source
@@ -335,16 +556,29 @@ def transfer(
335
556
  connections=count,
336
557
  )
337
558
  remote_ops_ranges.run_transfer(
338
- job, source, label, ranged=True, allow_slow_switch=allow_slow_switch
559
+ job,
560
+ source,
561
+ label,
562
+ ranged=True,
563
+ allow_slow_switch=allow_slow_switch,
564
+ promote=promote if promote is not None else _PROMOTE.get(),
339
565
  )
340
566
  if not (job.errors and isinstance(job.errors[0], remote_ops_ranges.NoRangeError)):
341
567
  remote_ops_ranges.finish_transfer(job, label)
342
568
  return
569
+ if remote_ops_common.kept_bytes(part, size) > 0:
570
+ remote_ops_ranges.finish_transfer(job, label)
571
+ return
343
572
  remote_ops_common.discard(part)
344
573
  open(part, "wb").close()
345
574
  job = remote_ops_ranges.Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
346
575
  remote_ops_ranges.run_transfer(
347
- job, source, label, ranged=False, allow_slow_switch=allow_slow_switch
576
+ job,
577
+ source,
578
+ label,
579
+ ranged=False,
580
+ allow_slow_switch=allow_slow_switch,
581
+ promote=promote if promote is not None else _PROMOTE.get(),
348
582
  )
349
583
  remote_ops_ranges.finish_transfer(job, label)
350
584
 
@@ -383,20 +617,22 @@ def _fallback(
383
617
  failed: list[remote_ops_common.Source],
384
618
  probe_speeds: dict[str, float] | None = None,
385
619
  ) -> str | None:
386
- """The other region, when ``used`` is on its side and either a source on the region's own
387
- side failed/was slow-aborted first, or cross-region speed probing proved the other side was
388
- decisively faster (>= 2x) while every probed preferred source was below
389
- ``CROSS_REGION_PROBE_BPS``. A neutral source (GitHub, a LAN or user mirror) never switches."""
620
+ """The other region, when ``used`` is on its side and an independent source on the region's
621
+ own side failed or was decisively slower. Hugging Face beating hf-mirror is not a reason to
622
+ flip to ``global``: hf-mirror is the same upstream once it 308s, and a file with no ModelScope
623
+ copy has no independent China source. A neutral source never switches the region."""
390
624
  other = side(used["url"])
391
625
  if region not in ("cn", "global") or other in ("", region):
392
626
  return None
393
- mine = [s for s in failed if side(s["url"]) == region]
627
+ mine = [s for s in failed if _independent_for_region(s["url"], region)]
394
628
  if mine:
395
629
  return other
396
630
  if probe_speeds:
397
631
  used_speed = probe_speeds.get(used["url"], 0.0)
398
632
  pref_speeds = [
399
- bps for candidate_url, bps in probe_speeds.items() if side(candidate_url) == region
633
+ bps
634
+ for candidate_url, bps in probe_speeds.items()
635
+ if _independent_for_region(candidate_url, region)
400
636
  ]
401
637
  if (
402
638
  used_speed > 0
@@ -408,6 +644,207 @@ def _fallback(
408
644
  return None
409
645
 
410
646
 
647
+ class _HealMonitor:
648
+ """Re-probe demoted independent mirrors in the background while a substitute stays slow."""
649
+
650
+ def __init__(self, sources: list[remote_ops_common.Source]) -> None:
651
+ self._feed = sources
652
+ self._fed = len(sources)
653
+ self.sources = list(sources)
654
+ self.probes = 0
655
+ self.next_at = time.monotonic() + HEAL_COOLDOWN_S
656
+ self._lock = threading.Lock()
657
+ self._inflight = False
658
+ self._thread: threading.Thread | None = None
659
+ self._pending_result: (
660
+ tuple[remote_ops_common.Source, tuple[float, bool] | None, float] | None
661
+ ) = None
662
+ self._active_url = ""
663
+
664
+ def _sync_feed_locked(self) -> None:
665
+ while self._fed < len(self._feed):
666
+ item = self._feed[self._fed]
667
+ self._fed += 1
668
+ if item["url"] != self._active_url and all(
669
+ s["url"] != item["url"] for s in self.sources
670
+ ):
671
+ self.sources.append(item)
672
+
673
+ def set_active(self, url: str) -> None:
674
+ with self._lock:
675
+ self._sync_feed_locked()
676
+ self._active_url = url
677
+ self.sources = [item for item in self.sources if item["url"] != url]
678
+ if self._pending_result is not None and self._pending_result[0]["url"] == url:
679
+ self._pending_result = None
680
+
681
+ def wait_probe(self, timeout: float = 5.0) -> None:
682
+ """Wait for any in-flight background probe to settle (deterministic test helper)."""
683
+ with self._lock:
684
+ thread = self._thread
685
+ if thread is not None:
686
+ thread.join(timeout=timeout)
687
+
688
+ def consider(
689
+ self,
690
+ done: int,
691
+ total: int,
692
+ rate: float,
693
+ *,
694
+ active_url: str | None = None,
695
+ ) -> PromoteTransferError | None:
696
+ with self._lock:
697
+ self._sync_feed_locked()
698
+ current = self._active_url if active_url is None else active_url
699
+ remaining = max(0, total - done)
700
+ if self._pending_result is not None:
701
+ target, result, trigger_rate = self._pending_result
702
+ self._pending_result = None
703
+ compare_rate = rate if rate > 0 else trigger_rate
704
+ # An unranged source restarts the file and would discard the kept .part.
705
+ if (
706
+ remaining > 0
707
+ and target["url"] != current
708
+ and result is not None
709
+ and result[1]
710
+ and result[0] >= 2.0 * compare_rate
711
+ ):
712
+ self.sources = [item for item in self.sources if item["url"] != target["url"]]
713
+ return PromoteTransferError(target, result[1])
714
+ if self.sources and self.sources[0]["url"] == target["url"]:
715
+ self.sources.append(self.sources.pop(0))
716
+ return None
717
+ if self._inflight:
718
+ return None
719
+ candidates = [item for item in self.sources if item["url"] != current]
720
+ if not candidates or self.probes >= HEAL_MAX_PROBES:
721
+ return None
722
+ if rate <= 0 or rate >= CROSS_REGION_PROBE_BPS:
723
+ return None
724
+ if remaining <= 0 or remaining / rate <= HEAL_MIN_REMAINING_S:
725
+ return None
726
+ now = time.monotonic()
727
+ if now < self.next_at:
728
+ return None
729
+ target = candidates[0]
730
+ self.probes += 1
731
+ self.next_at = now + HEAL_COOLDOWN_S
732
+ self._inflight = True
733
+
734
+ def _run_probe(
735
+ probe_target: remote_ops_common.Source = target,
736
+ probe_total: int = total,
737
+ probe_rate: float = rate,
738
+ ) -> None:
739
+ try:
740
+ outcome = probe(probe_target["url"], probe_total)
741
+ except Exception: # noqa: BLE001
742
+ outcome = None
743
+ with self._lock:
744
+ self._pending_result = (probe_target, outcome, probe_rate)
745
+ self._inflight = False
746
+
747
+ self._thread = threading.Thread(target=_run_probe, daemon=True)
748
+ self._thread.start()
749
+ return None
750
+
751
+
752
+ def _apply_promotion(
753
+ exc: PromoteTransferError,
754
+ source: remote_ops_common.Source,
755
+ ranged: bool,
756
+ label: str,
757
+ *,
758
+ promoted_urls: set[str],
759
+ failed: list[remote_ops_common.Source],
760
+ immediate: list[_Ranked],
761
+ deferred_slow: list[_Ranked],
762
+ ) -> None:
763
+ remote_ops_common.emit(
764
+ "log",
765
+ message=(
766
+ f"download from {source['source']} is below "
767
+ f"{CROSS_REGION_PROBE_BPS / 1e6:.1f} MB/s for {label}; "
768
+ f"resuming from {exc.source['source']}"
769
+ ),
770
+ )
771
+ promoted_url = exc.source["url"]
772
+ promoted_urls.add(promoted_url)
773
+ failed[:] = [f for f in failed if f["url"] != promoted_url]
774
+ immediate[:] = [entry for entry in immediate if entry[0]["url"] != promoted_url]
775
+ deferred_slow[:] = [entry for entry in deferred_slow if entry[0]["url"] != promoted_url]
776
+ immediate.insert(0, (exc.source, exc.ranged))
777
+ if all(entry[0]["url"] != source["url"] for entry in deferred_slow):
778
+ deferred_slow.append((source, ranged))
779
+
780
+
781
+ def _record_transfer_failure(
782
+ exc: Exception,
783
+ source: remote_ops_common.Source,
784
+ ranged: bool,
785
+ label: str,
786
+ *,
787
+ failed: list[remote_ops_common.Source],
788
+ deferred_slow: list[_Ranked],
789
+ ) -> None:
790
+ remote_ops_common.emit(
791
+ "log",
792
+ message=(
793
+ f"download from {source['source']} stopped, {label}: "
794
+ f"{remote_ops_common.redact_text(str(exc))}"
795
+ ),
796
+ )
797
+ failed.append(source)
798
+ if (
799
+ isinstance(exc, remote_ops_ranges.NoRangeError)
800
+ and ranged
801
+ and all(entry[0]["url"] != source["url"] or entry[1] for entry in deferred_slow)
802
+ ):
803
+ deferred_slow.append((source, False))
804
+
805
+
806
+ def _prepare_part(dest: str, size: int, label: str) -> tuple[str, bool]:
807
+ free = shutil.disk_usage(os.path.dirname(dest)).free
808
+ part = dest + ".part"
809
+ had_part = os.path.exists(part)
810
+ have = remote_ops_common.kept_bytes(part, size)
811
+ if have > size:
812
+ remote_ops_common.discard(part)
813
+ had_part, have = False, 0
814
+ if size - have > free:
815
+ raise RuntimeError(f"low disk space: {label} needs {size - have} more bytes, {free} free")
816
+ return part, had_part
817
+
818
+
819
+ def _publish_verified(
820
+ part: str,
821
+ dest: str,
822
+ marker: str,
823
+ sha256: str,
824
+ size: int,
825
+ label: str,
826
+ source: remote_ops_common.Source,
827
+ region: str | None,
828
+ failed: list[remote_ops_common.Source],
829
+ probe_speeds: dict[str, float],
830
+ ) -> str | None:
831
+ remote_ops_common.discard(part + ".ranges") # the record only; part is renamed
832
+ os.replace(part, dest)
833
+ if sha256:
834
+ remote_ops_common.write_text(marker, sha256)
835
+ remote_ops_common.store_cached(dest, sha256, size)
836
+ else:
837
+ remote_ops_common.write_text(marker, remote_ops_common.sha256_file(dest, label))
838
+ switch = _fallback(region, source, failed, probe_speeds)
839
+ extra = {"region_fallback": switch} if switch else {}
840
+ remote_ops_common.emit(
841
+ "log",
842
+ message=f"downloaded and verified {label} from {source['source']}",
843
+ **extra,
844
+ )
845
+ return switch
846
+
847
+
411
848
  def fetch(
412
849
  url: str,
413
850
  dest: str,
@@ -425,96 +862,107 @@ def fetch(
425
862
  marker = dest + ".sha256"
426
863
  if remote_ops_common.existing_verified(dest, marker, sha256, size, label):
427
864
  return None
428
- free = shutil.disk_usage(os.path.dirname(dest)).free
429
- part = dest + ".part"
430
- had_part = os.path.exists(part)
431
- have = remote_ops_common.kept_bytes(part, size)
432
- if have > size:
433
- remote_ops_common.discard(part)
434
- had_part, have = False, 0
435
- if size - have > free:
436
- raise RuntimeError(f"low disk space: {label} needs {size - have} more bytes, {free} free")
865
+ part, had_part = _prepare_part(dest, size, label)
437
866
  sources: list[remote_ops_common.Source] = [{"source": source_name(url), "url": url}]
438
867
  sources += [m for m in mirrors or [] if m.get("url") and m["url"] != url]
439
868
  error: Exception | None = None
440
869
  failed: list[remote_ops_common.Source] = []
441
870
  slow_urls: set[str] = set()
871
+ promoted_urls: set[str] = set()
442
872
  fresh_retried: set[str] = set()
443
- deferred_slow: list[tuple[remote_ops_common.Source, bool]] = []
444
- immediate: list[tuple[remote_ops_common.Source, bool]] = []
873
+ deferred_slow: list[_Ranked] = []
874
+ immediate: list[_Ranked] = []
445
875
  probe_speeds: dict[str, float] = {}
446
- stream = iter(ordered(sources, size, label, region, failed, probe_speeds))
447
- upcoming = next(stream, None)
448
- supports_slow = transfer is DEFAULT_TRANSFER
876
+ heal_sources: list[remote_ops_common.Source] = []
877
+ stream = iter(ordered(sources, size, label, region, failed, probe_speeds, heal_sources))
449
878
 
450
- while immediate or upcoming is not None or deferred_slow:
451
- if immediate:
452
- source, ranged = immediate.pop(0)
453
- elif upcoming is not None:
454
- source, ranged = upcoming
455
- upcoming = next(stream, None)
456
- else:
457
- source, ranged = deferred_slow.pop(0)
458
- probed_bad = any(f["url"] == source["url"] for f in failed)
459
- has_more = (
460
- bool(immediate)
461
- or upcoming is not None
462
- or any(s["url"] not in slow_urls for s, _ in deferred_slow)
463
- )
464
- allow_slow = supports_slow and has_more and source["url"] not in slow_urls
465
- resumed_prior = os.path.exists(part) and os.path.getsize(part) > 0
466
- try:
467
- _transfer_once(
468
- source, part, size, label, ranged, probed_bad=probed_bad, allow_slow=allow_slow
469
- )
470
- except SlowTransferError as exc:
471
- remote_ops_common.emit(
472
- "log",
473
- message=(
474
- f"download from {source['source']} is too slow for {label} ({exc}); "
475
- "switching source"
476
- ),
879
+ def _next_upcoming() -> _Ranked | None:
880
+ while True:
881
+ item = next(stream, None)
882
+ if item is None or item[0]["url"] not in promoted_urls:
883
+ return item
884
+
885
+ upcoming = _next_upcoming()
886
+ supports_slow = transfer is DEFAULT_TRANSFER
887
+ heal = _HealMonitor(heal_sources)
888
+ promote_token = _PROMOTE.set(heal.consider)
889
+ try:
890
+ while immediate or upcoming is not None or deferred_slow:
891
+ if immediate:
892
+ source, ranged = immediate.pop(0)
893
+ elif upcoming is not None:
894
+ source, ranged = upcoming
895
+ upcoming = _next_upcoming()
896
+ else:
897
+ source, ranged = deferred_slow.pop(0)
898
+ probed_bad = any(f["url"] == source["url"] for f in failed)
899
+ has_more = (
900
+ bool(immediate)
901
+ or upcoming is not None
902
+ or any(s["url"] not in slow_urls for s, _ in deferred_slow)
477
903
  )
478
- error = exc
479
- slow_urls.add(source["url"])
480
- deferred_slow.append((source, ranged))
481
- failed.append(source)
482
- continue
483
- except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
484
- remote_ops_common.emit(
485
- "log",
486
- message=(
487
- f"download from {source['source']} stopped, {label}: "
488
- f"{remote_ops_common.redact_text(str(exc))}"
489
- ),
904
+ allow_slow = supports_slow and has_more and source["url"] not in slow_urls
905
+ resumed_prior = os.path.exists(part) and os.path.getsize(part) > 0
906
+ heal.set_active(source["url"])
907
+ try:
908
+ _transfer_once(
909
+ source,
910
+ part,
911
+ size,
912
+ label,
913
+ ranged,
914
+ probed_bad=probed_bad,
915
+ allow_slow=allow_slow,
916
+ )
917
+ except PromoteTransferError as exc:
918
+ _apply_promotion(
919
+ exc,
920
+ source,
921
+ ranged,
922
+ label,
923
+ promoted_urls=promoted_urls,
924
+ failed=failed,
925
+ immediate=immediate,
926
+ deferred_slow=deferred_slow,
927
+ )
928
+ if upcoming is not None and upcoming[0]["url"] in promoted_urls:
929
+ upcoming = _next_upcoming()
930
+ continue
931
+ except SlowTransferError as exc:
932
+ remote_ops_common.emit(
933
+ "log",
934
+ message=(
935
+ f"download from {source['source']} is too slow for {label} ({exc}); "
936
+ "switching source"
937
+ ),
938
+ )
939
+ error = exc
940
+ slow_urls.add(source["url"])
941
+ deferred_slow.append((source, ranged))
942
+ failed.append(source)
943
+ continue
944
+ except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
945
+ _record_transfer_failure(
946
+ exc, source, ranged, label, failed=failed, deferred_slow=deferred_slow
947
+ )
948
+ error = exc
949
+ continue
950
+ mismatch = remote_ops_common.check_part(part, sha256, size, label, source["source"])
951
+ if mismatch is not None:
952
+ error = mismatch
953
+ remote_ops_common.discard(part)
954
+ if resumed_prior and source["url"] not in fresh_retried:
955
+ fresh_retried.add(source["url"])
956
+ immediate.append((source, ranged))
957
+ continue
958
+ return _publish_verified(
959
+ part, dest, marker, sha256, size, label, source, region, failed, probe_speeds
490
960
  )
491
- error = exc
492
- failed.append(source)
493
- continue
494
- mismatch = remote_ops_common.check_part(part, sha256, size, label, source["source"])
495
- if mismatch is not None:
496
- error = mismatch
961
+ if not had_part and remote_ops_common.kept_bytes(part, size) == 0:
497
962
  remote_ops_common.discard(part)
498
- if resumed_prior and source["url"] not in fresh_retried:
499
- fresh_retried.add(source["url"])
500
- immediate.append((source, ranged))
501
- continue
502
- remote_ops_common.discard(part + ".ranges") # the record only; part is renamed
503
- os.replace(part, dest)
504
- if sha256:
505
- remote_ops_common.write_text(marker, sha256)
506
- remote_ops_common.store_cached(dest, sha256, size)
507
- else:
508
- remote_ops_common.write_text(marker, remote_ops_common.sha256_file(dest, label))
509
- switch = _fallback(region, source, failed, probe_speeds)
510
- extra = {"region_fallback": switch} if switch else {}
511
- remote_ops_common.emit(
512
- "log", message=f"downloaded and verified {label} from {source['source']}", **extra
513
- )
514
- return switch
515
- if not had_part and remote_ops_common.kept_bytes(part, size) == 0:
516
- remote_ops_common.discard(part)
517
- raise error or RuntimeError(f"{label} has no download source")
963
+ raise error or RuntimeError(f"{label} has no download source")
964
+ finally:
965
+ _PROMOTE.reset(promote_token)
518
966
 
519
967
 
520
968
  def _missing_members(directory: str, assets: list[remote_ops_common.Archive]) -> set[str]: