@simplexai/localmodels-darwin-arm64 0.1.0-dev.43 → 0.1.0-dev.45

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 (81) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +76 -79
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +0 -1
  5. package/modules/localmodels/auth_proxy.py +285 -82
  6. package/modules/localmodels/bifrost_checks.py +3 -127
  7. package/modules/localmodels/bifrost_clients.py +1 -1
  8. package/modules/localmodels/bifrost_config.py +2 -2
  9. package/modules/localmodels/bifrost_models.py +9 -2
  10. package/modules/localmodels/bifrost_pi.py +1 -1
  11. package/modules/localmodels/bifrost_provider.py +42 -7
  12. package/modules/localmodels/budget.py +16 -1
  13. package/modules/localmodels/catalog.json +15 -50
  14. package/modules/localmodels/catalog_recipes.py +1 -1
  15. package/modules/localmodels/debug_mode.py +2 -18
  16. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +41 -1
  17. package/modules/localmodels/engines.py +19 -6
  18. package/modules/localmodels/gateway.py +50 -15
  19. package/modules/localmodels/gateway_accept.py +8 -5
  20. package/modules/localmodels/gateway_bifrost.py +23 -13
  21. package/modules/localmodels/gateway_cli.py +5 -2
  22. package/modules/localmodels/gateway_requests.py +9 -2
  23. package/modules/localmodels/harness.py +41 -12
  24. package/modules/localmodels/harness_gateway.py +1 -1
  25. package/modules/localmodels/hosts.py +7 -20
  26. package/modules/localmodels/library_convert.py +491 -57
  27. package/modules/localmodels/library_gateway.py +27 -16
  28. package/modules/localmodels/library_pricing.py +155 -31
  29. package/modules/localmodels/library_status.py +29 -4
  30. package/modules/localmodels/npm_transport.py +62 -54
  31. package/modules/localmodels/probe.py +42 -9
  32. package/modules/localmodels/recommend.py +1 -1
  33. package/modules/localmodels/recommend_cli.py +2 -2
  34. package/modules/localmodels/remote_ops.py +14 -6
  35. package/modules/localmodels/remote_ops_download.py +1 -1
  36. package/modules/localmodels/remote_ops_verify.py +0 -33
  37. package/modules/localmodels/runtime_args.py +2 -1
  38. package/modules/localmodels/runtime_auth.py +75 -25
  39. package/modules/localmodels/runtime_cli.py +9 -9
  40. package/modules/localmodels/runtime_install.py +57 -23
  41. package/modules/localmodels/runtime_io.py +224 -243
  42. package/modules/localmodels/runtime_process.py +15 -7
  43. package/modules/localmodels/runtime_windows_acl.py +196 -0
  44. package/modules/localmodels/source_byok.py +122 -33
  45. package/modules/localmodels/source_byok_probe.py +57 -141
  46. package/modules/localmodels/source_cli.py +19 -18
  47. package/modules/localmodels/stack.py +13 -6
  48. package/modules/localmodels/stack_args.py +6 -8
  49. package/modules/localmodels/stack_binding.py +3 -3
  50. package/modules/localmodels/stack_client_settings.py +8 -1
  51. package/modules/localmodels/stack_compose.py +4 -8
  52. package/modules/localmodels/stack_events.py +2 -1
  53. package/modules/localmodels/stack_plan.py +1 -4
  54. package/modules/localmodels/stack_ports.py +0 -1
  55. package/modules/localmodels/stack_route.py +1 -5
  56. package/modules/localmodels/stack_run.py +15 -30
  57. package/modules/localmodels/stack_suite.py +23 -46
  58. package/modules/localmodels/stack_summary.py +0 -1
  59. package/modules/localmodels/stack_try.py +3 -92
  60. package/modules/localmodels/stack_up.py +27 -4
  61. package/modules/localmodels/stack_update.py +5 -5
  62. package/modules/localmodels/stack_view_apply.py +1 -1
  63. package/modules/localmodels/stack_view_sandbox.py +0 -2
  64. package/modules/localmodels/stack_view_text.py +0 -1
  65. package/modules/localmodels/stack_view_words.py +0 -1
  66. package/modules/localmodels/suite.py +4 -7
  67. package/modules/localmodels/tui_dialogs.py +0 -1
  68. package/modules/localmodels/vision.py +2 -1
  69. package/modules/localmodels/web/view/view.css +1 -4
  70. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/METADATA +1 -1
  71. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/RECORD +73 -76
  72. package/package.json +1 -1
  73. package/tool.json +1 -1
  74. package/modules/localmodels/bifrost_search.py +0 -66
  75. package/modules/localmodels/gateway_search.py +0 -223
  76. package/modules/localmodels/search-ddgs-9.16.1.txt +0 -222
  77. package/modules/localmodels/search_server.py +0 -474
  78. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/WHEEL +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/entry_points.txt +0 -0
  80. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/NOTICE +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -19,12 +19,13 @@ import urllib.error
