@simplexai/localmodels-darwin-arm64 0.1.0-dev.39 → 0.1.0-dev.40

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 (49) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +48 -46
  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/chat_template.py +35 -0
  7. package/modules/localmodels/deploy.py +7 -1
  8. package/modules/localmodels/gateway.py +2 -0
  9. package/modules/localmodels/gateway_bifrost.py +3 -0
  10. package/modules/localmodels/gateway_home.py +132 -0
  11. package/modules/localmodels/harness.py +48 -13
  12. package/modules/localmodels/harness_probe.py +5 -1
  13. package/modules/localmodels/library_gateway.py +13 -2
  14. package/modules/localmodels/library_jobs.py +7 -1
  15. package/modules/localmodels/library_serve.py +5 -0
  16. package/modules/localmodels/metal.py +29 -12
  17. package/modules/localmodels/probe.py +4 -0
  18. package/modules/localmodels/remote_ops_download.py +8 -1
  19. package/modules/localmodels/remote_ops_remove.py +15 -0
  20. package/modules/localmodels/remote_ops_service.py +10 -0
  21. package/modules/localmodels/runtime_cli.py +58 -38
  22. package/modules/localmodels/runtime_discovery.py +38 -10
  23. package/modules/localmodels/runtime_install.py +31 -10
  24. package/modules/localmodels/runtime_io.py +4 -3
  25. package/modules/localmodels/runtime_pi.py +61 -18
  26. package/modules/localmodels/runtime_process.py +4 -2
  27. package/modules/localmodels/service_deployment.py +5 -3
  28. package/modules/localmodels/service_probe.py +84 -27
  29. package/modules/localmodels/setup_inspection.py +104 -25
  30. package/modules/localmodels/setup_text.py +12 -5
  31. package/modules/localmodels/slot_cache.py +467 -0
  32. package/modules/localmodels/stack_binding.py +90 -13
  33. package/modules/localmodels/stack_capacity.py +3 -3
  34. package/modules/localmodels/stack_down.py +22 -7
  35. package/modules/localmodels/stack_events.py +59 -0
  36. package/modules/localmodels/stack_hardware.py +13 -24
  37. package/modules/localmodels/stack_lifecycle.py +12 -3
  38. package/modules/localmodels/stack_rollback.py +9 -4
  39. package/modules/localmodels/stack_up.py +27 -20
  40. package/modules/localmodels/stack_update.py +3 -1
  41. package/modules/localmodels/tools.json +1 -0
  42. package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/METADATA +1 -1
  43. package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/RECORD +45 -43
  44. package/package.json +1 -1
  45. package/tool.json +1 -1
  46. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/WHEEL +0 -0
  47. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/entry_points.txt +0 -0
  48. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/NOTICE +0 -0
  49. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,132 @@
