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

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 (67) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +65 -59
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/catalog.json +2395 -9
  5. package/modules/localmodels/deploy.py +29 -134
  6. package/modules/localmodels/download-mirrors.json +47 -0
  7. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  8. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +132 -0
  9. package/modules/localmodels/gateway.py +23 -6
  10. package/modules/localmodels/gateway_bifrost.py +6 -2
  11. package/modules/localmodels/harness.py +8 -2
  12. package/modules/localmodels/harness_gateway.py +78 -17
  13. package/modules/localmodels/harness_probe.py +43 -23
  14. package/modules/localmodels/hosts.py +52 -5
  15. package/modules/localmodels/library_floor.py +76 -0
  16. package/modules/localmodels/library_gateway.py +17 -1
  17. package/modules/localmodels/library_jobs.py +38 -6
  18. package/modules/localmodels/library_model.py +5 -0
  19. package/modules/localmodels/library_poly.py +273 -0
  20. package/modules/localmodels/library_pricing.py +24 -35
  21. package/modules/localmodels/library_serve.py +7 -0
  22. package/modules/localmodels/library_state.py +16 -0
  23. package/modules/localmodels/library_status.py +114 -29
  24. package/modules/localmodels/llm_rank.py +14 -0
  25. package/modules/localmodels/magpie_windows.py +312 -0
  26. package/modules/localmodels/plan_envelope.py +234 -3
  27. package/modules/localmodels/probe.py +1 -1
  28. package/modules/localmodels/process_identity.py +19 -9
  29. package/modules/localmodels/process_identity_darwin.py +155 -0
  30. package/modules/localmodels/remote_ops.py +11 -0
  31. package/modules/localmodels/remote_ops_download.py +30 -5
  32. package/modules/localmodels/remote_ops_service.py +11 -13
  33. package/modules/localmodels/reuse.py +13 -6
  34. package/modules/localmodels/runtime_cli.py +8 -8
  35. package/modules/localmodels/runtime_install.py +25 -1
  36. package/modules/localmodels/runtime_io.py +32 -18
  37. package/modules/localmodels/setup_inspection.py +83 -79
  38. package/modules/localmodels/setup_inspection_harness.py +147 -0
  39. package/modules/localmodels/setup_text.py +12 -0
  40. package/modules/localmodels/setup_upgrade.py +11 -1
  41. package/modules/localmodels/stack.py +3 -1
  42. package/modules/localmodels/stack_auto.py +6 -2
  43. package/modules/localmodels/stack_cli.py +39 -0
  44. package/modules/localmodels/stack_clients.py +1 -1
  45. package/modules/localmodels/stack_compose.py +12 -43
  46. package/modules/localmodels/stack_down.py +25 -16
  47. package/modules/localmodels/stack_hardware.py +12 -1
  48. package/modules/localmodels/stack_picks.py +28 -13
  49. package/modules/localmodels/stack_plan.py +55 -3
  50. package/modules/localmodels/stack_remove.py +3 -1
  51. package/modules/localmodels/stack_suite.py +80 -20
  52. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  53. package/modules/localmodels/{strata-poly-serve-0.1.45-poly.9.txt → strata-poly-serve-0.2.20-poly.1.txt} +2 -2
  54. package/modules/localmodels/strata_poly_server.py +33 -2
  55. package/modules/localmodels/suite.py +45 -4
  56. package/modules/localmodels/tool_archive.py +4 -0
  57. package/modules/localmodels/vision.py +4 -2
  58. package/modules/localmodels/win_probe.py +24 -7
  59. package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/METADATA +1 -1
  60. package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/RECORD +62 -56
  61. package/package.json +1 -1
  62. package/tool.json +1 -1
  63. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +0 -75
  64. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/WHEEL +0 -0
  65. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/entry_points.txt +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/licenses/NOTICE +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -9,8 +9,10 @@ from __future__ import annotations
9
9
 
10
10
  import ctypes
11
11
  import errno
12
+ import ipaddress
12
13
  import os
13
14
  import struct
15
+ import sys
14
16
  from pathlib import Path
15
17
  from typing import Any
16
18
 
@@ -187,3 +189,156 @@ def command_info(pid: int) -> tuple[list[str], Path] | None:
187
189
  return None
188
190
  exec_path, argv = parsed
189
191
  return argv, Path(exec_path)