19
19
  import urllib.parse
20
20
  import urllib.request
21
21
  import zipfile
22
+ from collections import deque
22
23
  from collections.abc import Callable
23
24
  from pathlib import Path
24
25
  from typing import Any, cast
25
26
 
26
27
  # remote_ops before remote_ops_download: the bundle's entry module loads its siblings
27
- from localmodels import region, remote_ops, remote_ops_download
28
+ from localmodels import npm_transport, region, remote_ops, remote_ops_download, runtime_windows_acl
28
29
 
29
30
  Event = Callable[[dict[str, Any]], None]
30
31
 
@@ -53,8 +54,8 @@ def validate_runtime_root(root: Path) -> Path:
53
54
  return root
54
55
 
55
56
 
56
- def private_directory(path: Path) -> None:
57
- """Create each missing directory privately; existing state must already be private."""
57
+ def _create_private_directory(path: Path) -> bool:
58
+ """Create missing directories privately; return True when ``path`` itself was created."""
58
59
  if not path.is_absolute() or any(part == ".." for part in path.parts):
59
60
  raise ValueError("Runtime directory must be absolute and normalized")
60
61
  regular_directories(path)
@@ -65,14 +66,23 @@ def private_directory(path: Path) -> None:
65
66
  current = current.parent
66
67
  if not missing:
67
68
  private_permissions(path)
68
- return
69
+ return False
70
+ created = False
69
71
  for directory in reversed(missing):
70
72
  try:
71
73
  directory.mkdir(mode=0o700)
72
74
  except FileExistsError:
73
75
  private_permissions(directory)
76
+ created = False
74
77
  else:
75
78
  private_permissions(directory, created=True)
79
+ created = True
80
+ return created
81
+
82
+
83
+ def private_directory(path: Path) -> None:
84
+ """Create each missing directory privately; existing state must already be private."""
85
+ _create_private_directory(path)
76
86
 
77
87
 
78
88
  def private_permissions(path: Path, *, created: bool = False) -> None:
@@ -96,199 +106,10 @@ def private_permissions(path: Path, *, created: bool = False) -> None:
96
106
  raise ValueError("Existing runtime state must already be private")
97
107
 
98
108
 
