@simplexai/localmodels-darwin-arm64 0.1.0-dev.49 → 0.1.0-dev.50

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 (52) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +51 -45
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/catalog.json +416 -2
  5. package/modules/localmodels/download-mirrors.json +47 -0
  6. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  7. package/modules/localmodels/gateway.py +23 -6
  8. package/modules/localmodels/gateway_bifrost.py +6 -2
  9. package/modules/localmodels/harness.py +8 -2
  10. package/modules/localmodels/harness_gateway.py +78 -17
  11. package/modules/localmodels/harness_probe.py +5 -1
  12. package/modules/localmodels/hosts.py +52 -5
  13. package/modules/localmodels/library_floor.py +76 -0
  14. package/modules/localmodels/library_jobs.py +38 -6
  15. package/modules/localmodels/library_poly.py +272 -0
  16. package/modules/localmodels/library_pricing.py +24 -35
  17. package/modules/localmodels/library_serve.py +7 -0
  18. package/modules/localmodels/library_state.py +16 -0
  19. package/modules/localmodels/library_status.py +27 -7
  20. package/modules/localmodels/llm_rank.py +14 -0
  21. package/modules/localmodels/magpie_windows.py +312 -0
  22. package/modules/localmodels/probe.py +1 -1
  23. package/modules/localmodels/remote_ops.py +11 -0
  24. package/modules/localmodels/remote_ops_download.py +30 -5
  25. package/modules/localmodels/reuse.py +13 -6
  26. package/modules/localmodels/runtime_io.py +32 -18
  27. package/modules/localmodels/setup_inspection.py +83 -79
  28. package/modules/localmodels/setup_inspection_harness.py +147 -0
  29. package/modules/localmodels/setup_text.py +12 -0
  30. package/modules/localmodels/setup_upgrade.py +11 -1
  31. package/modules/localmodels/stack.py +3 -1
  32. package/modules/localmodels/stack_auto.py +6 -2
  33. package/modules/localmodels/stack_clients.py +1 -1
  34. package/modules/localmodels/stack_down.py +25 -16
  35. package/modules/localmodels/stack_hardware.py +12 -1
  36. package/modules/localmodels/stack_picks.py +28 -13
  37. package/modules/localmodels/stack_remove.py +3 -1
  38. package/modules/localmodels/stack_suite.py +29 -8
  39. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  40. package/modules/localmodels/strata_poly_server.py +14 -2
  41. package/modules/localmodels/suite.py +19 -3
  42. package/modules/localmodels/tool_archive.py +4 -0
  43. package/modules/localmodels/vision.py +4 -2
  44. package/modules/localmodels/win_probe.py +24 -7
  45. package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/METADATA +1 -1
  46. package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/RECORD +48 -42
  47. package/package.json +1 -1
  48. package/tool.json +1 -1
  49. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/WHEEL +0 -0
  50. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/entry_points.txt +0 -0
  51. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/NOTICE +0 -0
  52. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,312 @@