192
+
193
+
194
+ def parse_host_port(addr: str) -> tuple[str, int]:
195
+ """Split ``host:port`` (including bracketed IPv6 ``[::1]:port``)."""
196
+ host, sep, port_text = addr.strip().rpartition(":")
197
+ if not sep or not port_text.isdecimal():
198
+ raise ValueError(f"invalid address: {addr!r}")
199
+ if host.startswith("[") and host.endswith("]"):
200
+ host = host[1:-1]
201
+ return host, int(port_text)
202
+
203
+
204
+ def _parse_ip(raw: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
205
+ text = raw.strip()
206
+ if text.startswith("[") and text.endswith("]"):
207
+ text = text[1:-1]
208
+ text = text.partition("%")[0]
209
+ try:
210
+ parsed = ipaddress.ip_address(text)
211
+ except ValueError:
212
+ return None
213
+ if isinstance(parsed, ipaddress.IPv6Address):
214
+ return parsed.ipv4_mapped or parsed
215
+ return parsed
216
+
217
+
218
+ def address_conflicts(
219
+ bound: str | ipaddress.IPv4Address | ipaddress.IPv6Address, target: str
220
+ ) -> bool:
221
+ """Whether a listener bound to ``bound`` can receive or block traffic for ``target``.
222
+
223
+ Wildcard/unspecified bindings (``*``, ``0.0.0.0``, ``::``) conflict with every target.
224
+ Unparseable addresses fail closed (return True) so unknown listeners are never ignored.
225
+ """
226
+ target_text = target.strip()
227
+ if target_text in ("", "*", "0.0.0.0", "::", "[::]"):
228
+ return True
229
+ if isinstance(bound, str):
230
+ bound_text = bound.strip()
231
+ if bound_text in ("", "*"):
232
+ return True
233
+ bound_ip = _parse_ip(bound_text)
234
+ if bound_ip is None:
235
+ return True
236
+ elif isinstance(bound, ipaddress.IPv6Address):
237
+ bound_ip = bound.ipv4_mapped or bound
238
+ else:
239
+ bound_ip = bound
240
+ if bound_ip.is_unspecified:
241
+ return True
242
+ if target_text.lower() == "localhost":
243
+ return bound_ip in (ipaddress.IPv4Address("127.0.0.1"), ipaddress.IPv6Address("::1"))
244
+ target_ip = _parse_ip(target_text)
245
+ if target_ip is None or target_ip.is_unspecified:
246
+ return True
247
+ return bound_ip == target_ip
248
+
249
+
250
+ def parse_proc_net_addr(hex_addr: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
251
+ """Decode Linux ``/proc/net/tcp`` or ``/proc/net/tcp6`` local hex address."""
252
+ if len(hex_addr) not in (8, 32):
253
+ return None
254
+ try:
255
+ packed = b"".join(
256
+ int(hex_addr[i : i + 8], 16).to_bytes(4, sys.byteorder)
257
+ for i in range(0, len(hex_addr), 8)
258
+ )
259
+ bound = ipaddress.ip_address(packed)
260
+ except ValueError:
261
+ return None
262
+ if isinstance(bound, ipaddress.IPv6Address):
263
+ return bound.ipv4_mapped or bound
264
+ return bound
265
+
266
+
267
+ def _lsof_name_conflicts(name: str, port: int, target_host: str) -> bool:
268
+ host, sep, port_text = name.rpartition(":")
269
+ if not sep or not port_text.isdecimal():
270
+ return True
271
+ return int(port_text) == port and address_conflicts(host, target_host)
272
+
273
+
274
+ class _LsofCursor:
275
+ """Mutable cursor for parsing one ``lsof -Fpn`` / ``-Fpun`` stream."""
276
+
277
+ def __init__(self, port: int, target_host: str) -> None:
278
+ self.port = port
279
+ self.target_host = target_host
280
+ self.pids: set[int] = set()
281
+ self.uids: set[int] = set()
282
+ self.cur_pid: int | None = None
283
+ self.cur_uid: int | None = None
284
+ self.saw_proc = self.saw_uid = self.saw_name = self.fd_unlabeled = False
285
+
286
+ def _record(self) -> None:
287
+ if self.cur_pid is not None:
288
+ self.pids.add(self.cur_pid)
289
+ if self.cur_uid is not None:
290
+ self.uids.add(self.cur_uid)
291
+
292
+ def flush(self) -> None:
293
+ if self.cur_pid is not None and (not self.saw_name or self.fd_unlabeled):
294
+ self._record()
295
+
296
+ def feed(self, line: str) -> bool:
297
+ if not line:
298
+ return False
299
+ tag, value = line[0], line[1:]
300
+ if tag == "p":
301
+ if not value.isdecimal() or value == "0":
302
+ return False
303
+ self.flush()
304
+ self.cur_pid, self.cur_uid = int(value), None
305
+ self.saw_name = self.fd_unlabeled = False
306
+ self.saw_proc = True
307
+ return True
308
+ if self.cur_pid is None:
309
+ return False
310
+ if tag == "u":
311
+ if not value.isdecimal():
312
+ return False
313
+ self.cur_uid, self.saw_uid = int(value), True
314
+ return True
315
+ if tag == "f":
316
+ if not value.isdecimal():
317
+ return False
318
+ if self.fd_unlabeled:
319
+ self._record()
320
+ self.fd_unlabeled = True
321
+ return True
322
+ if tag == "n" and value:
323
+ self.saw_name, self.fd_unlabeled = True, False
324
+ if _lsof_name_conflicts(value, self.port, self.target_host):
325
+ self._record()
326
+ return True
327
+ return False
328
+
329
+
330
+ def parse_lsof_listeners(
331
+ output: str, port: int, target_host: str = "127.0.0.1"
332
+ ) -> tuple[set[int], set[int], bool, bool] | None:
333
+ """Parse ``lsof -Fpn`` / ``-Fpun`` output into ``(pids, uids, saw_proc, saw_uid)``.
334
+
335
+ Only sockets whose bound address conflicts with ``target_host`` on ``port`` are included;
336
+ records without an ``n`` socket name fail closed and are included. Returns None when any
337
+ line is malformed or attributes a listener to PID 0.
338
+ """
339
+ cursor = _LsofCursor(port, target_host)
340
+ for line in output.splitlines():
341
+ if not cursor.feed(line):
342
+ return None
343
+ cursor.flush()
344
+ return cursor.pids, cursor.uids, cursor.saw_proc, cursor.saw_uid
@@ -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
 
@@ -140,16 +140,16 @@ def _previous_install(
140
140
 
141
141
 
142
142
  def _darwin_listener_pids(port: int) -> set[int] | None:
143
- """Processes listening on TCP ``port`` (lsof; its warnings about unrelated mounts aside)."""
144
- argv = ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"]
143
+ """Processes listening on loopback TCP ``port`` (lsof; its warnings about unrelated mounts aside)."""
144
+ argv = ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"]
145
145
  try:
146
146
  done = subprocess.run(argv, capture_output=True, text=True, timeout=10, check=False)
147
147
  except (OSError, subprocess.SubprocessError):
148
148
  return None
149
- lines = done.stdout.splitlines()
150
- if done.returncode not in (0, 1) or any(not ln[1:].isdecimal() for ln in lines):
149
+ parsed = process_identity_darwin.parse_lsof_listeners(done.stdout, port, "127.0.0.1")
150
+ if done.returncode not in (0, 1) or parsed is None:
151
151
  return None
152
- return {int(ln[1:]) for ln in lines if ln[:1] == "p"}
152
+ return parsed[0]
153
153
 
154
154
 
155
155
  def _process_state(pid: int) -> str | None:
@@ -576,7 +576,7 @@ def _darwin_listener_problem(port: int, pids: list[int]) -> str | None:
576
576
  unknown = "who holds the port is unknown, not probed"
577
577
  try:
578
578
  result = subprocess.run(
579
- ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"],
579
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"],
580
580
  capture_output=True,
581
581
  text=True,
582
582
  timeout=10,
@@ -584,14 +584,12 @@ def _darwin_listener_problem(port: int, pids: list[int]) -> str | None:
584
584
  )
585
585
  except (OSError, subprocess.SubprocessError):
586
586
  return unknown
587
- lines = result.stdout.splitlines()
588
- if result.returncode or result.stderr or not lines:
589
- return unknown
590
- if any(line[:1] not in ("p", "f") or not line[1:].isdecimal() for line in lines):
591
- return unknown # -Fp: a p line per process, an f line per listening descriptor
592
- owners = {int(line[1:]) for line in lines if line[:1] == "p"}
593
- if 0 in owners:
587
+ parsed = process_identity_darwin.parse_lsof_listeners(result.stdout, port, "127.0.0.1")
588
+ if result.returncode or result.stderr or parsed is None or not parsed[2]:
594
589
  return unknown
590
+ owners = parsed[0]
591
+ if not owners:
592
+ return "the port is not listening"
595
593
  return None if owners <= set(pids) else "another process holds the port, not probed"
596
594
 
597
595
 
@@ -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
 
@@ -9,7 +9,6 @@ import os
9
9
  import re
10
10
  import subprocess
11
11
  import sys
12
- import tempfile
13
12
  import time
14
13
  from pathlib import Path
15
14
  from typing import Any
@@ -60,9 +59,11 @@ def _active_profile(runtime: str, env: dict[str, str]) -> Path:
60
59
  return Path(env.get(PROFILE_KEYS[runtime], str(Path.home() / PROFILE_DIRS[runtime])))
61
60
 
62
61
 
63
- def _probe(argv: list[str], env: dict[str, str] | None = None) -> tuple[int, str]:
64
- """Bound execution and output; raw native messages never enter public reports."""
65
- return runtime_process.probe(argv, env, retry_timeout=bool(argv and argv[-1] == "--version"))
62
+ def _probe(
63
+ argv: list[str], env: dict[str, str] | None = None, *, timeout: float = 5
64
+ ) -> tuple[int, str]:
65
+ retry_timeout = argv[-1:] == ["--version"]
66
+ return runtime_process.probe(argv, env, timeout=timeout, retry_timeout=retry_timeout)
66
67
 
67
68
 
68
69
  class RuntimeVersionVerificationError(ValueError):
@@ -566,9 +567,7 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
566
567
  replace = True
567
568
  private_directory(target.parent)
568
569
  event({"kind": "stage", "stage": "install", "state": "running"})
569
- # Short names: Windows allows 260 characters, and Pi's tree has files 138 below its root
570
- with tempfile.TemporaryDirectory(prefix=".s", dir=target.parent) as temporary:
571
- stage = Path(temporary)
570
+ with runtime_install.install_stage(target.parent) as stage:
572
571
  private_permissions(stage, created=True)
573
572
  tree = _install_tree(plan, stage, event)
574
573
  command = (
@@ -577,7 +576,8 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
577
576
  else [str(tree / ("pi.exe" if os.name == "nt" else "pi"))]
578
577
  )
579
578
  event({"kind": "stage", "stage": "verify", "state": "running"})
580
- code, version = _probe(command + ["--version"])
579
+ timeout = 10 if runtime == "pi" and plan["platform"].startswith("win32-") else 5
580
+ code, version = _probe(command + ["--version"], timeout=timeout)
581
581
  try:
582
582
  _require_installed_version(code, version, plan["version"])
583
583
  if runtime == "pi" and not pi_loads_extensions(command):
@@ -5,8 +5,10 @@ from __future__ import annotations
5
5
  import contextlib
6
6
  import os
7
7
  import shutil
8
+ import sys
9
+ import tempfile
8
10
  import threading
9
- from collections.abc import Callable
11
+ from collections.abc import Callable, Iterator
10
12
  from concurrent.futures import ThreadPoolExecutor, as_completed
11
13
  from functools import partial
12
14
  from pathlib import Path
@@ -25,6 +27,28 @@ from localmodels.runtime_io import (
25
27
  )
26
28
 
27
29
 
30
+ @contextlib.contextmanager
31
+ def install_stage(parent: Path) -> Iterator[Path]:
32
+ """Remove the stage while preserving an install failure if its files are still busy."""
33
+ # Keep the stage name short for the Windows Pi dependency tree.
34
+ temporary = tempfile.TemporaryDirectory(prefix=".s", dir=parent)
35
+ try:
36
+ yield Path(temporary.name)
37
+ except BaseException:
38
+ try:
39
+ temporary.cleanup()
40
+ except OSError as error:
41
+ print(
42
+ "localmodels harness: stage cleanup failed"
43
+ f" errno={error.errno} winerror={getattr(error, 'winerror', None)}",
44
+ file=sys.stderr,
45
+ flush=True,
46
+ )
47
+ raise
48
+ else:
49
+ temporary.cleanup()
50
+
51
+
28
52
  def bootstrap(path: Path, destination: str) -> dict[str, str]:
29
53
  if path.is_symlink():
30
54
  raise ValueError("Unsafe bootstrap executable")
@@ -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