99
- def _windows_api() -> tuple[Any, Any]:
100
- import ctypes
101
-
102
- load: Any = vars(ctypes)["WinDLL"]
103
- api, kernel = load("advapi32", use_last_error=True), load("kernel32", use_last_error=True)
104
- pointer, integer = ctypes.c_void_p, ctypes.c_uint
105
- out = ctypes.POINTER(pointer)
106
- signatures = {
107
- "OpenProcessToken": [pointer, integer, out],
108
- "GetTokenInformation": [pointer, integer, pointer, integer, ctypes.POINTER(integer)],
109
- "GetNamedSecurityInfoW": [ctypes.c_wchar_p, integer, integer, out, out, out, out, out],
110
- "SetNamedSecurityInfoW": [
111
- ctypes.c_wchar_p,
112
- integer,
113
- integer,
114
- pointer,
115
- pointer,
116
- pointer,
117
- pointer,
118
- ],
119
- "EqualSid": [pointer, pointer],
120
- "ConvertSidToStringSidW": [pointer, out],
121
- "ConvertStringSecurityDescriptorToSecurityDescriptorW": [
122
- ctypes.c_wchar_p,
123
- integer,
124
- out,
125
- ctypes.POINTER(integer),
126
- ],
127
- "GetSecurityDescriptorDacl": [
128
- pointer,
129
- ctypes.POINTER(ctypes.c_int),
130
- out,
131
- ctypes.POINTER(ctypes.c_int),
132
- ],
133
- "GetSecurityDescriptorControl": [
134
- pointer,
135
- ctypes.POINTER(ctypes.c_ushort),
136
- ctypes.POINTER(integer),
137
- ],
138
- "GetAce": [pointer, integer, out],
139
- }
140
- for name, arguments in signatures.items():
141
- function = getattr(api, name)
142
- function.argtypes, function.restype = arguments, integer
143
- kernel.GetCurrentProcess.restype = pointer
144
- kernel.CloseHandle.argtypes = [pointer]
145
- kernel.LocalFree.argtypes, kernel.LocalFree.restype = [pointer], pointer
146
- return api, kernel
147
-
148
-
149
- def _windows_private(path: Path, created: bool) -> None:
150
- """Query owner/DACL only; protect a newly created DACL without changing owner/group/SACL."""
151
- import ctypes
152
-
153
- api, kernel = _windows_api()
154
- token, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
155
- try:
156
- if not api.OpenProcessToken(kernel.GetCurrentProcess(), 0x8, ctypes.byref(token)):
157
- raise ValueError("Cannot query current user SID")
158
- size = ctypes.c_uint()
159
- api.GetTokenInformation(token, 1, None, 0, ctypes.byref(size))
160
- buffer = ctypes.create_string_buffer(size.value)
161
- if not api.GetTokenInformation(token, 1, buffer, size, ctypes.byref(size)):
162
- raise ValueError("Cannot query current user SID")
163
- user = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_void_p))[0]
164
- # TokenOwner (4): the owner this process gives what it creates. An elevated
165
- # administrator's token (the built-in Administrator always) names BUILTIN\Administrators,
166
- # so this process's own new files are owned by that group, not by its user.
167
- api.GetTokenInformation(token, 4, None, 0, ctypes.byref(size))
168
- default = ctypes.create_string_buffer(max(size.value, 8))
169
- creator = (
170
- ctypes.cast(default, ctypes.POINTER(ctypes.c_void_p))[0]
171
- if api.GetTokenInformation(token, 4, default, size, ctypes.byref(size))
172
- else None
173
- )
174
- owner, dacl = ctypes.c_void_p(), ctypes.c_void_p()
175
- # OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; never request SACL.
176
- error = api.GetNamedSecurityInfoW(
177
- str(path),
178
- 1,
179
- 0x5,
180
- ctypes.byref(owner),
181
- None,
182
- ctypes.byref(dacl),
183
- None,
184
- ctypes.byref(descriptor),
185
- )
186
- if error or not (
187
- api.EqualSid(owner, user) or (creator is not None and api.EqualSid(owner, creator))
188
- ):
189
- raise ValueError("Runtime state has a foreign or unreadable owner")
190
- if created:
191
- _windows_protect(api, kernel, path, user)
192
- else:
193
- control, revision = ctypes.c_ushort(), ctypes.c_uint()
194
- # Protected (SE_DACL_PROTECTED), or inherited whole from a private parent: a program
195
- # this tool runs (Magpie) replaces its own files, which then inherit that DACL.
196
- if (
197
- not api.GetSecurityDescriptorControl(
198
- descriptor, ctypes.byref(control), ctypes.byref(revision)
199
- )
200
- or not dacl.value
201
- ):
202
- raise ValueError("Existing runtime state must already have a private DACL")
203
- count = ctypes.c_ushort.from_address(dacl.value + 4).value
204
- entries: list[tuple[int, int, int, str]] = []
205
- if count not in (1, 2):
206
- raise ValueError("Existing runtime state must already have a private DACL")
207
- for index in range(count):
208
- ace = ctypes.c_void_p()
209
- if not api.GetAce(dacl, index, ctypes.byref(ace)) or not ace.value:
210
- raise ValueError("Cannot inspect runtime DACL entry")
211
- kind = ctypes.c_ubyte.from_address(ace.value).value
212
- if kind != 0:
213
- raise ValueError("Existing runtime state must already have a private DACL")
214
- entries.append(
215
- (
216
- kind,
217
- ctypes.c_ubyte.from_address(ace.value + 1).value,
218
- ctypes.c_uint.from_address(ace.value + 4).value,
219
- _windows_sid_text(api, kernel, ace.value + 8),
220
- )
221
- )
222
- if not _private_dacl_entries(
223
- entries, _windows_sid_text(api, kernel, user), protected=True,
224
- inherited=not control.value & 0x1000,
225
- ): # fmt: skip
226
- raise ValueError("Existing runtime state must already have a private DACL")
227
- finally:
228
- if descriptor.value:
229
- kernel.LocalFree(descriptor)
230
- if token.value:
231
- kernel.CloseHandle(token)
232
-
233
-
234
- def _private_dacl_entries(
235
- entries: list[tuple[int, int, int, str]],
236
- user_sid: str,
237
- *,
238
- protected: bool,
239
- inherited: bool = False,
240
- ) -> bool:
241
- """A private DACL grants full access to the owner and optionally Local System only. An
242
- ``inherited`` (unprotected) DACL counts only when every entry came from its parent."""
243
- identities = [sid for _, _, _, sid in entries]
244
- return (
245
- protected
246
- and (not inherited or all(flags & 0x10 for _, flags, _, _ in entries))
247
- and len(identities) in (1, 2)
248
- and user_sid in identities
249
- and len(set(identities)) == len(identities)
250
- and set(identities).issubset({user_sid, "S-1-5-18"})
251
- and all(
252
- kind == 0 and not flags & 0x8 and mask & 0x1F01FF == 0x1F01FF
253
- for kind, flags, mask, _ in entries
254
- )
255
- )
256
-
257
-
258
- def _windows_sid_text(api: Any, kernel: Any, sid: Any) -> str:
259
- import ctypes
260
-
261
- text = ctypes.c_void_p()
262
- try:
263
- if not api.ConvertSidToStringSidW(sid, ctypes.byref(text)) or text.value is None:
264
- raise ValueError("Cannot format runtime SID")
265
- return ctypes.wstring_at(text.value)
266
- finally:
267
- if text.value:
268
- kernel.LocalFree(text)
269
-
270
-
271
- def _windows_protect(api: Any, kernel: Any, path: Path, user: Any) -> None:
272
- import ctypes
273
-
274
- security = ctypes.c_void_p()
275
- try:
276
- inheritance = "OICI" if path.is_dir() else ""
277
- sddl = f"D:P(A;{inheritance};FA;;;{_windows_sid_text(api, kernel, user)})"
278
- if not api.ConvertStringSecurityDescriptorToSecurityDescriptorW(
279
- sddl, 1, ctypes.byref(security), None
280
- ):
281
- raise ValueError("Cannot construct private runtime DACL")
282
- present, defaulted, dacl = ctypes.c_int(), ctypes.c_int(), ctypes.c_void_p()
283
- if not api.GetSecurityDescriptorDacl(
284
- security, ctypes.byref(present), ctypes.byref(dacl), ctypes.byref(defaulted)
285
- ):
286
- raise ValueError("Cannot inspect private runtime DACL")
287
- if api.SetNamedSecurityInfoW(str(path), 1, 0x80000004, None, None, dacl, None):
288
- raise ValueError("Cannot protect new runtime state DACL")
289
- finally:
290
- if security.value:
291
- kernel.LocalFree(security)
109
+ _windows_api = runtime_windows_acl.api
110
+ _windows_private = runtime_windows_acl.private_permissions
111
+ _private_dacl_entries = runtime_windows_acl.private_dacl_entries
112
+ _windows_sid_text = runtime_windows_acl.sid_text
292
113
 
