@simplexai/localmodels-linux-x64 0.1.0-dev.39 → 0.1.0-dev.42

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 (72) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +70 -69
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/auth_proxy.py +74 -16
  5. package/modules/localmodels/budget.py +27 -18
  6. package/modules/localmodels/catalog.json +4 -130
  7. package/modules/localmodels/catalog.py +10 -0
  8. package/modules/localmodels/chat_template.py +35 -0
  9. package/modules/localmodels/debug_mode.py +8 -0
  10. package/modules/localmodels/deploy.py +7 -1
  11. package/modules/localmodels/download-mirrors.json +0 -8
  12. package/modules/localmodels/gateway.py +2 -0
  13. package/modules/localmodels/gateway_bifrost.py +3 -0
  14. package/modules/localmodels/gateway_home.py +132 -0
  15. package/modules/localmodels/harness.py +48 -13
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/library_gateway.py +13 -2
  18. package/modules/localmodels/library_jobs.py +63 -6
  19. package/modules/localmodels/library_model.py +60 -15
  20. package/modules/localmodels/library_pricing.py +99 -26
  21. package/modules/localmodels/library_serve.py +69 -14
  22. package/modules/localmodels/library_state.py +33 -2
  23. package/modules/localmodels/library_status.py +109 -13
  24. package/modules/localmodels/llm_rank.py +16 -27
  25. package/modules/localmodels/metal.py +29 -12
  26. package/modules/localmodels/probe.py +4 -0
  27. package/modules/localmodels/recommend.py +30 -13
  28. package/modules/localmodels/recommend_cli.py +6 -4
  29. package/modules/localmodels/remote_ops_download.py +75 -14
  30. package/modules/localmodels/remote_ops_remove.py +15 -0
  31. package/modules/localmodels/remote_ops_service.py +10 -0
  32. package/modules/localmodels/reuse.py +31 -5
  33. package/modules/localmodels/runtime_cli.py +61 -40
  34. package/modules/localmodels/runtime_discovery.py +38 -10
  35. package/modules/localmodels/runtime_install.py +31 -10
  36. package/modules/localmodels/runtime_io.py +4 -3
  37. package/modules/localmodels/runtime_pi.py +71 -19
  38. package/modules/localmodels/runtime_process.py +4 -2
  39. package/modules/localmodels/service_deployment.py +5 -3
  40. package/modules/localmodels/service_probe.py +84 -27
  41. package/modules/localmodels/setup_inspection.py +104 -25
  42. package/modules/localmodels/setup_text.py +12 -5
  43. package/modules/localmodels/sizecalc.py +0 -2
  44. package/modules/localmodels/slot_cache.py +467 -0
  45. package/modules/localmodels/stack_binding.py +90 -13
  46. package/modules/localmodels/stack_capacity.py +3 -3
  47. package/modules/localmodels/stack_card.py +1 -0
  48. package/modules/localmodels/stack_compose.py +2 -3
  49. package/modules/localmodels/stack_down.py +22 -7
  50. package/modules/localmodels/stack_events.py +59 -0
  51. package/modules/localmodels/stack_hardware.py +35 -29
  52. package/modules/localmodels/stack_hardware_text.py +40 -35
  53. package/modules/localmodels/stack_lifecycle.py +12 -3
  54. package/modules/localmodels/stack_mlx.py +4 -1
  55. package/modules/localmodels/stack_picks.py +6 -1
  56. package/modules/localmodels/stack_plan.py +1 -0
  57. package/modules/localmodels/stack_rollback.py +9 -4
  58. package/modules/localmodels/stack_summary.py +2 -0
  59. package/modules/localmodels/stack_up.py +27 -20
  60. package/modules/localmodels/stack_update.py +3 -1
  61. package/modules/localmodels/stack_warm.py +21 -11
  62. package/modules/localmodels/stack_warm_store.py +5 -16
  63. package/modules/localmodels/tools.json +1 -0
  64. package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/METADATA +1 -1
  65. package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/RECORD +67 -66
  66. package/package.json +1 -1
  67. package/tool.json +1 -1
  68. package/modules/localmodels/engines-b12167.json +0 -26
  69. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/WHEEL +0 -0
  70. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/entry_points.txt +0 -0
  71. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/licenses/NOTICE +0 -0
  72. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -652,6 +652,16 @@ def listener_problem(port: int, pids: list[int]) -> str | None:
652
652
  return None
653
653
 
654
654
 
655
+ def group_pids(pid: int) -> list[int]:
656
+ """A service's recorded process and the live members of the process group it leads. A
657
+ launcher in front of the server (slot_cache.py, auth_proxy.py) is the recorded process; the
658
+ server is its child in that group, and on a card it is the child that holds the memory."""
659
+ try:
660
+ return sorted({pid, *_group_members(pid)})
661
+ except (RuntimeError, OSError): # another owner, or no process list: the recorded process
662
+ return [pid]
663
+
664
+
655
665
  def _status_pids(p: remote_ops.ServiceParams, pid: int) -> list[int]:
656
666
  if p["service_kind"] != "systemd-user":
657
667
  return [pid]
@@ -209,11 +209,21 @@ def device(path: str) -> int | None:
209
209
  return None
210
210
 
211
211
 
212
+ def extra_reuse_roots() -> tuple[str, ...]:
213
+ """Extra directories from ``LOCALMODELS_REUSE_DIRS`` (``os.pathsep``-separated)."""
214
+ raw = os.environ.get("LOCALMODELS_REUSE_DIRS", "")
215
+ return tuple(entry.strip() for entry in raw.split(os.pathsep) if entry.strip())
216
+
217
+
212
218
  def find_copies(
213
- wanted: dict[str, tuple[int, str]], roots: tuple[str, ...] = SEARCH_ROOTS
219
+ wanted: dict[str, tuple[int, str]],
220
+ roots: tuple[str, ...] = SEARCH_ROOTS,
221
+ *,
222
+ allow_cross_device: bool = False,
214
223
  ) -> dict[str, str]:
