@simplexai/localmodels-darwin-arm64 0.1.0-dev.55 → 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.
Files changed (62) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +61 -55
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_admin.py +337 -0
  5. package/modules/localmodels/bifrost_checks.py +23 -10
  6. package/modules/localmodels/bifrost_config.py +13 -5
  7. package/modules/localmodels/bifrost_models.py +2 -1
  8. package/modules/localmodels/catalog.json +12 -9
  9. package/modules/localmodels/engines.py +24 -1
  10. package/modules/localmodels/gateway_accept.py +4 -3
  11. package/modules/localmodels/gateway_bifrost.py +2 -1
  12. package/modules/localmodels/gateway_cli.py +4 -3
  13. package/modules/localmodels/gateway_server.py +3 -1
  14. package/modules/localmodels/harness.py +2 -2
  15. package/modules/localmodels/hf_repo.py +27 -4
  16. package/modules/localmodels/library_floor.py +3 -1
  17. package/modules/localmodels/library_gateway.py +26 -4
  18. package/modules/localmodels/library_jobs.py +44 -6
  19. package/modules/localmodels/library_kept.py +117 -0
  20. package/modules/localmodels/library_model.py +1 -0
  21. package/modules/localmodels/library_order.py +234 -0
  22. package/modules/localmodels/library_poly.py +20 -16
  23. package/modules/localmodels/library_pricing.py +8 -1
  24. package/modules/localmodels/library_serve.py +9 -3
  25. package/modules/localmodels/library_state.py +12 -2
  26. package/modules/localmodels/library_status.py +2 -0
  27. package/modules/localmodels/llm_rank.py +11 -8
  28. package/modules/localmodels/mirrors.py +464 -0
  29. package/modules/localmodels/recommend.py +2 -2
  30. package/modules/localmodels/records.py +1 -0
  31. package/modules/localmodels/region.py +457 -42
  32. package/modules/localmodels/remote_ops.py +130 -33
  33. package/modules/localmodels/remote_ops_download.py +233 -418
  34. package/modules/localmodels/remote_ops_mirrors.py +290 -0
  35. package/modules/localmodels/remote_ops_ranges.py +447 -0
  36. package/modules/localmodels/runtime-lock.json +19 -19
  37. package/modules/localmodels/runtime_auth.py +2 -1
  38. package/modules/localmodels/runtime_cli.py +1 -1
  39. package/modules/localmodels/runtime_install.py +5 -2
  40. package/modules/localmodels/runtime_io.py +5 -6
  41. package/modules/localmodels/runtime_pi.py +2 -1
  42. package/modules/localmodels/runtime_windows_acl.py +39 -0
  43. package/modules/localmodels/setup_inspection.py +4 -0
  44. package/modules/localmodels/source_byok_probe.py +2 -1
  45. package/modules/localmodels/stack.py +13 -3
  46. package/modules/localmodels/stack_auto.py +38 -5
  47. package/modules/localmodels/stack_cli.py +1 -0
  48. package/modules/localmodels/stack_compose.py +2 -1
  49. package/modules/localmodels/stack_events.py +15 -0
  50. package/modules/localmodels/stack_plan.py +5 -1
  51. package/modules/localmodels/stack_progress.py +30 -5
  52. package/modules/localmodels/stack_run.py +117 -0
  53. package/modules/localmodels/stack_try.py +4 -1
  54. package/modules/localmodels/transport.py +2 -0
  55. package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/METADATA +1 -1
  56. package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/RECORD +58 -52
  57. package/package.json +1 -1
  58. package/tool.json +1 -1
  59. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/WHEEL +0 -0
  60. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/entry_points.txt +0 -0
  61. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/NOTICE +0 -0
  62. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -9,13 +9,10 @@ private-name imports.
9
9
 
10
10
  from __future__ import annotations
11
11
 
12
- import collections
13
12
  import contextlib
14
13
  import http.client
15
- import json
16
14
  import os
17
15
  import shutil
18
- import tarfile
19
16
  import threading
20
17
  import time
21
18
  import urllib.error
@@ -24,10 +21,12 @@ import urllib.request
24
21
  from typing import Iterator, Tuple
25
22
 
26
23
  try:
27
- from localmodels import remote_ops, remote_ops_prepare
24
+ from localmodels import remote_ops, remote_ops_mirrors, remote_ops_prepare, remote_ops_ranges
28
25
  except ImportError: # run as a bare file from this directory
29
26
  import remote_ops # type: ignore[import-not-found,no-redef]
27
+ import remote_ops_mirrors # type: ignore[import-not-found,no-redef]
30
28
  import remote_ops_prepare # type: ignore[import-not-found,no-redef]
29
+ import remote_ops_ranges # type: ignore[import-not-found,no-redef]
31
30
 
32
31
  _Ranked = Tuple["remote_ops.Source", bool] # a source and whether it serves byte ranges
33
32
 
@@ -43,20 +42,23 @@ def act_engine(p: remote_ops.EngineParams) -> None:
43
42
  return
44
43
  os.makedirs(directory, exist_ok=True)
45
44
  cache = os.path.join(os.path.dirname(directory), ".archives")
45
+ active_region = p.get("region")
46
46
  for i in remote_ops.each_file(
47
47
  [(os.path.join(cache, a["name"]), a["size_bytes"]) for a in p["assets"]]
48
48
  ):