293
114
 
294
115
  def _safe_member(name: str) -> Path:
@@ -310,26 +131,72 @@ def _safe_member(name: str) -> Path:
310
131
  return Path(*parts)
311
132
 
312
133
 
134
+ def _ensure_extract_dir(directory: Path, known: set[Path] | None) -> None:
135
+ if known is None:
136
+ private_directory(directory)
137
+ return
138
+ if directory in known:
139
+ return
140
+ missing: list[Path] = []
141
+ current = directory
142
+ while current not in known:
143
+ if current == current.parent:
144
+ raise ValueError("Unsafe archive path")
145
+ missing.append(current)
146
+ current = current.parent
147
+ for part in reversed(missing):
148
+ try:
149
+ part.mkdir(mode=0o700)
150
+ except FileExistsError as exc:
151
+ raise ValueError("Runtime parent must be a directory") from exc
152
+ if os.name != "nt":
153
+ part.chmod(0o700)
154
+ known.add(part)
155
+
156
+
157
+ def _write_extracted(source: Any, destination: Path, mode: int, *, inherited: bool) -> None:
158
+ if inherited:
159
+ flags = (
160
+ os.O_WRONLY
161
+ | os.O_CREAT
162
+ | os.O_EXCL
163
+ | getattr(os, "O_BINARY", 0)
164
+ | getattr(os, "O_NOFOLLOW", 0)
165
+ )
166
+ with os.fdopen(os.open(destination, flags, mode), "wb") as output:
167
+ shutil.copyfileobj(source, output)
168
+ if os.name != "nt":
169
+ destination.chmod(mode)
170
+ return
171
+ with destination.open("xb") as output:
172
+ shutil.copyfileobj(source, output)
173
+ if os.name != "nt":
174
+ destination.chmod(mode)
175
+ private_permissions(destination, created=True)
176
+
177
+
313
178
  def _extract_archive(archive: Path, target: Path) -> None:
314
179
  """Validate the complete member list before writing; never materialize links."""