1
+ """Windows multi-hop successor adoption for private ``magpie serve`` instances.
2
+
3
+ Controller-side (Layer 4): ``process_windows`` stays self-contained Python 3.8 inside
4
+ ``BUNDLES["remote_ops"]`` so it cannot import ``runtime_io``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+ import json
11
+ import os
12
+ import posixpath
13
+ import stat
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from localmodels import process_identity, process_windows, runtime_io
18
+
19
+
20
+ def _read_windows_argv0(text: str) -> tuple[str, int]:
21
+ """Read argv[0] per Windows CommandLineToArgvW (quotes toggle; backslashes are literal)."""
22
+ index, length, in_quotes = 0, len(text), False
23
+ buf: list[str] = []
24
+ while index < length:
25
+ ch = text[index]
26
+ if ch == '"':
27
+ in_quotes = not in_quotes
28
+ elif ch in " \t" and not in_quotes:
29
+ break
30
+ else:
31
+ buf.append(ch)
32
+ index += 1
33
+ return "".join(buf), index
34
+
35
+
36
+ def _read_windows_arg(text: str, index: int) -> tuple[str, int]:
37
+ """Read one non-argv[0] argument per Windows CommandLineToArgvW backslash/quote rules."""
38
+ length, in_quotes = len(text), False
39
+ buf: list[str] = []
40
+ while index < length:
41
+ ch = text[index]
42
+ if ch in " \t" and not in_quotes:
43
+ break
44
+ if ch == "\\":
45
+ slashes = 0
46
+ while index < length and text[index] == "\\":
47
+ slashes += 1
48
+ index += 1
49
+ if index < length and text[index] == '"':
50
+ buf.append("\\" * (slashes // 2))
51
+ if slashes % 2:
52
+ buf.append('"')
53
+ else:
54
+ in_quotes = not in_quotes
55
+ index += 1
56
+ else:
57
+ buf.append("\\" * slashes)
58
+ elif ch == '"':
59
+ if in_quotes and index + 1 < length and text[index + 1] == '"':
60
+ buf.append('"')
61
+ index += 2
62
+ else:
63
+ in_quotes = not in_quotes
64
+ index += 1
65
+ else:
66
+ buf.append(ch)
67
+ index += 1
68
+ return "".join(buf), index
69
+
70
+
71
+ def split_windows_cmdline(cmdline: str) -> list[str]:
72
+ """Parse a Windows command line into argv tokens following CommandLineToArgvW rules."""
73
+ text = cmdline.lstrip(" \t")
74
+ if not text:
75
+ return []
76
+ arg0, index = _read_windows_argv0(text)
77
+ args = [arg0]
78
+ length = len(text)
79
+ while index < length:
80
+ while index < length and text[index] in " \t":
81
+ index += 1
82
+ if index >= length:
83
+ break
84
+ arg, index = _read_windows_arg(text, index)
85
+ args.append(arg)
86
+ return args
87
+
88
+
89
+ def _is_magpie_serve_argv(argv: list[str]) -> bool:
90
+ """True only when ``serve`` is the actual Magpie subcommand (argv[1]), not a path segment."""
91
+ return len(argv) >= 2 and argv[1].lower() == "serve"
92
+
93
+
94
+ def _parse_windows_env_block(raw: bytes) -> dict[str, str]:
95
+ """Decode a Windows UTF-16LE double-NUL-terminated environment block (uppercased keys)."""
96
+ if len(raw) % 2:
97
+ raw = raw[:-1]
98
+ env: dict[str, str] = {}
99
+ for entry in raw.decode("utf-16-le", errors="replace").split("\x00"):
100
+ if not entry:
101
+ break
102
+ if "=" not in entry or entry.startswith("="):
103
+ continue
104
+ key, _, value = entry.partition("=")
105
+ env[key.upper()] = value
106
+ return env
107
+
108
+
109
+ def _read_remote_ptr(read_mem: Any, handle: Any, addr: int, ptr_size: int) -> int | None:
110
+ val = ctypes.c_size_t(0)
111
+ got = ctypes.c_size_t(0)
112
+ if not read_mem(handle, addr, ctypes.byref(val), ptr_size, ctypes.byref(got)):
113
+ return None
114
+ return int(val.value) if got.value == ptr_size else None
115
+
116
+
117
+ def process_environment(pid: int) -> dict[str, str] | None:
118
+ """Windows: read PID's PEB environment block via NtQueryInformationProcess + ReadProcessMemory.
119
+ Returns uppercased env mapping, or None when unavailable or off Windows."""
120
+ load: Any = getattr(ctypes, "WinDLL", None)
121
+ if load is None:
122
+ return None
123
+ from ctypes import wintypes
124
+
125
+ class BasicInfo(ctypes.Structure):
126
+ _fields_ = [
127
+ ("Reserved1", ctypes.c_void_p),
128
+ ("PebBaseAddress", ctypes.c_void_p),
129
+ ("Reserved2", ctypes.c_void_p * 2),
130
+ ("UniqueProcessId", ctypes.c_void_p),
131
+ ("Reserved3", ctypes.c_void_p),
132
+ ]
133
+
134
+ kernel, _ = process_identity._api()
135
+ ntdll = load("ntdll")
136
+ query = ntdll.NtQueryInformationProcess
137
+ query.argtypes = (
138
+ wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.ULONG, ctypes.POINTER(wintypes.ULONG)
139
+ ) # fmt: skip
140
+ query.restype = ctypes.c_long
141
+ read_mem = kernel.ReadProcessMemory
142
+ read_mem.argtypes = (
143
+ wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)
144
+ ) # fmt: skip
145
+ read_mem.restype = wintypes.BOOL
146
+ # PROCESS_QUERY_INFORMATION (0x0400) | PROCESS_VM_READ (0x0010)
147
+ handle = kernel.OpenProcess(0x0410, False, pid)
148
+ if not handle:
149
+ return None
150
+ try:
151
+ info = BasicInfo()
152
+ ret_len = wintypes.ULONG(0)
153
+ if query(handle, 0, ctypes.byref(info), ctypes.sizeof(info), ctypes.byref(ret_len)) != 0:
154
+ return None
155
+ if not info.PebBaseAddress:
156
+ return None
157
+ ptr_size = ctypes.sizeof(ctypes.c_size_t)
158
+ params_ptr = _read_remote_ptr(
159
+ read_mem, handle, int(info.PebBaseAddress) + (0x20 if ptr_size == 8 else 0x10), ptr_size
160
+ )
161
+ if not params_ptr:
162
+ return None
163
+ env_ptr = _read_remote_ptr(
164
+ read_mem, handle, params_ptr + (0x80 if ptr_size == 8 else 0x48), ptr_size
165
+ )
166
+ env_size = _read_remote_ptr(
167
+ read_mem, handle, params_ptr + (0x3F0 if ptr_size == 8 else 0x290), ptr_size
168
+ )
169
+ if not env_ptr or not env_size:
170
+ return None
171
+ to_read = min(env_size, 1 << 20)
172
+ buf = ctypes.create_string_buffer(to_read)
173
+ got = ctypes.c_size_t(0)
174
+ if not read_mem(handle, env_ptr, buf, to_read, ctypes.byref(got)) or got.value < 2:
175
+ return None
176
+ return _parse_windows_env_block(buf.raw[: got.value])
177
+ except OSError:
178
+ return None
179
+ finally:
180
+ kernel.CloseHandle(handle)
181
+
182
+
183
+ def _norm_path(value: str | Path) -> str:
184
+ text = str(value).strip()
185
+ if not text:
186
+ return ""
187
+ if os.name == "nt":
188
+ return os.path.normcase(os.path.realpath(text)).replace("\\", "/").rstrip("/")
189
+ slashed = text.replace("\\", "/")
190
+ if (len(slashed) >= 2 and slashed[1] == ":") or slashed.startswith("//"):
191
+ prefix = "//" if slashed.startswith("//") else ""
192
+ return (
193
+ (prefix + posixpath.normpath(slashed.lstrip("/") if prefix else slashed))
194
+ .rstrip("/")
195
+ .lower()
196
+ )
197
+ return os.path.realpath(slashed).rstrip("/").lower()
198
+
199
+
200
+ def _env_matches_gateway_home(env: dict[str, str], gateway_home: str | Path) -> bool:
201
+ """True only when the process environment positively targets this private ``gateway_home``."""
202
+ home_norm = _norm_path(gateway_home)
203
+ cfg_norm = _norm_path(Path(gateway_home) / ".config" / "magpie")
204
+ if not home_norm:
205
+ return False
206
+ upper = {k.upper(): v for k, v in env.items()}
207
+ if cfg := upper.get("MAGPIE_CONFIG_DIR", "").strip():
208
+ return _norm_path(cfg) == cfg_norm
209
+ userprofile = upper.get("USERPROFILE", "").strip()
210
+ if userprofile:
211
+ return _norm_path(userprofile) == home_norm
212
+ home = upper.get("HOME", "").strip()
213
+ return bool(home) and _norm_path(home) == home_norm
214
+
215
+
216
+ def _non_link_stat(path: Path) -> os.stat_result | None:
217
+ try:
218
+ info = path.lstat()
219
+ except OSError:
220
+ return None
221
+ if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
222
+ return None
223
+ return info
224
+
225
+
226
+ def _serving_lock_pid(gateway_home: str | Path) -> int | None:
227
+ """PID stored in private non-symlink ``gateway.serving.lock`` if readable; None otherwise."""
228
+ home = Path(gateway_home)
229
+ for parent in (home, home / ".config", home / ".config" / "magpie"):
230
+ pinfo = _non_link_stat(parent)
231
+ if pinfo is None or not stat.S_ISDIR(pinfo.st_mode):
232
+ return None
233
+ lock = home / ".config" / "magpie" / "gateway.serving.lock"
234
+ info = _non_link_stat(lock)
235
+ if info is None or not stat.S_ISREG(info.st_mode):
236
+ return None
237
+ try:
238
+ if os.name == "nt":
239
+ runtime_io.private_permissions(lock)
240
+ raw = lock.read_text(encoding="utf-8").strip()
241
+ except (OSError, ValueError):
242
+ return None
243
+ if raw.isdigit():
244
+ return int(raw)
245
+ try:
246
+ doc = json.loads(raw)
247
+ except ValueError:
248
+ return None
249
+ pid = doc.get("pid") if isinstance(doc, dict) else None
250
+ return pid if isinstance(pid, int) and not isinstance(pid, bool) and pid > 0 else None
251
+
252
+
253
+ def magpie_successor_pid(
254
+ saved: process_identity.Identity,
255
+ program: str,
256
+ port: int,
257
+ gateway_home: str | Path | None = None,
258
+ ) -> int | None:
259
+ """Windows: identify a single verified multi-hop successor of an owned ``magpie serve``
260
+ listening on the approved ``port`` (for example after periodic self-restarts broke the
261
+ 1-hop parent-PID chain). Fails closed: requires positive proof linking the listener to
262
+ ``gateway_home`` (private ``gateway.serving.lock`` PID match or matching PEB environment)."""
263
+ if gateway_home is None:
264
+ return None
265
+ listeners = process_identity.listener_pids(port)
266
+ if not listeners or len(listeners) != 1:
267
+ return None
268
+ cand = next(iter(listeners))
269
+ if cand <= 0:
270
+ return None
271
+ found = process_identity._windows_inspect(cand)
272
+ if found is None or found["uid"] != 0 or int(found["started"]) <= int(saved["started"]):
273
+ return None
274
+ if not process_identity._windows_command_matches(cand, [program]):
275
+ return None
276
+ cmdline = process_windows.command_line(cand)
277
+ if cmdline is not None and not _is_magpie_serve_argv(split_windows_cmdline(cmdline)):
278
+ return None
279
+ lock_pid = _serving_lock_pid(gateway_home)
280
+ if lock_pid is not None:
281
+ return cand if lock_pid == cand else None
282
+ if cmdline is None:
283
+ return None
284
+ proc_env = process_environment(cand)
285
+ if proc_env is None or not _env_matches_gateway_home(proc_env, gateway_home):
286
+ return None
287
+ return cand
288
+
289
+
290
+ def adopt_magpie_successor(
291
+ pid_file: str | Path,
292
+ program: str,
293
+ port: int | None = None,
294
+ gateway_home: str | Path | None = None,
295
+ ) -> bool:
296
+ """Adopt a restarted Windows ``magpie serve``: 1-hop child first, then multi-hop listener."""
297
+ if process_identity.adopt_successor(pid_file, program):
298
+ return True
299
+ if not process_identity._windows() or port is None:
300
+ return False
301
+ path = Path(pid_file)
302
+ try:
303
+ saved = process_identity._recorded(path)
304
+ if saved is None or process_identity._windows_inspect(saved["pid"]) is not None:
305
+ return False
306
+ cand = magpie_successor_pid(saved, program, port, gateway_home)
307
+ if cand is None:
308
+ return False
309
+ process_identity.save(path, cand)
310
+ return True
311
+ except (OSError, ValueError, RuntimeError):
312
+ return False
@@ -181,7 +181,7 @@ class HostFacts(RequiredHostFacts, total=False):
181
181
  memory_bandwidth: MemoryBandwidth # only after probe --measure-bandwidth
182
182
  shared_libraries: dict[str, bool] # HOST_LIBRARIES: can the loader find each one
183
183
  metal: dict[str, object] | None # metal_probe.py on Apple Silicon (2026-10-29; metal.Metal)
184
- gpu_processes: list[win_probe.GpuAppMemory] # Windows WDDM per-app dedicated VRAM (CIM)
184
+ gpu_processes: list[win_probe.GpuAppMemory] # Windows WDDM per-app local VRAM (CIM)
185
185
 
186
186
 
187
187
  SCHEMA = "localmodels.host-facts/v1"
@@ -406,9 +406,11 @@ def fetch(
406
406
  return None
407
407
  free = shutil.disk_usage(os.path.dirname(dest)).free
408
408
  part = dest + ".part"
409
+ had_part = os.path.exists(part)
409
410
  have = remote_ops_download.kept_bytes(part, size)
410
411
  if have > size:
411
412
  remote_ops_download.discard(part)
413
+ had_part = False
412
414
  have = 0
413
415
  if size - have > free:
414
416
  raise RuntimeError(f"low disk space: {label} needs {size - have} more bytes, {free} free")
@@ -417,9 +419,12 @@ def fetch(
417
419
  error: Exception | None = None
418
420
  failed: list[Source] = []
419
421
  for source, ranged in remote_ops_download.ordered(sources, size, label, region, failed):
422
+ probed_bad = any(f["url"] == source["url"] for f in failed)
420
423
  try:
421
424
  if source.get("member"):
422
425
  remote_ops_download.npm_transfer(source, part, size, label)
426
+ elif probed_bad:
427
+ remote_ops_download.transfer(source, part, size, label, ranged, attempts=1)
423
428
  else:
424
429
  remote_ops_download.transfer(source, part, size, label, ranged)
425
430
  except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
@@ -445,6 +450,8 @@ def fetch(
445
450
  extra = {"region_fallback": switch} if switch else {}
446
451
  emit("log", message=f"downloaded and verified {label} from {source['source']}", **extra)
447
452
  return switch
453
+ if not had_part and remote_ops_download.kept_bytes(part, size) == 0:
454
+ remote_ops_download.discard(part)
448
455
  raise error or RuntimeError(f"{label} has no download source")
449
456
 
450
457
 
@@ -511,6 +518,10 @@ def unpack(archive: str, directory: str, keep: tuple[str, ...] = ()) -> None:
511
518
  if member.islnk() and strip:
512
519
  member.linkname = target.lstrip("./").split("/", 1)[-1]
513
520
  member.name = name
521
+ if member.isdir():
522
+ member.mode |= 0o700
523
+ elif member.isfile():
524
+ member.mode |= 0o200
514
525
  tar.extract(member, directory)
515
526
 
516
527
 
@@ -454,13 +454,30 @@ def _resume_ranges(part: str, size: int) -> list[list[int]]:
454
454
  return segments
455
455
 
456
456
 
457
+ def _retryable(exc: BaseException) -> bool:
458
+ """Permanent HTTP responses (unfollowed redirects such as 308, client errors other than
459
+ 408/429) will not turn into the pinned file on retry; move on to the next source at once."""
460
+ if isinstance(exc, urllib.error.HTTPError):
461
+ return exc.code in (408, 429) or exc.code >= 500
462
+ return True
463
+
464
+
457
465
  class _Transfer:
458
466
  """Parallel ranged download of one file: each segment resumes from its own ``done`` offset