49
49
  a = p["assets"][i]
50
50
  archive = os.path.join(cache, a["name"])
51
- remote_ops.fetch(
51
+ switched = remote_ops.fetch(
52
52
  a["url"],
53
53
  archive,
54
54
  a["sha256"],
55
55
  a["size_bytes"],
56
56
  a["name"],
57
57
  npm_copies(a),
58
- p.get("region"),
58
+ active_region,
59
59
  )
60
+ if switched in ("cn", "global"):
61
+ active_region = switched
60
62
  remote_ops.unpack(archive, directory, tuple(a.get("members") or ()))
61
63
  if not os.access(binary, os.X_OK):
62
64
  raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
@@ -149,6 +151,7 @@ def act_download(p: remote_ops.DownloadParams) -> None:
149
151
  if not p.get("preparation"):
150
152
  remote_ops_prepare.verify_reused_outputs(p["files"])
151
153
  files = [f for f in p["files"] if not f.get("generated")]
154
+ active_region = p.get("region")
152
155
  for i in remote_ops.each_file(
153
156
  [(remote_ops._expand(f["dest"]), f["size_bytes"]) for f in files]
154
157
  ):
@@ -158,127 +161,83 @@ def act_download(p: remote_ops.DownloadParams) -> None:
158
161
  raise RuntimeError(
159
162
  f"{f['dest']} has no download URL, and the reusable copy failed the SHA256 check"
160
163
  )
161
- remote_ops.fetch(
162
- f["url"], dest, f["sha256"], f["size_bytes"], label, f.get("mirrors"), p.get("region")
164
+ switched = remote_ops.fetch(
165
+ f["url"], dest, f["sha256"], f["size_bytes"], label, f.get("mirrors"), active_region
163
166
  )
167
+ if switched in ("cn", "global"):
168
+ active_region = switched
164
169
  if p.get("preparation"):
165
- remote_ops_prepare.prepare(p["preparation"], p["files"], p.get("region"))
170
+ remote_ops_prepare.prepare(p["preparation"], p["files"], active_region)
166
171
  remote_ops.emit("result", files=len(p["files"]))
167
172
 
168
173
 
169
- # Weights are pinned by SHA256, so any source that serves the same bytes is safe: ``fetch``
170
- # ranks the plan's sources by a short read, downloads from the fastest in parallel byte
171
- # ranges, and moves to the next source on failure or a digest mismatch.
174
+ # Weights and pinned archives are verified by SHA256, so any source serving the same bytes is
175
+ # safe: ``fetch`` concurrently probes candidates, ranks them by actual throughput, downloads in
176
+ # parallel byte ranges, switches away from hosts that stall or throttle mid-transfer, and falls
177
+ # back cleanly on failure or digest mismatch.
172
178
  PROBE_BYTES = 8 << 20
173
- PROBE_TIMEOUT_S = 10.0
174
- SEGMENTS = 4
179
+ PROBE_TIMEOUT_S = 6.0
180
+ PROBE_SAMPLE_S = 3.0 # once sampled for 3s, stop reading slow mirrors instead of waiting 6-10s
181
+ # If the preferred region's fastest reachable candidate is slower than CROSS_REGION_PROBE_BPS,
182
+ # also probe the opposite region's mirrors so a misclassified region or throttled upstream
183
+ # immediately yields to a faster mirror (e.g., 880 KB/s Tsinghua beating 39 KB/s official PyPI).
184
+ CROSS_REGION_PROBE_BPS = 2_000_000
185
+ # Switch away from a transfer whose sustained throughput over SLOW_WINDOW_S stays below
186
+ # SLOW_BYTES_PER_S while more than SLOW_MIN_REMAINING_S of transfer time remains.
187
+ SLOW_WINDOW_S = 15.0
188
+ SLOW_BYTES_PER_S = 256 * 1024
189
+ SLOW_MIN_REMAINING_S = 30.0
190
+ # A file is fetched over up to CONNECTIONS parallel byte ranges of at least MIN_SEGMENT_BYTES
191
+ # each. A connection that finishes its range takes over the second part of the range that will
192
+ # finish last (work stealing), split by the two connections' rates so both end together; a
193
+ # stalled connection loses all of its range. A piece is stolen only when the thief would spend
194
+ # at least STEAL_MIN_S on it, so the extra request (TLS, a Hub redirect) is worth it. Counts come
195
+ # from the 2026-11-24 measurements in docs/local-models/network-download-optimization.md: from
196
+ # China the Hugging Face CDN (also behind hf-mirror) caps each connection near 0.1 MB/s, so 16
197
+ # connections fetch about 16 times as fast; ModelScope reaches the link's ~100 MB/s with 8.
198
+ CONNECTIONS = 8
199
+ SOURCE_CONNECTIONS: dict[str, int] = {"huggingface": 16, "hf-mirror": 16}
175
200
  MIN_SEGMENT_BYTES = 64 << 20
201
+ STEAL_MIN_S = 6.0
202
+ STEAL_MIN_BYTES = 8 << 20 # while no connection's rate is known yet, halve ranges this large
203
+ CLAIM_GRACE_S = 3.0 # a connection's rate is unknown until this long after its first byte
204
+ # A connection with no first byte after this long counts as stalled. The first byte of a Hub
205
+ # range took up to 3 s (a redirect, then TLS to the CDN), so a slow start is not a stall.
206
+ CLAIM_STALL_S = 20.0
207
+ CLAIM_RATE_WINDOW_S = 10.0
208
+ STEAL_POLL_S = 0.5 # how often an idle connection looks for a range to steal
176
209
  ATTEMPTS = 5
177
210
  # A connection's progress moves once per read, so reads stay small: an 8 MiB read at 2-3 MB/s
178
211
  # per connection made the 2 s rate jump in 4 MiB/s steps (often 0). The rate shown is the
179
212
  # average over RATE_WINDOW_S, so a stall or burst of one connection does not swing the ETA.
180
213
  READ_BYTES = 1 << 20
181
214
  RATE_WINDOW_S = 10.0
182
- WEB = ("http", "https")
183
- SOURCE_HOSTS = (
184
- ("hf-mirror.com", "hf-mirror"),
185
- ("huggingface.co", "huggingface"),
186
- ("modelscope.cn", "modelscope"),
187
- ("npmmirror.com", "npmmirror"),
188
- )
189
- # Which side of the network each host serves best. A host on neither (GitHub, a LAN registry,
190
- # a user's own mirror) is neutral: it is never a reason to switch the region.
191
- GLOBAL_HOSTS = ("huggingface.co", "registry.npmjs.org", "nodejs.org")
192
- CN_HOSTS = ("hf-mirror.com", "modelscope.cn", "npmmirror.com")
193
- # The same bytes under another host: (global prefix, cn prefix). Region "cn" tries the cn copy
194
- # first; "global" keeps today's sources first and tries the cn copy only after them.
195
- ALTERNATES = (
196
- ("https://huggingface.co/", "https://hf-mirror.com/"),
197
- ("https://registry.npmjs.org/", "https://registry.npmmirror.com/"),
198
- ("https://nodejs.org/dist/", "https://cdn.npmmirror.com/binaries/node/"),
199
- )
200
- NPM_REGISTRIES = (
201
- ("npm", "https://registry.npmjs.org"),
202
- ("npmmirror", "https://registry.npmmirror.com"),
203
- )
204
- # Region cn's order by label; within one rank the plan's order holds. A non-public source (a
205
- # LAN registry or mirror, remote_ops.non_public) comes first, then ModelScope and the npm
206
- # mirror, then another neutral source (a user's public mirror, the original GitHub asset), then
207
- # hf-mirror.com, then the global hosts.
208
- CN_RANK = {"modelscope": 1, "npmmirror": 1, "custom": 2, "hf-mirror": 3}
209
-
210
-
211
- def cn_rank(source: remote_ops.Source) -> int:
212
- return 0 if remote_ops.non_public(source["url"]) else CN_RANK.get(source["source"], 4)
213
-
214
-
215
- NPM_OVERHEAD_BYTES = 4 << 20
216
-
217
-
218
- def _host_in(url: str, domains: tuple[str, ...]) -> bool:
219
- host = (urllib.parse.urlsplit(url).hostname or "").lower()
220
- return any(host == d or host.endswith("." + d) for d in domains)
221
-
222
-
223
- def source_name(url: str) -> str:
224
- """The public label of a download URL: huggingface, hf-mirror, modelscope, npmmirror or
225
- custom (never the URL)."""
226
- for domain, name in SOURCE_HOSTS:
227
- if _host_in(url, (domain,)):
228
- return name
229
- return "custom"
230
-
231
-
232
- def side(url: str) -> str:
233
- """``cn``, ``global`` or "" (neutral) for a download URL."""
234
- return "cn" if _host_in(url, CN_HOSTS) else "global" if _host_in(url, GLOBAL_HOSTS) else ""
235
-
236
-
237
- def alternates(source: remote_ops.Source) -> list[remote_ops.Source]:
238
- """Other hosts that serve the same path: hf-mirror.com for huggingface.co, the npm mirror for
239
- the npm registry and nodejs.org's releases, and the other way round."""
240
- found: list[remote_ops.Source] = []
241
- for pair in ALTERNATES:
242
- for here, there in (pair, pair[::-1]):
243
- if source["url"].startswith(here):
244
- url = there + source["url"][len(here) :]
245
- other: remote_ops.Source = {"source": source_name(url), "url": url}
246
- if source.get("member"):
247
- other["member"] = source["member"]
248
- found.append(other)
249
- return found
250
-
251
-
252
- def npm_copies(asset: remote_ops.Archive) -> list[remote_ops.Source]:
253
- """The npm packages holding a byte-identical copy of ``asset`` (``npm_copy`` in the engine
254
- and tool locks), on the npm registry and its China mirror; the copy is the package's file of
255
- the asset's name, and its SHA256 pin is the asset's."""
256
- copy = asset.get("npm_copy")
257
- if not copy:
258
- return []
259
- name, version = copy["package"], copy["version"]
260
- tail = f"{name}/-/{name.split('/')[-1]}-{version}.tgz"
261
- return [
262
- {"source": label, "url": f"{base}/{tail}", "member": "package/" + asset["name"]}
263
- for label, base in NPM_REGISTRIES
264
- ]
215
+ WEB = remote_ops_mirrors.WEB
216
+ SOURCE_HOSTS = remote_ops_mirrors.SOURCE_HOSTS
217
+ GLOBAL_HOSTS = remote_ops_mirrors.GLOBAL_HOSTS
218
+ CN_HOSTS = remote_ops_mirrors.CN_HOSTS
219
+ MIRROR_GROUPS = remote_ops_mirrors.MIRROR_GROUPS
220
+ ALTERNATES = remote_ops_mirrors.ALTERNATES
221
+ NPM_REGISTRIES = remote_ops_mirrors.NPM_REGISTRIES
222
+ CN_RANK = remote_ops_mirrors.CN_RANK
223
+ NPM_OVERHEAD_BYTES = remote_ops_mirrors.NPM_OVERHEAD_BYTES
224
+
225
+ cn_rank = remote_ops_mirrors.cn_rank
226
+ source_name = remote_ops_mirrors.source_name
227
+ side = remote_ops_mirrors.side
228
+ alternates = remote_ops_mirrors.alternates
229
+ npm_copies = remote_ops_mirrors.npm_copies
230
+ candidates = remote_ops_mirrors.candidates
231
+ _web = remote_ops_mirrors.is_web
232
+ _state_path = remote_ops_mirrors.state_path
233
+ _load_ranges = remote_ops_mirrors.load_ranges
234
+ _save_ranges = remote_ops_mirrors.save_ranges
235
+ kept_bytes = remote_ops_mirrors.kept_bytes
236
+ discard = remote_ops_mirrors.discard
265
237
 
266
238
 
267
- def candidates(
268
- sources: list[remote_ops.Source], region: str | None
269
- ) -> tuple[list[remote_ops.Source], list[remote_ops.Source]]:
270
- """(the plan's own sources, the alternates added for the region), without duplicates."""
271
- own: list[remote_ops.Source] = []
272
- for s in sources:
273
- if s.get("url") and all(s["url"] != o["url"] for o in own):
274
- own.append(s)
275
- extra: list[remote_ops.Source] = []
276
- if region in ("cn", "global"):
277
- for s in own:
278
- for alt in alternates(s):
279
- if all(alt["url"] != o["url"] for o in own + extra):
280
- extra.append(alt)
281
- return own, extra
239
+ def npm_transfer(source: remote_ops.Source, part: str, size: int, label: str) -> None:
240
+ remote_ops_mirrors.npm_transfer(source, part, size, label, overhead=NPM_OVERHEAD_BYTES)
282
241
 
283
242
 
284
243
  def _ranged_request(url: str, start: int, end: int) -> urllib.request.Request:
@@ -295,8 +254,9 @@ def _range_total(response: object) -> int | None:
295
254
 
296
255
 
297
256
  def probe(url: str, size: int) -> tuple[float, bool] | None:
298
- """Read the first PROBE_BYTES of ``url``: (bytes per second, whether it serves byte ranges),
299
- or None when it fails or names another size (so it cannot be the pinned file)."""
257
+ """Read up to PROBE_BYTES (or for PROBE_SAMPLE_S on slow links) of ``url``: returns
258
+ (bytes per second, whether it serves byte ranges), or None when it fails or names another
259
+ size (so it cannot be the pinned file)."""
300
260
  want = min(size, PROBE_BYTES)
301
261
  start, got = time.monotonic(), 0
302
262
  try:
@@ -308,19 +268,52 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
308
268
  return None
309
269
  if status != 206 and length.isdigit() and int(length) != size:
310
270
  return None
311
- while got < want and time.monotonic() - start < PROBE_TIMEOUT_S:
312
- chunk = r.read(min(1 << 20, want - got))
271
+ read_fn = getattr(r, "read1", r.read)
272
+ while got < want:
273
+ elapsed = time.monotonic() - start
274
+ if elapsed >= PROBE_TIMEOUT_S:
275
+ break
276
+ if got > 0 and elapsed >= PROBE_SAMPLE_S:
277
+ break
278
+ chunk = read_fn(min(1 << 20, want - got))
313
279
  if not chunk:
314
280
  break
315
281
  got += len(chunk)
316
282
  except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
317
283
  return None
284
+ if got <= 0 and want > 0:
285
+ return None
318
286
  return got / max(1e-3, time.monotonic() - start), ranged
319
287
 
320
288
 
321
289
  LONE_SMALL_BYTES = 1 << 20
322
290
 
323
291
 
292
+ def _probe_many(
293
+ sources: list[remote_ops.Source],
294
+ size: int,
295
+ ) -> list[tuple[remote_ops.Source, tuple[float, bool] | None]]:
296
+ """Probe ``sources`` concurrently so multi-mirror ranking completes in one RTT window."""
297
+ if not sources:
298
+ return []
299
+ if len(sources) == 1:
300
+ return [(sources[0], probe(sources[0]["url"], size))]
301
+ results: list[tuple[float, bool] | None] = [None] * len(sources)
302
+
303
+ def run_one(idx: int, src: remote_ops.Source) -> None:
304
+ results[idx] = probe(src["url"], size)
305
+
306
+ threads = [
307
+ threading.Thread(target=run_one, args=(i, s), daemon=True) for i, s in enumerate(sources)
308
+ ]
309
+ for t in threads:
310
+ t.start()
311
+ deadline = time.monotonic() + PROBE_TIMEOUT_S + 2.0
312
+ for t in threads:
313
+ t.join(timeout=max(0.0, deadline - time.monotonic()))
314
+ return list(zip(sources, results))
315
+
316
+
324
317
  def rank(
325
318
  sources: list[remote_ops.Source],
326
319
  size: int,
@@ -337,10 +330,9 @@ def rank(
337
330
  measured: list[tuple[float, int, _Ranked]] = []
338
331
  failed: list[_Ranked] = []
339
332
  notes = []
340
- for i, source in enumerate(sources):
341
- result = probe(source["url"], size)
333
+ for i, (source, result) in enumerate(_probe_many(sources, size)):
342
334
  if result is None: # try ranges anyway: a resumed .part must not restart on a hiccup
343
- failed.append((source, urllib.parse.urlsplit(source["url"]).scheme in WEB))
335
+ failed.append((source, _web(source)))
344
336
  notes.append(source["source"] + " unreachable")
345
337
  if unreachable is not None:
346
338
  unreachable.append(source)
@@ -354,8 +346,86 @@ def rank(
354
346
  return [r for _, _, r in sorted(measured)] + failed
355
347
 
356
348
 
357
- def _web(source: remote_ops.Source) -> bool:
358
- return urllib.parse.urlsplit(source["url"]).scheme in WEB
349
+ def _probe_batch(
350
+ batch: list[remote_ops.Source],
351
+ size: int,
352
+ region: str,
353
+ tier: int,
354
+ failed: list[remote_ops.Source],
355
+ demoted: list[remote_ops.Source],
356
+ notes: list[str],
357
+ scored: list[tuple[float, int, int, int, _Ranked]],
358
+ probe_speeds: dict[str, float] | None,
359
+ ) -> float:
360
+ best = 0.0
361
+ for idx, (src, res) in enumerate(_probe_many(batch, size)):
362
+ if res is None:
363
+ notes.append(src["source"] + " unreachable")
364
+ failed.append(src)
365
+ demoted.append(src)
366
+ continue
367
+ bps, ranged = res
368
+ if probe_speeds is not None:
369
+ probe_speeds[src["url"]] = bps
370
+ best = max(best, bps)
371
+ tie = cn_rank(src) if region == "cn" else idx
372
+ scored.append((-bps, tier, tie, idx, (src, ranged)))
373
+ notes.append("{} {:.2f} MB/s".format(src["source"], bps / 1e6))
374
+ return best
375
+
376
+
377
+ def _ordered_public(
378
+ own: list[remote_ops.Source],
379
+ public_s: list[remote_ops.Source],
380
+ size: int,
381
+ label: str,
382
+ region: str,
383
+ failed: list[remote_ops.Source],
384
+ probe_speeds: dict[str, float] | None,
385
+ ) -> Iterator[_Ranked]:
386
+ public_probe = [s for s in public_s if not s.get("member")]
387
+ public_member = [s for s in public_s if s.get("member")]
388
+ cn_member = [s for s in public_member if side(s["url"]) == "cn"]
389
+ other_member = [s for s in public_member if side(s["url"]) != "cn"]
390
+
391
+ if region == "cn":
392
+ if cn_member and not any(side(s["url"]) == "cn" for s in public_probe):
393
+ yield from ((s, False) for s in cn_member)
394
+ cn_member = []
395
+ primary = sorted([s for s in public_probe if side(s["url"]) == "cn"], key=cn_rank)
396
+ secondary = sorted([s for s in public_probe if side(s["url"]) != "cn"], key=cn_rank)
397
+ else:
398
+ primary = [s for s in own if not s.get("member") and not remote_ops.non_public(s["url"])]
399
+ primary_urls = {s["url"] for s in primary}
400
+ secondary = [s for s in public_probe if s["url"] not in primary_urls]
401
+
402
+ notes: list[str] = []
403
+ scored: list[tuple[float, int, int, int, _Ranked]] = []
404
+ demoted: list[remote_ops.Source] = []
405
+ best_primary = (
406
+ _probe_batch(primary, size, region, 0, failed, demoted, notes, scored, probe_speeds)
407
+ if primary
408
+ else 0.0
409
+ )
410
+ cross_probed = bool(secondary and (not primary or best_primary < CROSS_REGION_PROBE_BPS))
411
+ if cross_probed:
412
+ _probe_batch(secondary, size, region, 1, failed, demoted, notes, scored, probe_speeds)
413
+ if notes:
414
+ remote_ops.emit(
415
+ "log", message=f"download sources for {label} (region {region}): {', '.join(notes)}"
416
+ )
417
+
418
+ scored.sort(key=lambda entry: (entry[0], entry[1], entry[2], entry[3]))
419
+ for _, _, _, _, ranked_entry in scored:
420
+ yield ranked_entry
421
+ tail_members = (cn_member, other_member) if region == "cn" else (other_member, cn_member)
422
+ yield from ((s, False) for s in tail_members[0])
423
+ if region == "cn" and not cross_probed:
424
+ yield from ((s, _web(s)) for s in secondary)
425
+ yield from ((s, False) for s in tail_members[1])
426
+ if region != "cn" and not cross_probed:
427
+ yield from ((s, _web(s)) for s in secondary)
428
+ yield from ((s, _web(s)) for s in demoted)
359
429
 
360
430
 
361
431
  def ordered(
@@ -364,179 +434,35 @@ def ordered(
364
434
  label: str,
365
435
  region: str | None,
366
436
  failed: list[remote_ops.Source],
437
+ probe_speeds: dict[str, float] | None = None,
367
438
  ) -> Iterator[_Ranked]:
368
- """The sources to try in turn. Without a region, ``rank``'s speed order as before. In
369
- global, the plan's own sources keep that order and the cn alternates follow. In cn, the
370
- CN_RANK order: each source is probed only when its turn comes, one that fails the probe is
371
- added to ``failed`` and moved last, and the first that passes is used. npm packages (a
372
- ``member``) cannot be probed for the pinned size; they are tried as they come."""
439
+ """Dynamic speed-first source ordering with tiered cross-region probing."""
373
440
  own, extra = candidates(sources, region)
374
- if region != "cn":
441
+ if region not in ("cn", "global"):
375
442
  yield from rank([s for s in own if not s.get("member")], size, label, failed)
376
- rest = [s for s in own if s.get("member")] + extra
377
- rest.sort(key=lambda s: side(s["url"]) == "cn")
378
- yield from ((s, _web(s) and not s.get("member")) for s in rest)
443
+ yield from ((s, False) for s in own if s.get("member"))
379
444
  return
380
- queue = sorted(own + extra, key=cn_rank)
381
- demoted: list[remote_ops.Source] = []
382
- notes = []
383
- for source in queue:
384
- if source.get("member"):
385
- yield source, False
386
- continue
387
- result = probe(source["url"], size)
388
- if result is None:
389
- notes.append(source["source"] + " unreachable")
390
- failed.append(source)
391
- demoted.append(source)
392
- continue
393
- notes.append("{} {:.1f} MB/s".format(source["source"], result[0] / 1e6))
394
- remote_ops.emit(
395
- "log", message="download source for {} (region cn): {}".format(label, ", ".join(notes))
445
+ all_sources = own + extra
446
+ local_s = [s for s in all_sources if remote_ops.non_public(s["url"])]
447
+ public_s = [s for s in all_sources if not remote_ops.non_public(s["url"])]
448
+ if local_s:
449
+ local_probe = [s for s in local_s if not s.get("member")]
450
+ if local_probe:
451
+ yield from rank(local_probe, size, label, failed)
452
+ yield from ((s, False) for s in local_s if s.get("member"))
453
+ if public_s:
454
+ yield from _ordered_public(own, public_s, size, label, region, failed, probe_speeds)
455
+
456
+
457
+ class SlowTransferError(RuntimeError):
458
+ """Sustained transfer throughput dropped below SLOW_BYTES_PER_S; switch to another host."""
459
+
460
+ def __init__(self, bytes_per_s: int) -> None:
461
+ self.bytes_per_s = bytes_per_s
462
+ super().__init__(
463
+ f"download too slow ({bytes_per_s / 1024:.0f} KB/s < "
464
+ f"{SLOW_BYTES_PER_S / 1024:.0f} KB/s)"
396
465
  )
397
- yield source, result[1]
398
- yield from ((s, _web(s)) for s in demoted)
399
-
400
-
401
- class _NoRangeError(Exception):
402
- """The source stopped honouring byte ranges; the next source is tried."""
403
-
404
-
405
- def _split(start: int, end: int) -> list[list[int]]:
406
- """[start, end, done] segments of [start, end): SEGMENTS of them when each gets at least
407
- MIN_SEGMENT_BYTES, fewer otherwise, never none for a non-empty range."""
408
- count = max(1, min(SEGMENTS, (end - start) // MIN_SEGMENT_BYTES))
409
- step = -(-(end - start) // count)
410
- return [[s, min(end, s + step), s] for s in range(start, end, step)]
411
-
412
-
413
- def _state_path(part: str) -> str:
414
- return part + ".ranges"
415
-
416
-
417
- def kept_bytes(part: str, size: int) -> int:
418
- """Bytes of ``part`` already downloaded: its ranges record when it has one, else its size."""
419
- segments = _load_ranges(part, size)
420
- if segments is not None:
421
- return size - sum(end - done for _, end, done in segments)
422
- return os.path.getsize(part) if os.path.exists(part) else 0
423
-
424
-
425
- def _load_ranges(part: str, size: int) -> list[list[int]] | None:
426
- try:
427
- state = json.loads(remote_ops._read(_state_path(part)))
428
- segments = [[int(a), int(b), int(c)] for a, b, c in state["segments"]]
429
- except (OSError, ValueError, KeyError, TypeError):
430
- return None
431
- if state.get("size") != size or not os.path.exists(part) or os.path.getsize(part) != size:
432
- return None
433
- if any(not 0 <= start <= done <= end <= size for start, end, done in segments):
434
- return None
435
- return segments
436
-
437
-
438
- def _save_ranges(part: str, size: int, segments: list[list[int]]) -> None:
439
- path = _state_path(part)
440
- remote_ops._write(path + ".tmp", json.dumps({"size": size, "segments": segments}))
441
- os.replace(path + ".tmp", path)
442
-
443
-
444
- def discard(part: str) -> None:
445
- for path in (part, _state_path(part)):
446
- if os.path.exists(path):
447
- os.remove(path)
448
-
449
-
450
- def _resume_ranges(part: str, size: int) -> list[list[int]]:
451
- """The segments still to fetch. A plain .part (a single-connection download of an earlier
452
- version) is a finished prefix; the file is then sized so each range writes in place."""
453
- segments = _load_ranges(part, size)
454
- if segments is None:
455
- have = os.path.getsize(part) if os.path.exists(part) else 0
456
- with open(part, "ab") as out:
457
- out.truncate(size)
458
- segments = _split(have, size) if have < size else []
459
- _save_ranges(part, size, segments)
460
- return segments
461
-
462
-
463
- def _retryable(exc: BaseException) -> bool:
464
- """Permanent HTTP responses (unfollowed redirects such as 308, client errors other than
465
- 408/429) will not turn into the pinned file on retry; move on to the next source at once."""
466
- if isinstance(exc, urllib.error.HTTPError):
467
- return exc.code in (408, 429) or exc.code >= 500
468
- return True
469
-
470
-
471
- class _Transfer:
472
- """Parallel ranged download of one file: each segment resumes from its own ``done`` offset
473
- with retries; ``done`` advances only after the bytes are written, so the saved record never
474
- claims bytes the file lacks."""
475
-
476
- def __init__(
477
- self,
478
- url: str,
479
- part: str,
480
- size: int,
481
- segments: list[list[int]],
482
- *,
483
- attempts: int | None = None,
484
- ) -> None:
485
- self.url, self.part, self.size, self.segments = url, part, size, segments
486
- self.attempts = ATTEMPTS if attempts is None else max(1, attempts)
487
- self.lock, self.stop = threading.Lock(), threading.Event()
488
- self.errors: list[BaseException] = []
489
-
490
- def remaining(self) -> int:
491
- with self.lock:
492
- return sum(end - done for _, end, done in self.segments)
493
-
494
- def snapshot(self) -> list[list[int]]:
495
- with self.lock:
496
- return [list(s) for s in self.segments]
497
-
498
- def _range(self, segment: list[int]) -> None:
499
- done, end = segment[2], segment[1]
500
- with urllib.request.urlopen(_ranged_request(self.url, done, end), timeout=60) as r:
501
- if getattr(r, "status", 200) != 206 or not str(
502
- r.headers.get("Content-Range", "")
503
- ).startswith(f"bytes {done}-"):
504
- raise _NoRangeError()
505
- with open(self.part, "r+b", buffering=0) as out:
506
- out.seek(done)
507
- while done < end and not self.stop.is_set():
508
- chunk = r.read(min(READ_BYTES, end - done))
509
- if not chunk:
510
- break
511
- view = memoryview(chunk)
512
- while view:
513
- view = view[out.write(view) or 0 :]
514
- done += len(chunk)
515
- with self.lock:
516
- segment[2] = done
517
- if done < end and not self.stop.is_set():
518
- raise http.client.IncompleteRead(b"", end - done)
519
-
520
- def worker(self, segment: list[int]) -> None:
521
- attempt = 0
522
- while segment[2] < segment[1] and not self.stop.is_set():
523
- try:
524
- self._range(segment)
525
- except _NoRangeError as exc:
526
- self.fail(exc)
527
- except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
528
- attempt += 1
529
- if not _retryable(exc) or attempt >= self.attempts:
530
- self.fail(exc)
531
- return
532
- self.stop.wait(min(30, 2**attempt))
533
- except BaseException as exc: # noqa: BLE001 - reported by the main thread
534
- self.fail(exc)
535
-
536
- def fail(self, exc: BaseException) -> None:
537
- with self.lock:
538
- self.errors.append(exc)
539
- self.stop.set()
540
466
 
541
467
 
542
468
  def transfer(
@@ -547,143 +473,32 @@ def transfer(
547
473
  ranged: bool,
548
474
  *,
549
475
  attempts: int | None = None,
476
+ allow_slow_switch: bool = False,
550
477
  ) -> None:
551
478
  """Fill ``part`` with all ``size`` bytes from ``source``, reporting progress events; raises
552
479
  on failure with the kept ranges saved so the next call (or source) resumes them. A source
553
480
  that turns out not to serve ranges is read once as one plain stream from the start."""
554
481
  if ranged:
555
- job = _Transfer(source["url"], part, size, _resume_ranges(part, size), attempts=attempts)
556
- _run(job, source, label, ranged=True)
557
- if not (job.errors and isinstance(job.errors[0], _NoRangeError)):
558
- _finish(job, label)
482
+ count = remote_ops_ranges.connections_for(source)
483
+ job = remote_ops_ranges._Transfer(
484
+ source["url"],
485
+ part,
486
+ size,
487
+ remote_ops_ranges._resume_ranges(part, size, count),
488
+ attempts=attempts,
489
+ connections=count,
490
+ )
491
+ remote_ops_ranges._run(job, source, label, ranged=True, allow_slow_switch=allow_slow_switch)
492
+ if not (job.errors and isinstance(job.errors[0], remote_ops_ranges._NoRangeError)):
493
+ remote_ops_ranges._finish(job, label)
559
494
  return
560
495
  discard(part)
561
496
  open(part, "wb").close()
562
- job = _Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
563
- _run(job, source, label, ranged=False)
564
- _finish(job, label)
565
-
497
+ job = remote_ops_ranges._Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
498
+ remote_ops_ranges._run(job, source, label, ranged=False, allow_slow_switch=allow_slow_switch)
499
+ remote_ops_ranges._finish(job, label)
566
500
 
567
- def npm_transfer(source: remote_ops.Source, part: str, size: int, label: str) -> None:
568
- """Fill ``part`` with the ``member`` file of the npm package at ``source``: the package is
569
- read in one bounded stream (an npm tarball is a gzip of the file, so a little larger than
570
- it), then only that regular file of exactly ``size`` bytes is taken. The caller checks its
571
- SHA256 against the asset's pin as for any other source."""
572
- archive = part + ".npm"
573
- cap = size + size // 64 + NPM_OVERHEAD_BYTES
574
- request = urllib.request.Request(source["url"], headers={"User-Agent": "localmodels-deploy"})
575
- got, start, mark = 0, time.monotonic(), time.monotonic()
576
- try:
577
- with urllib.request.urlopen(request, timeout=60) as r, open(archive, "wb") as out:
578
- while True:
579
- chunk = r.read(remote_ops._CHUNK)
580
- if not chunk:
581
- break
582
- got += len(chunk)
583
- if got > cap:
584
- raise RuntimeError(f"the npm copy of {label} exceeds its size limit")
585
- out.write(chunk)
586
- if time.monotonic() - mark >= remote_ops._PROGRESS_EVERY_S:
587
- mark = time.monotonic()
588
- remote_ops.emit(
589
- "progress",
590
- phase="download",
591
- file=label,
592
- done=min(got, size),
593
- total=size,
594
- bytes_per_s=int(got / max(1e-3, mark - start)),
595
- source=source["source"],
596
- connections=1,
597
- **remote_ops.step_fields(min(got, size)),
598
- )
599
- with tarfile.open(archive) as tar:
600
- member = tar.getmember(source["member"])
601
- stream = tar.extractfile(member) if member.isfile() and member.size == size else None
602
- if stream is None:
603
- raise RuntimeError(f"the npm copy of {label} does not hold a {size}-byte file")
604
- discard(_state_path(part)) # part is rewritten whole, not resumed
605
- with stream, open(part, "wb") as out:
606
- shutil.copyfileobj(stream, out, remote_ops._CHUNK)
607
- except KeyError:
608
- raise RuntimeError(f"the npm copy of {label} does not hold {source['member']}") from None
609
- finally:
610
- if os.path.exists(archive):
611
- os.remove(archive)
612
-
613
-
614
- def _finish(job: _Transfer, label: str) -> None:
615
- if job.errors:
616
- raise job.errors[0]
617
- if job.remaining():
618
- raise RuntimeError(f"{label} download stopped with bytes missing")
619
-
620
-
621
- class Rate:
622
- """Bytes per second over the last ``window`` seconds of (time, bytes done) samples."""
623
-
624
- def __init__(self, now: float, done: int, window: float | None = None) -> None:
625
- self.window = RATE_WINDOW_S if window is None else window
626
- self.samples: collections.deque[tuple[float, int]] = collections.deque([(now, done)])
627
-
628
- def add(self, now: float, done: int) -> int:
629
- while len(self.samples) > 1 and now - self.samples[1][0] >= self.window:
630
- self.samples.popleft()
631
- then, before = self.samples[0]
632
- self.samples.append((now, done))
633
- return int((done - before) / max(1e-3, now - then))
634
-
635
-
636
- def _run(job: _Transfer, source: remote_ops.Source, label: str, *, ranged: bool) -> None:
637
- if ranged:
638
- threads = [
639
- threading.Thread(target=job.worker, args=(s,), daemon=True)
640
- for s in job.segments
641
- if s[2] < s[1]
642
- ]
643
- else:
644
- threads = [threading.Thread(target=_plain, args=(job,), daemon=True)]
645
- for thread in threads:
646
- thread.start()
647
- size = job.size
648
- mark = time.monotonic()
649
- meter = Rate(mark, size - job.remaining())
650
- while True:
651
- alive = [t for t in threads if t.is_alive()] # the connections open during this interval
652
- if not alive:
653
- break
654
- for t in alive:
655
- t.join(timeout=remote_ops._PROGRESS_EVERY_S / len(alive))
656
- now, done = time.monotonic(), size - job.remaining()
657
- if now - mark >= remote_ops._PROGRESS_EVERY_S:
658
- remote_ops.emit(
659
- "progress",
660
- phase="download",
661
- file=label,
662
- done=done,
663
- total=size,
664
- bytes_per_s=meter.add(now, done),
665
- source=source["source"],
666
- connections=len(alive),
667
- **remote_ops.step_fields(done),
668
- )
669
- mark = now
670
- if ranged:
671
- _save_ranges(job.part, size, job.snapshot())
672
- if ranged:
673
- _save_ranges(job.part, size, job.snapshot())
674
501
 
502
+ DEFAULT_TRANSFER = transfer
675
503
 
676
- def _plain(job: _Transfer) -> None:
677
- """A single unranged stream (a data: URL or a server without Range support)."""
678
- segment = job.segments[0]
679
- try:
680
- with urllib.request.urlopen(
681
- urllib.request.Request(job.url, headers={"User-Agent": "localmodels-deploy"}),
682
- timeout=60,
683
- ) as r, open(job.part, "wb") as out:
684
- for chunk in iter(lambda: r.read(READ_BYTES), b""):
685
- out.write(chunk)
686
- with job.lock:
687
- segment[2] = min(segment[1], segment[2] + len(chunk))
688
- except BaseException as exc: # noqa: BLE001 - reported by the main thread
689
- job.fail(exc)
504
+ Rate = remote_ops_mirrors.Rate