315
- private_directory(target)
180
+ # A freshly created target has a protected OICI DACL on Windows, so new subdirectories and
181
+ # files beneath it inherit owner-only access without per-file SetNamedSecurityInfoW calls.
182
+ fresh = _create_private_directory(target)
183
+ known = {target} if fresh else None
316
184
  if zipfile.is_zipfile(archive):
317
185
  with zipfile.ZipFile(archive) as stream:
318
186
  members = stream.infolist()
319
187
  for member in members:
320
188
  _safe_member(member.filename)
321
189
  mode = member.external_attr >> 16
322
- if stat.S_ISLNK(mode) or (stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)):
190
+ if stat.S_ISLNK(mode) or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR):
323
191
  raise ValueError("Unsafe archive member")
324
192
  for member in members:
325
193
  destination = target / _safe_member(member.filename)
326
194
  if member.is_dir():
327
- private_directory(destination)
195
+ _ensure_extract_dir(destination, known)
328
196
  else:
329
- private_directory(destination.parent)
330
- with stream.open(member) as source, destination.open("xb") as output:
331
- shutil.copyfileobj(source, output)
332
- private_permissions(destination, created=True)
197
+ _ensure_extract_dir(destination.parent, known)
198
+ with stream.open(member) as source:
199
+ _write_extracted(source, destination, 0o600, inherited=fresh)
333
200
  return
334
201
  with tarfile.open(archive) as tar:
335
202
  # npm tarballs may repeat a/b as a/./b; the last wins, as with tar (scripts/pin_pi.py
@@ -343,19 +210,26 @@ def _extract_archive(archive: Path, target: Path) -> None:
343
210
  for entry in entries:
344
211
  destination = target / _safe_member(entry.name)
345
212
  if entry.isdir():
346
- private_directory(destination)
213
+ _ensure_extract_dir(destination, known)
347
214
  continue
348
- private_directory(destination.parent)
215
+ _ensure_extract_dir(destination.parent, known)
349
216
  tar_source = tar.extractfile(entry)
350
217
  if tar_source is None:
351
218
  raise ValueError("Unsafe archive member")
352
- with tar_source, destination.open("xb") as output:
353
- shutil.copyfileobj(tar_source, output)
354
- destination.chmod(0o700 if entry.mode & 0o111 else 0o600)
355
- private_permissions(destination, created=True)
219
+ with tar_source:
220
+ _write_extracted(
221
+ tar_source, destination, 0o700 if entry.mode & 0o111 else 0o600, inherited=fresh
222
+ )
356
223
 
357
224
 
358
225
  DOWNLOAD_ATTEMPTS = 5
226
+ # One timeout covers the connection, the response headers and each read: a retry resumes the
227
+ # kept bytes, so a stalled connection is cheap to replace and needs no separate read timeout.
228
+ DOWNLOAD_TIMEOUT_S = 15
229
+ # A host that delivers less than SLOW_BYTES_PER_S over a whole SLOW_WINDOW_S window is left for
230
+ # another host serving the same file, when one is still worth trying (see ``download``).
231
+ SLOW_BYTES_PER_S = 512 * 1024
232
+ SLOW_WINDOW_S = 15
359
233
  _RETRY_HTTP = frozenset({408, 425, 429, 500, 502, 503, 504})
360
234
 
361
235
 
@@ -363,13 +237,16 @@ class RuntimeDownloadError(ValueError):
363
237
  """A pinned artifact could not be downloaded. The message names only the host, the file,
364
238
  a fixed reason and the bytes kept: no URL query, header or response body."""
365
239
 
366
- def __init__(self, url: str, reason: str, kept: int, *, retryable: bool) -> None:
240
+ def __init__(
241
+ self, url: str, reason: str, kept: int, *, retryable: bool, slow: bool = False
242
+ ) -> None:
367
243
  parts = urllib.parse.urlsplit(url)
368
244
  self.host = parts.hostname or "the download host"
369
245
  self.file = parts.path.rsplit("/", 1)[-1] or "artifact"
370
246
  self.reason = reason
371
247
  self.kept = kept
372
248
  self.retryable = retryable
249
+ self.slow = slow # the host was left for being too slow, not for failing
373
250
  message = f"Download of {self.file} from {self.host} failed: {reason}."
374
251
  if kept:
375
252
  message += f" {kept} bytes are kept; a retry resumes from there."
@@ -382,16 +259,19 @@ class RuntimeDownloadError(ValueError):
382
259
 
383
260
 
384
261
  class _TransferError(Exception):
385
- def __init__(self, reason: str, *, retryable: bool = True) -> None:
262
+ def __init__(self, reason: str, *, retryable: bool = True, slow: bool = False) -> None:
386
263
  super().__init__(reason)
387
264
  self.reason = reason
388
265
  self.retryable = retryable
266
+ self.slow = slow
389
267
 
390
268
 
391
269
  def _network_reason(exc: BaseException) -> tuple[str, bool]:
392
270
  """A fixed description of a network failure, and whether trying again can help."""
393
271
  if isinstance(exc, urllib.error.HTTPError):
394
272
  return f"HTTP {exc.code}", exc.code in _RETRY_HTTP
273
+ if isinstance(exc, npm_transport.UnsafeRedirect):
274
+ return "the server redirected to a URL without HTTPS or with credentials", False
395
275
  if isinstance(exc, urllib.error.URLError) and isinstance(exc.reason, BaseException):
396
276
  exc = exc.reason
397
277
  if isinstance(exc, ssl.SSLCertVerificationError):
@@ -438,14 +318,25 @@ class Rate:
438
318
  return found
439
319
 
440
320
 
441
- def _transfer(url: str, part: Path, limit: int, event: Event, *, retry_missing: bool) -> None:
442
- """One request for the rest of ``part``; network failures raise _TransferError."""
321
+ def _transfer(
322
+ url: str,
323
+ part: Path,
324
+ limit: int,
325
+ event: Event,
326
+ *,
327
+ retry_missing: bool,
328
+ slow_abort: bool = False,
329
+ clock: Callable[[], float] = time.monotonic,
330
+ ) -> None:
331
+ """One request for the rest of ``part``; network failures raise _TransferError. With
332
+ ``slow_abort``, a whole SLOW_WINDOW_S below SLOW_BYTES_PER_S raises one marked ``slow``."""
443
333
  have = part.stat().st_size
444
334
  request = urllib.request.Request(url, headers={"User-Agent": "localmodels-runtime"})
445
335
  if have:
446
336
  request.add_header("Range", f"bytes={have}-")
447
337
  try:
448
- source = urllib.request.urlopen(request, timeout=30)
338
+ # Redirects stay on HTTPS without credentials, as for every npm download of this tool.
339
+ source = npm_transport.https_opener().open(request, timeout=DOWNLOAD_TIMEOUT_S)
449
340
  except urllib.error.HTTPError as exc:
450
341
  if exc.code == 404 and retry_missing:
451
342
  raise _TransferError("HTTP 404") from None
@@ -465,6 +356,7 @@ def _transfer(url: str, part: Path, limit: int, event: Event, *, retry_missing:
465
356
  length = source.headers.get("Content-Length")
466
357
  total = completed + int(length) if length and length.isdigit() else None
467
358
  rate = Rate(completed)
359
+ window, window_bytes = clock(), 0
468
360
  with part.open("ab" if resumed else "wb") as output:
469
361
  while True:
470
362
  try:
@@ -478,6 +370,17 @@ def _transfer(url: str, part: Path, limit: int, event: Event, *, retry_missing:
478
370
  output.truncate(0)
479
371
  raise ValueError("Runtime artifact exceeds size limit")
480
372
  output.write(chunk)
373
+ window_bytes += len(chunk)
374
+ elapsed = clock() - window
375
+ # The rest arriving within one window at the floor is not worth another host
376
+ # (it also keeps a finished file from being left on its last read).
377
+ near_done = (
378
+ total is not None and total - completed <= SLOW_BYTES_PER_S * SLOW_WINDOW_S
379
+ )
380
+ if slow_abort and elapsed >= SLOW_WINDOW_S and not near_done:
381
+ if window_bytes < SLOW_BYTES_PER_S * elapsed:
382
+ raise _TransferError("the download is too slow", slow=True)
383
+ window, window_bytes = window + elapsed, 0
481
384
  event(
482
385
  {
483
386
  "kind": "progress",
@@ -509,6 +412,11 @@ def download_urls(url: str) -> list[str]:
509
412
  return region.prefer(region.current_region(), [u for u in every if u not in cn], cn)
510
413
 
511
414
 
415
+ def _host(url: str) -> str:
416
+ """The host name of ``url`` alone: events never carry a path, query or credentials."""
417
+ return urllib.parse.urlsplit(url).hostname or ""
418
+
419
+
512
420
  def download(
513
421
  artifact: dict[str, Any],
514
422
  destination: Path,
@@ -517,16 +425,25 @@ def download(
517
425
  attempts: int = DOWNLOAD_ATTEMPTS,
518
426
  pause: Callable[[float], None] = time.sleep,
519
427
  retry_missing: bool = False,
428
+ clock: Callable[[], float] = time.monotonic,
520
429
  ) -> None:
521
430
  """Fetch a pinned artifact into ``destination``, which must not exist. Network failures are
522
431
  retried with backoff and each retry resumes ``destination.part``; a part left by an earlier
523
- call is resumed too. Only content matching the pinned digest is published. When every
524
- retry against one host fails, the next host serving the same file (``download_urls``) is
525
- tried, and a success on the other region's side switches the region."""
526
- urls = download_urls(artifact["url"])
432
+ call is resumed too, also from another host, since the bytes are pinned by digest. Only
433
+ content matching the pinned digest is published.
434
+
435
+ The hosts serving the same file (``download_urls``) are tried in turn. A host that fails
436
+ every retry is dropped. A host slower than SLOW_BYTES_PER_S is left once for the next host
437
+ and queued again last, never to be left for slowness again; only a host followed by one not
438
+ yet left for slowness may be left, so a uniformly slow network switches once and the last
439
+ host always finishes. A success on the other region's side after a failure on the preferred
440
+ side switches the region."""
441
+ urls = deque(download_urls(artifact["url"]))
527
442
  preferred = remote_ops_download.side(urls[0])
528
443
  failed_preferred = False
529
- for index, url in enumerate(urls):
444
+ slow: set[str] = set() # hosts already left once for slowness
445
+ while urls:
446
+ url = urls.popleft()
530
447
  try:
531
448
  _download_from(
532
449
  url,
@@ -536,11 +453,30 @@ def download(
536
453
  attempts=attempts,
537
454
  pause=pause,
538
455
  retry_missing=retry_missing,
456
+ slow_abort=url not in slow and any(u not in slow for u in urls),
457
+ clock=clock,
539
458
  )
540
- except RuntimeDownloadError:
541
- if index + 1 == len(urls):
459
+ except RuntimeDownloadError as exc:
460
+ if exc.slow:
461
+ slow.add(url)
462
+ urls.append(url)
463
+ else:
464
+ # Only a failure moves the region: the region also picks model hubs, so a slow
465
+ # npm mirror must not send a cn user's model downloads to huggingface.co.
466
+ failed_preferred = failed_preferred or remote_ops_download.side(url) == preferred
467
+ if not urls:
542
468
  raise
543
- failed_preferred = failed_preferred or remote_ops_download.side(url) == preferred
469
+ event(
470
+ {
471
+ "kind": "stage",
472
+ "stage": "download",
473
+ "state": "switching",
474
+ "from": _host(url),
475
+ "to": _host(urls[0]),
476
+ "reason": "slow" if exc.slow else exc.reason,
477
+ "completed": exc.kept,
478
+ }
479
+ )
544
480
  continue
545
481
  used = remote_ops_download.side(url)
546
482
  if failed_preferred and used and used != preferred:
@@ -557,6 +493,8 @@ def _download_from(
557
493
  attempts: int,
558
494
  pause: Callable[[float], None],
559
495
  retry_missing: bool,
496
+ slow_abort: bool = False,
497
+ clock: Callable[[], float] = time.monotonic,
560
498
  ) -> None:
561
499
  part = destination.with_name(destination.name + ".part")
562
500
  if destination.exists() or destination.is_symlink():
@@ -569,39 +507,82 @@ def _download_from(
569
507
  flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
570
508
  os.close(os.open(part, flags, 0o600))
571
509
  private_permissions(part, created=True)
572
- attempt = 0
510
+ # Bytes kept by an earlier call: they may be another version's when the pin changed.
511
+ resumed = part.stat().st_size > 0
512
+ if resumed and _matches(part, artifact):
513
+ _publish(part, destination)
514
+ return
573
515
  while True:
574
- attempt += 1
575
- try:
576
- _transfer(url, part, artifact["maxBytes"], event, retry_missing=retry_missing)
577
- break
578
- except _TransferError as exc:
579
- kept = part.stat().st_size
580
- if not exc.retryable or attempt >= attempts:
581
- raise RuntimeDownloadError(url, exc.reason, kept, retryable=exc.retryable) from None
582
- wait = min(30, 2**attempt)
516
+ attempt = 0
517
+ while True:
518
+ attempt += 1
583
519
  event(
584
520
  {
585
521
  "kind": "stage",
586
522
  "stage": "download",
587
- "state": "retrying",
523
+ "state": "connecting",
524
+ "host": _host(url),
588
525
  "attempt": attempt,
589
526
  "attempts": attempts,
590
- "reason": exc.reason,
591
- "completed": kept,
592
- "waitSeconds": wait,
593
527
  }
594
528
  )
595
- pause(wait)
596
- digest = hashlib.new(artifact["algorithm"])
597
- with part.open("rb") as stream:
598
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
599
- digest.update(chunk)
600
- if digest.hexdigest() != artifact["digest"]:
529
+ try:
530
+ _transfer(
531
+ url,
532
+ part,
533
+ artifact["maxBytes"],
534
+ event,
535
+ retry_missing=retry_missing,
536
+ slow_abort=slow_abort,
537
+ clock=clock,
538
+ )
539
+ break
540
+ except _TransferError as exc:
541
+ kept = part.stat().st_size
542
+ if exc.slow: # not retried here: the caller moves to another host
543
+ raise RuntimeDownloadError(
544
+ url, exc.reason, kept, retryable=True, slow=True
545
+ ) from None
546
+ if not exc.retryable or attempt >= attempts:
547
+ raise RuntimeDownloadError(
548
+ url, exc.reason, kept, retryable=exc.retryable
549
+ ) from None
550
+ wait = min(30, 2**attempt)
551
+ event(
552
+ {
553
+ "kind": "stage",
554
+ "stage": "download",
555
+ "state": "retrying",
556
+ "attempt": attempt,
557
+ "attempts": attempts,
558
+ "reason": exc.reason,
559
+ "completed": kept,
560
+ "waitSeconds": wait,
561
+ }
562
+ )
563
+ pause(wait)
564
+ if _matches(part, artifact):
565
+ break
566
+ if resumed: # restart once from zero on this host rather than blame it
567
+ part.write_bytes(b"")
568
+ resumed = False
569
+ continue
601
570
  part.unlink()
602
571
  raise RuntimeDownloadError(
603
572
  url, "the content does not match the pinned digest", 0, retryable=True
604
573
  )
574
+ _publish(part, destination)
575
+
576
+
577
+ def _matches(part: Path, artifact: dict[str, Any]) -> bool:
578
+ digest = hashlib.new(artifact["algorithm"])
579
+ with part.open("rb") as stream:
580
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
581
+ digest.update(chunk)
582
+ return bool(digest.hexdigest() == artifact["digest"])
583
+
584
+
585
+ def _publish(part: Path, destination: Path) -> None:
605
586
  part.rename(destination)
606
587
  private_permissions(destination)
607
588
 
@@ -98,7 +98,8 @@ PROBE_TIMEOUT = -1000
98
98
  # A just-unpacked executable can be briefly unavailable to CreateProcess on Windows (for
99
99
  # example while antivirus or indexing scans or locks it), so these spawn errors are retried.
100
100
  SPAWN_RETRY_DELAYS = (0.25, 0.5, 1.0, 2.0, 4.0, 4.0)
101
- _RETRYABLE_WINERRORS = (2, 5, 32, 225)
101
+ _WINERROR_FILE_NOT_FOUND = 2
102
+ _LOCKED_WINERRORS = (5, 32, 225)
102
103
 
103
104
 
104
105
  # taskkill's exit code when the PID no longer exists: the child exited before cleanup reached it.
@@ -141,16 +142,23 @@ def _spawn(
141
142
  )
142
143
  except OSError as error:
143
144
  winerror = getattr(error, "winerror", None)
145
+ absolute = bool(argv and Path(argv[0]).is_absolute())
146
+ exists = "unknown"
147
+ if absolute:
148
+ with contextlib.suppress(OSError, ValueError):
149
+ exists = "true" if Path(argv[0]).exists() else "false"
150
+ # Bare PATH names and absent paths failing with ERROR_FILE_NOT_FOUND are ordinary
151
+ # "not installed" results; only retry locks or a present absolute executable.
144
152
  retrying = (
145
153
  _windows()
146
- and winerror in _RETRYABLE_WINERRORS
154
+ and absolute
147
155
  and attempt <= len(SPAWN_RETRY_DELAYS)
156
+ and (
157
+ winerror in _LOCKED_WINERRORS
158
+ or (winerror == _WINERROR_FILE_NOT_FOUND and exists != "false")
159
+ )
148
160
  )
149
- # A bare PATH name that fails to spawn is an ordinary "not installed" result.
150
- if argv and Path(argv[0]).is_absolute():
151
- exists = "unknown"
152
- with contextlib.suppress(OSError, ValueError):
153
- exists = "true" if Path(argv[0]).exists() else "false"
161
+ if absolute:
154
162
  _diagnose(
155
163
  "spawn failed",
156
164
  attempt=attempt,