459
467
  with retries; ``done`` advances only after the bytes are written, so the saved record never
460
468
  claims bytes the file lacks."""
461
469
 
462
- def __init__(self, url: str, part: str, size: int, segments: list[list[int]]) -> None:
470
+ def __init__(
471
+ self,
472
+ url: str,
473
+ part: str,
474
+ size: int,
475
+ segments: list[list[int]],
476
+ *,
477
+ attempts: int | None = None,
478
+ ) -> None:
463
479
  self.url, self.part, self.size, self.segments = url, part, size, segments
480
+ self.attempts = ATTEMPTS if attempts is None else max(1, attempts)
464
481
  self.lock, self.stop = threading.Lock(), threading.Event()
465
482
  self.errors: list[BaseException] = []
466
483
 
@@ -503,7 +520,7 @@ class _Transfer:
503
520
  self.fail(exc)
504
521
  except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
505
522
  attempt += 1
506
- if attempt >= ATTEMPTS:
523
+ if not _retryable(exc) or attempt >= self.attempts:
507
524
  self.fail(exc)
508
525
  return
509
526
  self.stop.wait(min(30, 2**attempt))
@@ -516,19 +533,27 @@ class _Transfer:
516
533
  self.stop.set()
517
534
 
518
535
 
519
- def transfer(source: remote_ops.Source, part: str, size: int, label: str, ranged: bool) -> None:
536
+ def transfer(
537
+ source: remote_ops.Source,
538
+ part: str,
539
+ size: int,
540
+ label: str,
541
+ ranged: bool,
542
+ *,
543
+ attempts: int | None = None,
544
+ ) -> None:
520
545
  """Fill ``part`` with all ``size`` bytes from ``source``, reporting progress events; raises