1
+ """Recover this tool's private gateway client context, ``gateway-home``, on Windows.
2
+
3
+ An elevated run (Run as administrator, or an elevated shell) creates files owned by
4
+ BUILTIN\\Administrators, not by the user. A ``gateway-home`` made that way fails the private
5
+ check of every later, unelevated run, so every library load failed after its model reached the
6
+ GPU (GitLab #15). Such an owner can only come from an elevated process, so when the tools
7
+ directory around it is this user's private one, the folder is this tool's own: its contents are
8
+ copied into a new private ``gateway-home`` and the old folder is kept beside it, renamed, for
9
+ the user to delete. Any other foreign owner is left alone and reported with a remedy
10
+ (``GatewayHomeError``). The location does not move (a later release decides that).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import time
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from localmodels import harness, harness_probe, runtime_io
23
+
24
+ ADMINISTRATORS_SID = "S-1-5-32-544"
25
+ STAGING = "gateway-home.recovering"
26
+ BACKUP_PREFIX = "gateway-home.elevated-"
27
+ CAUSE = "GATEWAY_HOME_NOT_PRIVATE"
28
+ _REPARSE_POINT = 0x400
29
+
30
+
31
+ class GatewayHomeError(harness.HarnessError):
32
+ """``gateway-home`` is not this user's private folder and this tool cannot prove it its own:
33
+ ``cause`` and ``path`` are the structured fields an installer maps to its own copy."""
34
+
35
+ cause = CAUSE
36
+
37
+ def __init__(self, path: Path, why: str) -> None:
38
+ self.path = path
39
+ super().__init__(
40
+ f"{path} is not a private folder of the current Windows user ({why}); nothing was "
41
+ "changed. Close Linger and stop the localmodels gateway if it is running, then rename "
42
+ "that folder in File Explorer (for example to gateway-home.old; ask an administrator "
43
+ "if Windows denies it) and try again without Run as administrator."
44
+ )
45
+
46
+
47
+ def reclaim(tools_dir: str) -> Path | None:
48
+ """On Windows, replace an Administrators-owned ``gateway-home`` with a private copy; return
49
+ where the old folder was kept, or None when there was nothing to recover. Elsewhere, or when
50
+ the folder is missing or already private, nothing happens."""
51
+ if sys.platform != "win32":
52
+ return None
53
+ home = harness_probe.gateway_home(tools_dir)
54
+ if not os.path.lexists(home):
55
+ return None
56
+ try:
57
+ runtime_io.private_permissions(home)
58
+ return None
59
+ except ValueError as exc:
60
+ problem = str(exc)
61
+ parent = home.parent
62
+ try:
63
+ runtime_io.private_permissions(parent)
64
+ except ValueError as exc:
65
+ raise GatewayHomeError(home, f"{problem}; its parent folder: {exc}") from None
66
+ try:
67
+ owner = owner_sid(home)
68
+ except (OSError, ValueError) as exc:
69
+ raise GatewayHomeError(home, f"{problem}; owner unreadable: {exc}") from None
70
+ if owner != ADMINISTRATORS_SID:
71
+ raise GatewayHomeError(home, f"{problem}; owner {owner}")
72
+ return _replace(home)
73
+
74
+
75
+ def _replace(home: Path) -> Path:
76
+ staging = home.with_name(STAGING)
77
+ backup = home.with_name(BACKUP_PREFIX + time.strftime("%Y%m%dT%H%M%S"))
78
+ try:
79
+ if os.path.lexists(staging):
80
+ runtime_io.private_permissions(staging) # a copy an interrupted recovery left
81
+ shutil.rmtree(staging)
82
+ runtime_io.private_directory(staging)
83
+ _copy(home, staging)
84
+ os.rename(home, backup)
85
+ except (OSError, ValueError) as exc:
86
+ shutil.rmtree(staging, ignore_errors=True)
87
+ raise GatewayHomeError(home, f"owned by Administrators; recovery failed: {exc}") from None
88
+ try:
89
+ os.rename(staging, home)
90
+ except OSError as exc:
91
+ os.rename(backup, home) # put the original back; the copy is discarded
92
+ shutil.rmtree(staging, ignore_errors=True)
93
+ raise GatewayHomeError(home, f"owned by Administrators; recovery failed: {exc}") from None
94
+ return backup
95
+
96
+
97
+ def _copy(source: Path, target: Path) -> None:
98
+ """Regular files and folders only; links and junctions are not followed or copied. New files
99
+ inherit the private folder's access list."""
100
+ for entry in os.scandir(source):
101
+ info = entry.stat(follow_symlinks=False)
102
+ if entry.is_symlink() or getattr(info, "st_file_attributes", 0) & _REPARSE_POINT:
103
+ continue
104
+ destination = target / entry.name
105
+ if entry.is_dir(follow_symlinks=False):
106
+ destination.mkdir()
107
+ _copy(Path(entry.path), destination)
108
+ elif entry.is_file(follow_symlinks=False):
109
+ shutil.copyfile(entry.path, destination)
110
+
111
+
112
+ def owner_sid(path: Path) -> str:
113
+ """The owner of ``path`` as a string SID (Windows only)."""
114
+ import ctypes
115
+
116
+ api, kernel = _api()
117
+ owner, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
118
+ try:
119
+ # SE_FILE_OBJECT (1), OWNER_SECURITY_INFORMATION (1)
120
+ error = api.GetNamedSecurityInfoW(
121
+ str(path), 1, 0x1, ctypes.byref(owner), None, None, None, ctypes.byref(descriptor)
122
+ )
123
+ if error:
124
+ raise OSError(error, "cannot read the folder's owner")
125
+ return runtime_io._windows_sid_text(api, kernel, owner)
126
+ finally:
127
+ if descriptor.value:
128
+ kernel.LocalFree(descriptor)
129
+
130
+
131
+ def _api() -> tuple[Any, Any]:
132
+ return runtime_io._windows_api()
@@ -17,10 +17,11 @@ import shutil
17
17
  import subprocess
18
18
  import tempfile