215
224
  """{file name: existing path} for each wanted name (-> (size, destination)) found with the
216
- same size on the destination's filesystem, so a hard link can replace the download."""
225
+ same size on the destination's filesystem (or anywhere under ``roots`` when
226
+ ``allow_cross_device`` is true), so reuse can replace the download."""
217
227
  found: dict[str, str] = {}
218
228
  for root in roots:
219
229
  for path in _walk(Path(os.path.expanduser(root))):
@@ -221,12 +231,28 @@ def find_copies(
221
231
  if spec is None or path.name in found:
222
232
  continue
223
233
  real = os.path.realpath(path)
234
+ dest = os.path.expanduser(spec[1])
224
235
  try:
225
- same = os.path.getsize(real) == spec[0] and os.stat(real).st_dev == device(
226
- os.path.expanduser(spec[1])
236
+ same = (
237
+ os.path.isfile(real)
238
+ and os.path.getsize(real) == spec[0]
239
+ and (allow_cross_device or os.stat(real).st_dev == device(dest))
227
240
  )
228
241
  except OSError:
229
242
  continue
230
- if same and real != os.path.realpath(os.path.expanduser(spec[1])):
243
+ if same and real != os.path.realpath(dest):
231
244
  found[path.name] = real
232
245
  return found
246
+
247
+
248
+ def find_library_copies(wanted: dict[str, tuple[int, str]]) -> dict[str, str]:
249
+ """Existing copies for library downloads: same-device hard-link candidates under
250
+ ``SEARCH_ROOTS`` first, then missing entries from ``LOCALMODELS_REUSE_DIRS`` (allowing
251
+ cross-device copies)."""
252
+ if not wanted:
253
+ return {}
254
+ found = find_copies(wanted, SEARCH_ROOTS, allow_cross_device=False)
255
+ missing = {name: spec for name, spec in wanted.items() if name not in found}
256
+ if missing and (extra := extra_reuse_roots()):
257
+ found.update(find_copies(missing, extra, allow_cross_device=True))
258
+ return found
@@ -71,6 +71,7 @@ class RuntimeVersionVerificationError(ValueError):
71
71
  def __init__(self, code: str, message: str) -> None:
72
72
  super().__init__(message)
73
73
  self.code = code
74
+ self.details: dict[str, int] = {}
74
75
 
75
76
 
76
77
  def _require_installed_version(code: int, output: str, expected: str) -> None:
@@ -402,15 +403,14 @@ def build_plan(
402
403
  )["runtimes"]
403
404
  if row["runtime"] == runtime
404
405
  )
405
- if (
406
- os.environ.get(f"SIMPLEX_{runtime.upper()}_PATH") is not None
407
- and status["executable"]
408
- and not _compatible_version(runtime, status["version"], before_version=before_version)
409
- ):
410
- raise ValueError(
411
- "Explicit runtime version is incompatible with the supported baseline or "
412
- "--before-version bound"
413
- )
406
+ if os.environ.get(f"SIMPLEX_{runtime.upper()}_PATH") is not None and status["executable"]:
407
+ if not _compatible_version(runtime, status["version"], before_version=before_version):
408
+ raise ValueError(
409
+ "Explicit runtime version is incompatible with the supported baseline or "
410
+ "--before-version bound"
411
+ )
412
+ if not status["installed"]: # the status reads only the explicit path: no install helps
413
+ raise ValueError("The explicit runtime path cannot load extensions")
414
414
  plan = native_plan(
415
415
  runtime,
416
416
  root,
@@ -558,39 +558,19 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
558
558
  ):
559
559
  raise ValueError("Changed bootstrap artifact")
560
560
  if plan["action"] == "reuse":
561
- if not _compatible_version(runtime, plan["existingVersion"]):
562
- raise ValueError("Existing runtime version is incompatible with the supported baseline")
563
- code, current_version = _probe([*plan["command"], "--version"])
564
- match = re.search(r"\d+\.\d+\.\d+(?:[\w.+-]*)", current_version)
565
- if code != 0 or (match.group() if match else None) != plan["existingVersion"]:
566
- raise ValueError("Existing runtime changed; create a new plan")
561
+ _check_reused(plan)
567
562
  event({"kind": "stage", "stage": "reuse", "state": "succeeded"})
568
- return inspect_runtimes(root, before_versions=before_versions)
563
+ return _installed(root, runtime, before_versions)
569
564
  target = root / "tools" / runtime / plan["version"]
570
- runtime_pi.replace_broken(target, plan, pi_loads_extensions)
565
+ replace = False
571
566
  if target.exists() or target.is_symlink():
572
- # An owned complete install can be safely retried, but unrelated/broken content is never overwritten.
573
- marker = target / "localmodels-runtime.json"
574
- if (
575
- marker.is_file()
576
- and not marker.is_symlink()
577
- and json.loads(marker.read_text()).get("planId") == approve
578
- ):
579
- command = (
580
- [str(installed_command(plan))]
581
- if runtime != "pi"
582
- else [str(target / ("pi.exe" if os.name == "nt" else "pi"))]
583
- )
584
- code, version = _probe(command + ["--version"])
585
- if code != 0 or plan["version"] not in version:
586
- raise ValueError(
587
- "Owned runtime failed version verification; inspect before retrying"
588
- )
589
- return inspect_runtimes(root, before_versions=before_versions)
590
- raise ValueError("Runtime target exists; refusing to overwrite it")
567
+ if _kept(target, plan, approve):
568
+ return _installed(root, runtime, before_versions)
569
+ replace = True
591
570
  private_directory(target.parent)
592
571
  event({"kind": "stage", "stage": "install", "state": "running"})
593
- with tempfile.TemporaryDirectory(prefix=".runtime-", dir=target.parent) as temporary:
572
+ # Short names: Windows allows 260 characters, and Pi's tree has files 138 below its root
573
+ with tempfile.TemporaryDirectory(prefix=".s", dir=target.parent) as temporary:
594
574
  stage = Path(temporary)
595
575
  private_permissions(stage, created=True)
596
576
  tree = _install_tree(plan, stage, event)
@@ -621,10 +601,51 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
621
601
  marker = tree / "localmodels-runtime.json"
622
602
  marker.write_text(json.dumps({"schema": "localmodels.runtime-owned/v1", "planId": approve}))
623
603
  private_permissions(marker, created=True)
604
+ if replace:
605
+ runtime_pi.retire(target)
624
606
  tree.rename(target)
625
607
  runtime_install.release_downloads(plan)
626
608
  event({"kind": "stage", "stage": "install", "state": "succeeded"})
627
- return inspect_runtimes(root, before_versions=before_versions)
609
+ return _installed(root, runtime, before_versions)
610
+
611
+
612
+ def _check_reused(plan: dict[str, Any]) -> None:
613
+ """The reused runtime still reports its version, and a Pi still loads an extension."""
614
+ if not _compatible_version(plan["runtime"], plan["existingVersion"]):
615
+ raise ValueError("Existing runtime version is incompatible with the supported baseline")
616
+ code, current_version = _probe([*plan["command"], "--version"])
617
+ match = re.search(r"\d+\.\d+\.\d+(?:[\w.+-]*)", current_version)
618
+ if code != 0 or (match.group() if match else None) != plan["existingVersion"]:
619
+ raise ValueError("Existing runtime changed; create a new plan")
620
+ if plan["runtime"] == "pi" and not pi_loads_extensions(plan["command"]):
621
+ raise RuntimeVersionVerificationError(
622
+ "RUNTIME_EXTENSIONS_FAILED", "Pi could not load an extension."
623
+ )
624
+
625
+
626
+ def _kept(target: Path, plan: dict[str, Any], approve: str) -> bool:
627
+ """Whether the owned install at ``target`` is the install; False: an owned Pi to replace
628
+ once the new tree verified (dev38's, without jiti). A working owned Pi is kept, whichever
629
+ plan made it; anything not owned is never overwritten."""
630
+ marker = None if target.is_symlink() else runtime_discovery.owned_marker(target)
631
+ if marker is None:
632
+ raise ValueError("Runtime target exists; refusing to overwrite it")
633
+ if plan["runtime"] == "pi":
634
+ return runtime_pi.healthy(target, plan["version"], _probe, pi_loads_extensions)
635
+ if marker.get("planId") != approve:
636
+ raise ValueError("Runtime target exists; refusing to overwrite it")
637
+ code, version = _probe([str(installed_command(plan)), "--version"])
638
+ if code != 0 or plan["version"] not in version:
639
+ raise ValueError("Owned runtime failed version verification; inspect before retrying")
640
+ return True
641
+
642
+
643
+ def _installed(root: Path, runtime: str, before_versions: dict[str, str] | None) -> dict[str, Any]:
644
+ """The status after apply; never exit 0 while the runtime is not installed (Linger)."""
645
+ status = inspect_runtimes(root, before_versions=before_versions)
646
+ if not next(row for row in status["runtimes"] if row["runtime"] == runtime)["installed"]:
647
+ raise ValueError(f"{runtime} is still not usable after apply")
648
+ return status
628
649
 
629
650
 
630
651
  def _act(args: argparse.Namespace) -> dict[str, Any]:
@@ -691,8 +712,8 @@ def run(args: argparse.Namespace) -> int:
691
712
  try:
692
713
  print(json.dumps(_act(args)))
693
714
  return 0
694
- except RuntimeVersionVerificationError as error:
695
- _report_error(error.code, str(error))
715
+ except (RuntimeVersionVerificationError, runtime_pi.RuntimeRootTooLongError) as error:
716
+ _report_error(error.code, str(error), **error.details)
696
717
  return 1
697
718
  except RuntimeDownloadError as error:
698
719
  _report_error(
@@ -2,12 +2,15 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import json
5
6
  import os
6
7
  import platform
7
8
  import re
8
9
  import shutil
9
10
  import tempfile
11
+ from collections.abc import Mapping
10
12
  from pathlib import Path
13
+ from typing import Any
11
14
 
12
15
  from localmodels import runtime_process
13
16
  from localmodels.runtime_io import private_permissions
@@ -87,28 +90,53 @@ def compatible_version(
87
90
 
88
91
  PI_EXTENSION_MARKER = "localmodels-pi-extension-probe"
89
92
  # TypeScript, so loading it needs the jiti transform Pi loads every extension with (Linger passes
90
- # --extension <computer-tools>/extensions/pi-mcp.mjs on every run).
91
- PI_EXTENSION_PROBE = f"""const marker: string = "{PI_EXTENSION_MARKER}";
92
- export default function (_pi: unknown): void {{
93
+ # --extension <computer-tools>/extensions/pi-mcp.mjs on every run). The marker is joined at run
94
+ # time: a loader error that quotes the source must not print it.
95
+ PI_EXTENSION_PROBE = """const marker: string = ["localmodels-pi", "extension-probe"].join("-");
96
+ export default function (_pi: unknown): void {
93
97
  process.stderr.write(marker + "\\n");
94
- }}
98
+ }
95
99
  """
96
100
 
97
101
 
98
- def pi_loads_extensions(argv: list[str]) -> bool:
102
+ def pi_loads_extensions(argv: list[str], env: Mapping[str, str] | None = None) -> bool:
99
103
  """Whether this Pi can load an extension. A Pi missing its dependencies (localmodels before
100
104
  0.1.0.dev39 installed only the bundled CLI and its image module) prints "Cannot find module
101
105
  'jiti'" and still exits 0, so the probe extension's own output is the evidence. The probe
102
- runs with an empty private profile and without extension discovery: no user extension runs
103
- and no user setting is read or written."""
104
- with tempfile.TemporaryDirectory(prefix="localmodels-pi-probe-") as temporary:
106
+ runs in its own empty directory with an empty private profile and without extension
107
+ discovery: no user extension or project setting runs and no user setting is read or
108
+ written."""
109
+ with tempfile.TemporaryDirectory(
110
+ prefix="localmodels-pi-probe-", ignore_cleanup_errors=True
111
+ ) as temporary:
105
112
  directory = Path(temporary)
106
113
  extension = directory / "probe.ts"
107
114
  extension.write_text(PI_EXTENSION_PROBE, encoding="utf-8")
108
- env = {**os.environ, "PI_CODING_AGENT_DIR": str(directory / "agent")}
115
+ (directory / "agent").mkdir()
116
+ child = {
117
+ **(os.environ if env is None else env),
118
+ "PI_CODING_AGENT_DIR": str(directory / "agent"),
119
+ }
109
120
  code, output = runtime_process.probe(
110
121
  [*argv, "--no-extensions", "--extension", str(extension), "--list-models"],
111
- env,
122
+ child,
112
123
  timeout=30,
124
+ retry_timeout=True,
125
+ cwd=str(directory),
113
126
  )
114
127
  return code == 0 and PI_EXTENSION_MARKER in output
128
+
129
+
130
+ def owned_marker(target: Path) -> dict[str, Any] | None:
131
+ """The ownership record apply wrote into ``target``, or None when there is none or it is
132
+ not one (a hand-made file, or JSON that is not an object)."""
133
+ marker = target / "localmodels-runtime.json"
134
+ if not private_file(marker):
135
+ return None
136
+ try:
137
+ value = json.loads(marker.read_text(encoding="utf-8"))
138
+ except (OSError, ValueError):
139
+ return None
140
+ if not isinstance(value, dict) or value.get("schema") != "localmodels.runtime-owned/v1":
141
+ return None
142
+ return value
@@ -7,7 +7,7 @@ import os
7
7
  import shutil
8
8
  import threading
9
9
  from collections.abc import Callable
10
- from concurrent.futures import ThreadPoolExecutor
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
11
11
  from functools import partial
12
12
  from pathlib import Path
13
13
  from typing import Any
@@ -62,42 +62,63 @@ def fetch_all(
62
62
  def _fetch_modules(
63
63
  cache: Path, artifacts: list[dict[str, Any]], event: Event, download_fn: Callable[..., Any]
64
64
  ) -> dict[str, Path]:
65
+ """Download the modules eight at a time. The byte count never goes back: a module that
66
+ restarts (a retry, the other registry) keeps its highest count, and the rate counts only
67
+ bytes that came over the network, not modules already in the cache. The first failure
68
+ cancels the modules still queued."""
65
69
  if not artifacts:
66
70
  return {}
67
71
  total = sum(int(a["maxBytes"]) for a in artifacts) # the pinned sizes are exact
68
- done: dict[str, int] = {}
72
+ done: dict[str, int] = {} # each module's highest byte count, cached ones included
73
+ fetched: dict[str, int] = {} # each module's highest count reported by a transfer
69
74
  lock = threading.Lock()
70
75
  rate = Rate(0)
76
+ shown = 0
71
77
  private_directory(cache) # once, before the downloads race to create it
72
78
 
73
79
  def fetch(artifact: dict[str, Any]) -> Path:
80
+ digest = artifact["digest"]
81
+
74
82
  def report(update: dict[str, Any]) -> None:
83
+ nonlocal shown
75
84
  with lock:
76
85
  if update.get("kind") != "progress":
77
86
  if update.get("state") != "reused":
78
87
  event(update)
79
88
  return
80
- done[artifact["digest"]] = int(update["completed"])
81
- completed = min(total, sum(done.values()))
89
+ count = int(update["completed"])
90
+ done[digest] = max(done.get(digest, 0), count)
91
+ fetched[digest] = max(fetched.get(digest, 0), count)
92
+ shown = max(shown, min(total, sum(done.values())))
82
93
  event(
83
94
  {
84
95
  "kind": "progress",
85
96
  "stage": "download",
86
- "completed": completed,
97
+ "completed": shown,
87
98
  "total": total,
88
99
  "unit": "bytes",
89
- **rate.fields(completed, total),
100
+ **rate.fields(sum(fetched.values()), None),
101
+ **_eta(rate, total - shown),
90
102
  }
91
103
  )
92
104
 
93
105
  path = cached_download(cache, artifact, report, download_fn)
94
106
  with lock:
95
- done[artifact["digest"]] = int(artifact["maxBytes"])
107
+ done[digest] = int(artifact["maxBytes"])
96
108
  return path
97
109
 
98
- with ThreadPoolExecutor(MODULE_DOWNLOADS) as pool:
110
+ pool = ThreadPoolExecutor(MODULE_DOWNLOADS)
111
+ try:
99
112
  futures = {a["digest"]: pool.submit(fetch, a) for a in artifacts}
100
- return {digest: future.result() for digest, future in futures.items()} # first failure raises
113
+ for future in as_completed(futures.values()):
114
+ future.result() # the first failure raises; the finally clause drops the queue
115
+ finally:
116
+ pool.shutdown(wait=True, cancel_futures=True)
117
+ return {digest: future.result() for digest, future in futures.items()}
118
+
119
+
120
+ def _eta(rate: Rate, left: int) -> dict[str, int]:
121
+ return {"etaSeconds": -(-max(0, left) // rate.rate)} if rate.rate else {}
101
122
 
102
123
 
103
124
  def _wanted(plan: dict[str, Any]) -> list[dict[str, Any] | None]:
@@ -127,7 +148,7 @@ def install_tree(
127
148
  *,
128
149
  download_fn: Callable[..., Any] = download,
129
150
  ) -> Path:
130
- tree = stage / "runtime"
151
+ tree = stage / "t" # short: see apply_plan
131
152
  private_directory(tree)
132
153
  fetched = fetch_all(plan, event, download_fn=download_fn)
133
154
  for index, artifact in enumerate(plan["artifacts"]):
@@ -334,11 +334,12 @@ def _extract_archive(archive: Path, target: Path) -> None:
334
334
  with tarfile.open(archive) as tar:
335
335
  # npm tarballs may repeat a/b as a/./b; the last wins, as with tar (scripts/pin_pi.py
336
336
  # refuses a pinned Pi archive whose repeats differ).
337
- entries = list({_safe_member(e.name): e for e in tar.getmembers()}.values())
338
- for entry in entries:
337
+ entries_all = tar.getmembers()
338
+ for entry in entries_all: # every member, before a repeat could hide a link or device
339
339
  _safe_member(entry.name)
340
340
  if not (entry.isfile() or entry.isdir()):
341
341
  raise ValueError("Unsafe archive member")
342
+ entries = list({_safe_member(e.name): e for e in entries_all}.values())
342
343
  for entry in entries:
343
344
  destination = target / _safe_member(entry.name)
344
345
  if entry.isdir():
@@ -427,7 +428,7 @@ class Rate:
427
428
  def fields(self, completed: int, total: int | None) -> dict[str, int]:
428
429
  now = self.clock()
429
430
  if now - self.mark >= 1.0:
430
- self.rate = int((completed - self.marked) / (now - self.mark))
431
+ self.rate = max(0, int((completed - self.marked) / (now - self.mark)))
431
432
  self.mark, self.marked = now, completed
432
433
  if self.rate is None:
433
434
  return {}
@@ -6,17 +6,17 @@ Pi is one pinned release with its whole production dependency tree (``tools.json
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
- import json
10
9
  import os
10
+ import secrets
11
11
  import shutil
12
- import tempfile
12
+ import sys
13
13
  from collections.abc import Callable
14
14
  from pathlib import Path
15
15
  from typing import Any
16
16
 
17
17
  from localmodels import runtime_process
18
18
  from localmodels.harness import load_lock
19
- from localmodels.runtime_discovery import private_file
19
+ from localmodels.runtime_discovery import owned_marker as owned_marker
20
20
  from localmodels.runtime_install import bootstrap
21
21
  from localmodels.runtime_releases import STABLE, version_key
22
22
 
@@ -53,6 +53,8 @@ def plan_install(
53
53
  plan["launcherArtifact"] = lock["launchers"].get(platform)
54
54
  if not plan["launcherArtifact"]:
55
55
  raise ValueError("Windows Pi launcher artifact is unpublished; supply --launcher")
56
+ if sys.platform == "win32": # the real file system's limit, not the plan's platform tag
57
+ _check_path_budget(Path(plan["root"]), load_lock()["pi"]["longest_path"])
56
58
  minimum = load_lock()["node"]["min_version"] # pi's engines.node, checked by pin_pi.py
57
59
  if not runtime_process.version_ok(node_version, minimum):
58
60
  raise ValueError(f"Pi {plan['version']} needs Node.js {minimum} or newer")
@@ -60,20 +62,70 @@ def plan_install(
60
62
  raise ValueError("Pi has no pinned release older than the --before-version bound")
61
63
 
62
64
 
63
- def replace_broken(
64
- target: Path, plan: dict[str, Any], loads_extensions: Callable[[list[str]], bool]
65
- ) -> None:
66
- """Retire an owned Pi of another plan at ``target`` that cannot load extensions:
67
- 0.1.0.dev38 installed Pi 1.5.2 there without its dependencies. Anything else stays."""
68
- marker = target / "localmodels-runtime.json"
69
- if plan["runtime"] != "pi" or not private_file(marker):
70
- return
71
- if json.loads(marker.read_text()).get("planId") == plan["id"]:
72
- return
73
- if loads_extensions([str(target / ("pi.exe" if os.name == "nt" else "pi"))]):
74
- return
75
- # Move it aside, then delete it; a file still in use on Windows only leaves the hidden copy
76
- # behind, under the runtime root that uninstall removes.
77
- aside = Path(tempfile.mkdtemp(prefix=f".retired-{target.name}-", dir=target.parent))
78
- target.rename(aside / target.name)
65
+ WINDOWS_MAX_PATH = 259 # MAX_PATH less the terminator, without long paths enabled
66
+ # What sits between the runtime root and the package root while apply stages the tree (the
67
+ # deepest it gets: runtime_cli.apply_plan's ".s" temporary directory with its 8 random
68
+ # characters, then runtime_install.install_tree's "t").
69
+ STAGED = ("tools", "pi", ".s" + "x" * 8, "t", "package")
70
+
71
+
72
+ class RuntimeRootTooLongError(ValueError):
73
+ """The pinned Pi tree exceeds the Windows path limit under this root."""
74
+
75
+ code = "RUNTIME_ROOT_TOO_LONG"
76
+
77
+ def __init__(self, length: int, limit: int) -> None:
78
+ super().__init__(
79
+ f"The runtime root is {length} characters; Pi needs at most {limit} on Windows. "
80
+ "Choose a shorter install location or enable long paths."
81
+ )
82
+ self.details = {"rootLength": length, "maxRootLength": limit}
83
+
84
+
85
+ def _check_path_budget(root: Path, longest: int) -> None:
86
+ """Refuse at plan time a Windows runtime root too long for Pi's dependency tree, unless
87
+ long paths are enabled; an unpacked file past 260 characters fails mid-install."""
88
+ limit = WINDOWS_MAX_PATH - sum(len(part) + 1 for part in STAGED) - 1 - longest
89
+ length = len(str(root))
90
+ if length > limit and not _long_paths_enabled():
91
+ raise RuntimeRootTooLongError(length, limit)
92
+
93
+
94
+ def _long_paths_enabled() -> bool:
95
+ if sys.platform != "win32":
96
+ return False
97
+ try:
98
+ import winreg
99
+
100
+ with winreg.OpenKey(
101
+ winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem"
102
+ ) as key:
103
+ return bool(winreg.QueryValueEx(key, "LongPathsEnabled")[0] == 1)
104
+ except (ImportError, OSError):
105
+ return False
106
+
107
+
108
+ def executable(tree: Path) -> list[str]:
109
+ return [str(tree / ("pi.exe" if os.name == "nt" else "pi"))]
110
+
111
+
112
+ def healthy(
113
+ tree: Path,
114
+ version: str,
115
+ probe: Callable[[list[str]], tuple[int, str]],
116
+ loads_extensions: Callable[[list[str]], bool],
117
+ ) -> bool:
118
+ """The Pi at ``tree`` reports ``version`` and loads an extension. 0.1.0.dev38 installed
119
+ Pi 1.5.2 there without its dependencies: it passes the first and fails the second."""
120
+ code, output = probe([*executable(tree), "--version"])
121
+ return code == 0 and version in output and loads_extensions(executable(tree))
122
+
123
+
124
+ def retire(target: Path) -> None:
125
+ """Move an owned Pi aside and delete it; a file still in use on Windows only leaves the
126
+ hidden sibling behind, under the runtime root that uninstall removes. The sibling's name
127
+ is barely longer than the version's, so no file below it passes Windows' 260 characters
128
+ where the installed one did not."""
129
+ aside = target.with_name(f".old-{secrets.token_hex(2)}")
130
+ target.rename(aside)
79
131
  shutil.rmtree(aside, ignore_errors=True)
@@ -119,7 +119,7 @@ def _diagnose(event: str, **fields: object) -> None:
119
119
 
120
120
 
121
121
  def _spawn(
122
- argv: list[str], env: dict[str, str] | None, output: IO[bytes]
122
+ argv: list[str], env: dict[str, str] | None, output: IO[bytes], cwd: str | None = None
123
123
  ) -> subprocess.Popen[bytes]:
124
124
  """Start the probe, retrying transient Windows spawn errors; one stderr line per failure
125
125
  of an absolute executable records which error it was, without the path, environment or
@@ -134,6 +134,7 @@ def _spawn(
134
134
  stdout=output,
135
135
  stderr=subprocess.STDOUT,
136
136
  env=env,
137
+ cwd=cwd,
137
138
  shell=False,
138
139
  start_new_session=os.name != "nt",
139
140
  creationflags=child_flags(),
@@ -179,6 +180,7 @@ def probe(
179
180
  *,
180
181
  timeout: float = 5,
181
182
  retry_timeout: bool = False,
183
+ cwd: str | None = None,
182
184
  ) -> tuple[int, str]:
183
185
  """Capture bounded public-read output; a timeout returns no native text. A child that exits
184
186
  on its own while timeout cleanup runs (taskkill finds no PID) reports its real exit code."""
@@ -186,7 +188,7 @@ def probe(
186
188
  process: subprocess.Popen[bytes] | None = None
187
189
  try:
188
190
  with tempfile.TemporaryFile() as output:
189
- process = _spawn(argv, env, output)
191
+ process = _spawn(argv, env, output, cwd)
190
192
  try:
191
193
  code = process.wait(timeout=timeout)
192
194
  except subprocess.TimeoutExpired:
@@ -55,7 +55,8 @@ def plan_component(
55
55
  if owned := _existing_parts(role, root):
56
56
  return owned
57
57
  if role == "decision":
58
- if budget.unknown_services(facts):
58
+ # With sharing consent the free VRAM decides whoever else uses a card (decision 60).
59
+ if not share_gpu and budget.unknown_services(facts):
59
60
  raise WaitingForResourcesError("gpu")
60
61
  candidates = budget.sharing_cards(facts, 0) if share_gpu else budget.idle_cards(facts, 0)
61
62
  for card in candidates:
@@ -474,7 +475,7 @@ class Deployment:
474
475
 
475
476
  def _check_gpu(self, plan: Plan, facts: HostFacts) -> None:
476
477
  share_gpu = self.sharing_consent()
477
- if type(share_gpu) is not bool or budget.unknown_services(facts):
478
+ if type(share_gpu) is not bool or (not share_gpu and budget.unknown_services(facts)):
478
479
  raise WaitingForResourcesError("gpu")
479
480
  records = hosts.records("local")
480
481
 
@@ -503,8 +504,9 @@ class Deployment:
503
504
  if services is None:
504
505
  raise WaitingForResourcesError("gpu")
505
506
  processes = services["compute_processes"]
506
- if processes is None:
507
+ if processes is None and not share_gpu:
507
508
  raise WaitingForResourcesError("gpu")
509
+ processes = processes or []
508
510
  # Receipt-verified PIDs below are authoritative. The generic /proc
509
511
  # heuristic cannot identify keyless native decision backends.
510
512
  container_facts = facts.copy()