521
546
  on failure with the kept ranges saved so the next call (or source) resumes them. A source
522
547
  that turns out not to serve ranges is read once as one plain stream from the start."""
523
548
  if ranged:
524
- job = _Transfer(source["url"], part, size, _resume_ranges(part, size))
549
+ job = _Transfer(source["url"], part, size, _resume_ranges(part, size), attempts=attempts)
525
550
  _run(job, source, label, ranged=True)
526
551
  if not (job.errors and isinstance(job.errors[0], _NoRangeError)):
527
552
  _finish(job, label)
528
553
  return
529
554
  discard(part)
530
555
  open(part, "wb").close()
531
- job = _Transfer(source["url"], part, size, [[0, size, 0]])
556
+ job = _Transfer(source["url"], part, size, [[0, size, 0]], attempts=attempts)
532
557
  _run(job, source, label, ranged=False)
533
558
  _finish(job, label)
534
559
 
@@ -194,7 +194,11 @@ def _walk(root: Path, depth: int = 0) -> Iterator[Path]:
194
194
  except OSError:
195
195
  return
196
196
  for entry in entries:
197
- if entry.is_dir(follow_symlinks=False):
197
+ try:
198
+ is_dir = entry.is_dir(follow_symlinks=False)
199
+ except OSError:
200
+ continue
201
+ if is_dir:
198
202
  if depth < MAX_DEPTH and entry.name not in SKIP_DIRS:
199
203
  yield from _walk(Path(entry.path), depth + 1)
200
204
  elif entry.name.endswith(".gguf"):
@@ -204,8 +208,11 @@ def _walk(root: Path, depth: int = 0) -> Iterator[Path]:
204
208
  def device(path: str) -> int | None:
205
209
  """The filesystem a path is or would be on: that of its nearest existing ancestor."""
206
210
  for candidate in (Path(path), *Path(path).parents):
207
- if candidate.exists():
208
- return candidate.stat().st_dev
211
+ try:
212
+ if candidate.exists():
213
+ return candidate.stat().st_dev
214
+ except OSError:
215
+ continue
209
216
  return None
210
217
 
211
218
 
@@ -230,18 +237,18 @@ def find_copies(
230
237
  spec = wanted.get(path.name)
231
238
  if spec is None or path.name in found:
232
239
  continue
233
- real = os.path.realpath(path)
234
240
  dest = os.path.expanduser(spec[1])
235
241
  try:
242
+ real = os.path.realpath(path)
236
243
  same = (
237
244
  os.path.isfile(real)
238
245
  and os.path.getsize(real) == spec[0]
239
246
  and (allow_cross_device or os.stat(real).st_dev == device(dest))
240
247
  )
248
+ if same and real != os.path.realpath(dest):
249
+ found[path.name] = real
241
250
  except OSError:
242
251
  continue
243
- if same and real != os.path.realpath(dest):
244
- found[path.name] = real
245
252
  return found
246
253
 
247
254
 
@@ -13,6 +13,7 @@ import socket
13
13
  import ssl
14
14
  import stat
15
15
  import subprocess
16
+ import sys
16
17
  import tarfile
17
18
  import time
18
19
  import urllib.error
@@ -30,7 +31,25 @@ from localmodels import npm_transport, region, remote_ops, remote_ops_download,
30
31
  Event = Callable[[dict[str, Any]], None]
31
32
 
32
33
 
33
- def regular_directories(path: Path) -> None:
34
+ _MACOS_SYSTEM_LINKS = {Path(p): Path("/private" + p) for p in ("/tmp", "/var", "/etc")}
35
+
36
+
37
+ def _macos_system_link(parent: Path, info: os.stat_result) -> bool:
38
+ target = _MACOS_SYSTEM_LINKS.get(parent) if sys.platform == "darwin" else None
39
+ if target is None:
40
+ return False
41
+ try:
42
+ if parent.resolve(strict=True) != target:
43
+ return False
44
+ stats = [p.lstat() for p in (*reversed(target.parents), target)]
45
+ except OSError:
46
+ return False
47
+ return all(not stat.S_ISLNK(s.st_mode) and stat.S_ISDIR(s.st_mode) for s in stats) and all(
48
+ s.st_uid == 0 for s in (info, *stats)
49
+ )
50
+
51
+
52
+ def regular_directories(path: Path, *, allow_terminal_system_link: bool = False) -> None:
34
53
  """Validate existing directory components without creating or repairing them."""
35
54
  for parent in [*reversed(path.parents), path]:
36
55
  try:
@@ -38,6 +57,8 @@ def regular_directories(path: Path) -> None:
38
57
  except FileNotFoundError:
39
58
  continue
40
59
  if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
60
+ if (allow_terminal_system_link or parent != path) and _macos_system_link(parent, info):
61
+ continue
41
62
  raise ValueError("Unsafe runtime root")
42
63
  if not stat.S_ISDIR(info.st_mode):
43
64
  raise ValueError("Runtime parent must be a directory")
@@ -87,7 +108,7 @@ def private_directory(path: Path) -> None:
87
108
 
88
109
  def private_permissions(path: Path, *, created: bool = False) -> None:
89
110
  """Repair only new owned state. Existing broad or foreign permissions fail closed."""
90
- regular_directories(path.parent)
111
+ regular_directories(path.parent, allow_terminal_system_link=True)
91
112
  info = path.lstat()
92
113
  if (
93
114
  stat.S_ISLNK(info.st_mode)
@@ -427,17 +448,8 @@ def download(
427
448
  retry_missing: bool = False,
428
449
  clock: Callable[[], float] = time.monotonic,
429
450
  ) -> None:
430
- """Fetch a pinned artifact into ``destination``, which must not exist. Network failures are
431
- retried with backoff and each retry resumes ``destination.part``; a part left by an earlier
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."""
451
+ """Fetch a pinned artifact into ``destination`` (must not exist), resuming ``.part`` across
452
+ retries and alternate hosts, leaving slow hosts once, and switching region on host failure."""
441
453
  urls = deque(download_urls(artifact["url"]))
442
454
  preferred = remote_ops_download.side(urls[0])
443
455
  failed_preferred = False
@@ -504,10 +516,12 @@ def _download_from(
504
516
  if part.stat().st_size > artifact["maxBytes"]:
505
517
  part.write_bytes(b"")
506
518
  else:
507
- flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
508
- os.close(os.open(part, flags, 0o600))
519
+ os.close(
520
+ os.open(
521
+ part, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600
522
+ )
523
+ )
509
524
  private_permissions(part, created=True)
510
- # Bytes kept by an earlier call: they may be another version's when the pin changed.
511
525
  resumed = part.stat().st_size > 0
512
526
  if resumed and _matches(part, artifact):
513
527
  _publish(part, destination)
@@ -539,7 +553,7 @@ def _download_from(
539
553
  break
540
554
  except _TransferError as exc:
541
555
  kept = part.stat().st_size
542
- if exc.slow: # not retried here: the caller moves to another host
556
+ if exc.slow:
543
557
  raise RuntimeDownloadError(
544
558
  url, exc.reason, kept, retryable=True, slow=True
545
559
  ) from None
@@ -563,7 +577,7 @@ def _download_from(
563
577
  pause(wait)
564
578
  if _matches(part, artifact):
565
579
  break
566
- if resumed: # restart once from zero on this host rather than blame it
580
+ if resumed:
567
581
  part.write_bytes(b"")
568
582
  resumed = False
569
583
  continue