19
19
  from collections.abc import Callable
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
20
21
  from pathlib import Path
21
22
  from typing import Any, Literal, TypedDict, cast
22
23
 
23
- from localmodels import harness_probe, hosts, region
24
+ from localmodels import harness_probe, hosts, region, runtime_discovery
24
25
  from localmodels.contracts import decode
25
26
  from localmodels.harness_cleanup import (
26
27
  changed as changed,
@@ -51,6 +52,7 @@ from localmodels.npm_transport import install_bifrost
51
52
  from localmodels.remote_ops import Archive, fetch
52
53
  from localmodels.remote_ops_download import npm_copies
53
54
  from localmodels.runtime_io import error_cause
55
+ from localmodels.stack_events import CombinedEvents as _CombinedEvents
54
56
  from localmodels.stack_events import ToolEvents
55
57
  from localmodels.tool_archive import (
56
58
  ArchiveError,
@@ -114,6 +116,7 @@ class PiLock(NpmArtifact):
114
116
 
115
117
  entry: str
116
118
  modules: list[PiModule]
119
+ longest_path: int # characters of the deepest file below the package root
117
120
 
118
121
 
119
122
  class MagpieLock(TypedDict):
@@ -357,8 +360,8 @@ def plan_tools(
357
360
  and not _owned_wrapper(wrapper)
358
361
  ):
359
362
  raise HarnessError(
360
- f"{wrapper} exists but does not run and localmodels did not create it;"
361
- " deal with it first"
363
+ f"{wrapper} exists but does not run or cannot load extensions, and localmodels"
364
+ " did not create it; deal with it first"
362
365
  )
363
366
  if not state["bin_on_path"]:
364
367
  warnings.append(
@@ -515,18 +518,48 @@ def _fetch(tools_dir: Path, artifact: Artifact, log: Callable[[str], None]) -> P
515
518
  staged.replace(path)
516
519
  return path
517
520
  with contextlib.redirect_stdout(_Events(log)):
518
- fetch(
519
- artifact["url"],
520
- str(path),
521
- artifact["sha256"],
522
- artifact["size_bytes"],
523
- artifact["name"],
524
- npm_copies(cast(Archive, artifact)),
525
- region.current_region(),
526
- )
521
+ _download(path, artifact)
527
522
  return path
528
523
 
529
524
 
525
+ def _download(path: Path, artifact: Artifact) -> None:
526
+ fetch(
527
+ artifact["url"],
528
+ str(path),
529
+ artifact["sha256"],
530
+ artifact["size_bytes"],
531
+ artifact["name"],
532
+ npm_copies(cast(Archive, artifact)),
533
+ region.current_region(),
534
+ )
535
+
536
+
537
+ PI_DOWNLOADS = 8 # pi's tree is ~120 small tarballs; one at a time takes minutes
538
+
539
+
540
+ def _fetch_many(
541
+ tools_dir: Path, artifacts: list[Artifact], log: Callable[[str], None]
542
+ ) -> list[Path]:
543
+ """Download ``artifacts`` eight at a time, reported as one download of their total bytes;
544
+ the first failure cancels the ones still queued. A tarball two of them share downloads
545
+ once."""
546
+ unique = {a["name"]: a for a in artifacts}
547
+ events = _CombinedEvents(log, {name: a["size_bytes"] for name, a in unique.items()})
548
+ pool = ThreadPoolExecutor(PI_DOWNLOADS)
549
+ try:
550
+ with contextlib.redirect_stdout(events):
551
+ futures = {
552
+ pool.submit(_download, tools_dir / ".archives" / name, a): name
553
+ for name, a in unique.items()
554
+ }
555
+ for future in as_completed(futures):
556
+ future.result()
557
+ events.finished(futures[future])
558
+ finally:
559
+ pool.shutdown(wait=True, cancel_futures=True)
560
+ return [tools_dir / ".archives" / a["name"] for a in artifacts]
561
+
562
+
530
563
  def _install_tree(tools_dir: Path, name: str, unpack: Callable[[Path], None], marker: str) -> Path:
531
564
  """Unpack into tools_dir/name once; a matching .complete marker means it is already there."""
532
565
  final = tools_dir / name
@@ -559,7 +592,7 @@ def _install_pi(
559
592
  modules = action["artifacts"][1:]
560
593
  if any("path" not in m for m in modules): # plans saved before 2026-11-18
561
594
  raise HarnessError("this plan installs pi without its dependency tree; plan again")
562
- archives = [_fetch(tools_dir, a, log) for a in action["artifacts"]]
595
+ archives = _fetch_many(tools_dir, action["artifacts"], log)
563
596
 
564
597
  def unpack_pi(dest: Path) -> None:
565
598
  _safe_extract(archives[0], dest)
@@ -577,6 +610,8 @@ def _install_pi(
577
610
  about = f"{OWNED_WRAPPER} for {pi['package']}@{pi['version']}; remove this file and {tree}"
578
611
  write_launcher(wrapper, [node, str(tree / pi["entry"])], about)
579
612
  wrapper.chmod(0o755)
613
+ if not runtime_discovery.pi_loads_extensions([str(wrapper)]):
614
+ raise HarnessError(f"pi {pi['version']} at {wrapper} could not load an extension")
580
615
  log(f"pi {pi['version']} installed: {wrapper}")
581
616
  return [str(tree), str(wrapper)]
582
617
 
@@ -13,7 +13,7 @@ import sys
13
13
  from pathlib import Path
14
14
  from typing import TYPE_CHECKING, TypedDict
15
15
 
16
- from localmodels import hosts
16
+ from localmodels import hosts, runtime_discovery
17
17
 
18
18
  if TYPE_CHECKING:
19
19
  from localmodels import harness
@@ -264,6 +264,10 @@ def inspect(
264
264
  pi_version = (
265
265
  first_line(harness.run_tool([pi, "--version"], timeout=30, env=env)) if pi else None
266
266
  )
267
+ if pi and pi_version and not runtime_discovery.pi_loads_extensions([pi], env):
268
+ # localmodels before 0.1.0.dev39 installed pi without jiti, so it cannot load the
269
+ # extension Linger starts it with: plan_tools installs the pinned tree over an owned one.
270
+ pi_version = None
267
271
  magpie_version = pi_model = None
268
272
  gateway_up = False
269
273
  if magpie and not bifrost:
@@ -28,6 +28,7 @@ from localmodels import (
28
28
  bifrost_models,
29
29
  bifrost_unit,
30
30
  gateway_bifrost,
31
+ gateway_home,
31
32
  harness,
32
33
  harness_probe,
33
34
  hosts,
@@ -66,6 +67,16 @@ def pi_profile() -> Path:
66
67
  return Path(harness_probe.client_environment(hosts.tools_dir())["PI_CODING_AGENT_DIR"])
67
68
 
68
69
 
70
+ def _gateway_error(exc: Exception) -> LibraryError:
71
+ """GATEWAY_REGISTRATION_FAILED for ``exc``; a gateway-home this tool could not recover
72
+ (GitLab #15) adds ``cause`` and ``path`` for the installer's own remedy copy."""
73
+ if isinstance(exc, gateway_home.GatewayHomeError):
74
+ return LibraryError(
75
+ "GATEWAY_REGISTRATION_FAILED", str(exc), cause=exc.cause, path=str(exc.path)
76
+ )
77
+ return _fail(str(exc))
78
+
79
+
69
80
  def _fail(detail: str) -> LibraryError:
70
81
  return LibraryError("GATEWAY_REGISTRATION_FAILED", detail)
71
82
 
@@ -423,7 +434,7 @@ def _register(
423
434
  except LibraryError:
424
435
  raise
425
436
  except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
426
- raise _fail(str(exc)) from None
437
+ raise _gateway_error(exc) from None
427
438
  return added
428
439
 
429
440
 
@@ -446,7 +457,7 @@ def _unregister(registration: Registration) -> None:
446
457
  sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
447
458
  apply_config(record, config, sheet)
448
459
  except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
449
- raise _fail(str(exc)) from None
460
+ raise _gateway_error(exc) from None
450
461
 
451
462
 
452
463
  def _stack_owns_pi() -> bool:
@@ -26,6 +26,7 @@ from localmodels import (
26
26
  library_pricing,
27
27
  library_state,
28
28
  library_status,
29
+ metal,
29
30
  plan_envelope,
30
31
  process_identity,
31
32
  remote_ops_download,
@@ -45,7 +46,12 @@ from localmodels.transport import Executor
45
46
 
46
47
 
47
48
  def probe() -> HostFacts:
48
- return app.probe(hosts.LOCAL_ID)
49
+ """This computer's facts, an inference server's file-cached weights on a Mac out of the RAM
50
+ available (metal.foreign_cached_bytes; the library's own servers are not foreign)."""
51
+ facts = app.probe(hosts.LOCAL_ID)
52
+ if foreign := metal.foreign_cached_bytes(facts):
53
+ facts["ram"]["available_bytes"] = max(0, facts["ram"]["available_bytes"] - foreign)
54
+ return facts
49
55
 
50
56
 
51
57
  def executor() -> Executor:
@@ -266,6 +266,11 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
266
266
  releasing the lock, so the next claimant sees it."""
267
267
  freed: dict[str, int] = {}
268
268
  for target in [*targets, *([record] if record["state"] != "idle" else [])]:
269
+ # A server that does not answer (failed, crashed, already stopped) is not counted:
270
+ # ``facts`` already count a gone one's memory as free (on a Mac its weights as file
271
+ # cache), and one still starting is priced as held.
272
+ if not library_status.answering(str(target["plan"]["endpoint"]["base_url"])):
273
+ continue
269
274
  pool = target["pool"]
270
275
  freed[pool] = freed.get(pool, 0) + library_pricing.memory_bytes(target["plan"])
271
276
  _room(facts, model, record, freed)
@@ -20,7 +20,7 @@ from collections.abc import Mapping
20
20
  from typing import TypedDict
21
21
 
22
22
  from localmodels.contracts import decode
23
- from localmodels.probe import GPU, HostFacts
23
+ from localmodels.probe import GPU, ComputeProcess, HostFacts
24
24
 
25
25
  GIB = 1 << 30
26
26
  METAL_UUID = "metal-0" # service_probe.METAL_UUID labels the processes it finds on the GPU
@@ -228,26 +228,43 @@ def conflicts(facts: HostFacts) -> list[str]:
228
228
  return found
229
229
 
230
230
 
231
- def owned_bytes(facts: HostFacts) -> int:
232
- """Resident memory of this tool's own servers on the GPU (service discovery's ``ps``)."""
231
+ def _metal_processes(facts: HostFacts) -> list[ComputeProcess]:
233
232
  services = facts.get("services")
234
233
  processes = (services.get("compute_processes") if services else None) or []
234
+ return [p for p in processes if p["gpu_uuid"] == METAL_UUID]
235
+
236
+
237
+ def owned_bytes(facts: HostFacts) -> int:
238
+ """What stopping this tool's own servers on the GPU gives back (service discovery's
239
+ ``ps``): their resident memory less their file cache, which the RAM available already
240
+ counts (``cached_bytes``)."""
241
+ return sum(
242
+ max(0, int(p.get("used_bytes") or 0) - int(p.get("cached_bytes") or 0))
243
+ for p in _metal_processes(facts)
244
+ if p["owned"] is True
245
+ )
246
+
247
+
248
+ def foreign_cached_bytes(facts: HostFacts) -> int:
249
+ """The file-cached weights of inference servers this tool does not own: an upstream server
250
+ unwires its weights a few minutes into idling, and macOS then counts them as available.
251
+ They are still that server's model (decision 43), so they are not free for a plan."""
235
252
  return sum(
236
- int(p.get("used_bytes") or 0)
237
- for p in processes
238
- if p["gpu_uuid"] == METAL_UUID and p["owned"] is True
253
+ int(p.get("cached_bytes") or 0) for p in _metal_processes(facts) if p["owned"] is not True
239
254
  )
240
255
 
241
256
 
242
257
  def reclaimed(facts: HostFacts) -> HostFacts:
243
- """``facts`` with this tool's own servers' memory back in the RAM available: a re-plan prices
244
- them as a fresh plan would, as the Linux suite slice is reclaimed (budget.host_ram)."""
245
- owned = owned_bytes(facts)
246
- if not owned:
258
+ """``facts`` with this tool's own servers' memory back in the RAM available, as a fresh plan
259
+ would price them (as the Linux suite slice is reclaimed, budget.host_ram), and another
260
+ server's file-cached weights out of it."""
261
+ owned, foreign = owned_bytes(facts), foreign_cached_bytes(facts)
262
+ if not owned and not foreign:
247
263
  return facts
248
264
  seen = copy.deepcopy(facts)
249
- seen["ram"]["available_bytes"] = min(
250
- seen["ram"]["total_bytes"], seen["ram"]["available_bytes"] + owned
265
+ ram = seen["ram"]
266
+ ram["available_bytes"] = max(
267
+ 0, min(ram["total_bytes"], ram["available_bytes"] + owned) - foreign
251
268
  )
252
269
  return seen
253
270
 
@@ -101,6 +101,10 @@ class CgroupMemory(TypedDict):
101
101
 
102
102
  class _ComputeSince20261024(TypedDict, total=False):
103
103
  in_suite: bool # verified current-user deployment in the suite; never just a cgroup label
104
+ # A Mac process's resident file cache: its resident memory less its physical footprint
105
+ # (mapped GGUF weights that are not wired). The RAM available already counts these pages
106
+ # (metal_probe.available_memory), so a stop gives back only the rest. Absent: unknown.
107
+ cached_bytes: int
104
108
 
105
109
 
106
110
  class ComputeProcess(_ComputeSince20261024):
@@ -258,6 +258,9 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
258
258
  return got / max(1e-3, time.monotonic() - start), ranged
259
259
 
260
260
 
261
+ LONE_SMALL_BYTES = 1 << 20
262
+
263
+
261
264
  def rank(
262
265
  sources: list[remote_ops.Source],
263
266
  size: int,
@@ -266,7 +269,11 @@ def rank(
266
269
  ) -> list[_Ranked]:
267
270
  """The sources fastest first, each with whether it serves ranges; ones that failed the probe
268
271
  go last in plan order (and into ``unreachable``), so a passing hiccup still leaves them as
269
- a fallback."""
272
+ a fallback. A lone source of a small file is not probed: there is nothing to rank, the
273
+ probe would download the whole file a second time (most of pi's ~120 module tarballs),
274
+ and one plain stream reads it in about the time a resume would save."""
275
+ if len(sources) == 1 and size <= min(PROBE_BYTES, LONE_SMALL_BYTES):
276
+ return [(sources[0], False)]
270
277
  measured: list[tuple[float, int, _Ranked]] = []
271
278
  failed: list[_Ranked] = []
272
279
  notes = []
@@ -35,6 +35,20 @@ def _purgeable(p: remote_ops.RemoveParams, preparation: list[str]) -> list[list[
35
35
  return [[f, st.st_size, st.st_nlink] for f, st in stats if not os.path.isdir(f)]
36
36
 
37
37
 
38
+ def _delete_prompt_caches(root: str) -> None:
39
+ """The kept prompt starts, which hold prompt text: slot_cache.py's prefix.json,
40
+ prefix-tally.json and saved slots (prefix-<hash>.bin) under ``slots``, and a temporary
41
+ file a stop may have left of them."""
42
+ slots = os.path.join(root, "slots")
43
+ if not os.path.isdir(slots):
44
+ return
45
+ for name in os.listdir(slots):
46
+ if name.startswith("prefix") and name.endswith((".json", ".bin", ".tmp")):
47
+ _delete(os.path.join(slots, name))
48
+ if not os.listdir(slots):
49
+ _delete(slots, os.rmdir)
50
+
51
+
38
52
  def _delete(path: str, remove: Callable[[str], None] = os.remove) -> None:
39
53
  """Delete one of a stopped service's files or emptied directories. Windows refuses while
40
54
  another process still has it open, and a server that was just ended keeps its log and its
@@ -105,6 +119,7 @@ def _remove(p: remote_ops.RemoveParams, preparation: list[str]) -> None:
105
119
  ]:
106
120
  if os.path.exists(remote_ops._expand(path)):
107
121
  _delete(remote_ops._expand(path))
122
+ _delete_prompt_caches(paths["root"])
108
123
  approved = set(p.get("purge") or []) & {str(f[0]) for f in listed}
109
124
  for path in approved:
110
125
  if os.path.lexists(path): # the service files above may be listed too
@@ -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]
@@ -402,15 +402,14 @@ def build_plan(
402
402
  )["runtimes"]
403
403
  if row["runtime"] == runtime
404
404
  )
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
- )
405
+ if os.environ.get(f"SIMPLEX_{runtime.upper()}_PATH") is not None and status["executable"]:
406
+ if not _compatible_version(runtime, status["version"], before_version=before_version):
407
+ raise ValueError(
408
+ "Explicit runtime version is incompatible with the supported baseline or "
409
+ "--before-version bound"
410
+ )
411
+ if not status["installed"]: # the status reads only the explicit path: no install helps
412
+ raise ValueError("The explicit runtime path cannot load extensions")
414
413
  plan = native_plan(
415
414
  runtime,
416
415
  root,
@@ -558,39 +557,19 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
558
557
  ):
559
558
  raise ValueError("Changed bootstrap artifact")
560
559
  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")
560
+ _check_reused(plan)
567
561
  event({"kind": "stage", "stage": "reuse", "state": "succeeded"})
568
- return inspect_runtimes(root, before_versions=before_versions)
562
+ return _installed(root, runtime, before_versions)
569
563
  target = root / "tools" / runtime / plan["version"]
570
- runtime_pi.replace_broken(target, plan, pi_loads_extensions)
564
+ replace = False
571
565
  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")
566
+ if _kept(target, plan, approve):
567
+ return _installed(root, runtime, before_versions)
568
+ replace = True
591
569
  private_directory(target.parent)
592
570
  event({"kind": "stage", "stage": "install", "state": "running"})
593
- with tempfile.TemporaryDirectory(prefix=".runtime-", dir=target.parent) as temporary:
571
+ # Short names: Windows allows 260 characters, and Pi's tree has files 138 below its root
572
+ with tempfile.TemporaryDirectory(prefix=".s", dir=target.parent) as temporary:
594
573
  stage = Path(temporary)
595
574
  private_permissions(stage, created=True)
596
575
  tree = _install_tree(plan, stage, event)
@@ -621,10 +600,51 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
621
600
  marker = tree / "localmodels-runtime.json"
622
601
  marker.write_text(json.dumps({"schema": "localmodels.runtime-owned/v1", "planId": approve}))
623
602
  private_permissions(marker, created=True)
603
+ if replace:
604
+ runtime_pi.retire(target)
624
605
  tree.rename(target)
625
606
  runtime_install.release_downloads(plan)
626
607
  event({"kind": "stage", "stage": "install", "state": "succeeded"})
627
- return inspect_runtimes(root, before_versions=before_versions)
608
+ return _installed(root, runtime, before_versions)
609
+
610
+
611
+ def _check_reused(plan: dict[str, Any]) -> None:
612
+ """The reused runtime still reports its version, and a Pi still loads an extension."""
613
+ if not _compatible_version(plan["runtime"], plan["existingVersion"]):
614
+ raise ValueError("Existing runtime version is incompatible with the supported baseline")
615
+ code, current_version = _probe([*plan["command"], "--version"])
616
+ match = re.search(r"\d+\.\d+\.\d+(?:[\w.+-]*)", current_version)
617
+ if code != 0 or (match.group() if match else None) != plan["existingVersion"]:
618
+ raise ValueError("Existing runtime changed; create a new plan")
619
+ if plan["runtime"] == "pi" and not pi_loads_extensions(plan["command"]):
620
+ raise RuntimeVersionVerificationError(
621
+ "RUNTIME_EXTENSIONS_FAILED", "Pi could not load an extension."
622
+ )
623
+
624
+
625
+ def _kept(target: Path, plan: dict[str, Any], approve: str) -> bool:
626
+ """Whether the owned install at ``target`` is the install; False: an owned Pi to replace
627
+ once the new tree verified (dev38's, without jiti). A working owned Pi is kept, whichever
628
+ plan made it; anything not owned is never overwritten."""
629
+ marker = None if target.is_symlink() else runtime_discovery.owned_marker(target)
630
+ if marker is None:
631
+ raise ValueError("Runtime target exists; refusing to overwrite it")
632
+ if plan["runtime"] == "pi":
633
+ return runtime_pi.healthy(target, plan["version"], _probe, pi_loads_extensions)
634
+ if marker.get("planId") != approve:
635
+ raise ValueError("Runtime target exists; refusing to overwrite it")
636
+ code, version = _probe([str(installed_command(plan)), "--version"])
637
+ if code != 0 or plan["version"] not in version:
638
+ raise ValueError("Owned runtime failed version verification; inspect before retrying")
639
+ return True
640
+
641
+
642
+ def _installed(root: Path, runtime: str, before_versions: dict[str, str] | None) -> dict[str, Any]:
643
+ """The status after apply; never exit 0 while the runtime is not installed (Linger)."""
644
+ status = inspect_runtimes(root, before_versions=before_versions)
645
+ if not next(row for row in status["runtimes"] if row["runtime"] == runtime)["installed"]:
646
+ raise ValueError(f"{runtime} is still not usable after apply")
647
+ return status
628
648
 
629
649
 
630
650
  def _act(args: argparse.Namespace) -> dict[str, Any]: