@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
@@ -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,61 @@ 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"))]):
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
+ def _check_path_budget(root: Path, longest: int) -> None:
73
+ """Refuse at plan time a Windows runtime root too long for Pi's dependency tree, unless
74
+ long paths are enabled; an unpacked file past 260 characters fails mid-install."""
75
+ deepest = len(str(root)) + sum(len(part) + 1 for part in STAGED) + 1 + longest
76
+ if deepest <= WINDOWS_MAX_PATH or _long_paths_enabled():
74
77
  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)
78
+ room = WINDOWS_MAX_PATH - (deepest - len(str(root)))
79
+ raise ValueError(
80
+ f"The runtime root is {len(str(root))} characters; Pi's dependency tree fits below a"
81
+ f" root of at most {room} on Windows unless long paths are enabled"
82
+ )
83
+
84
+
85
+ def _long_paths_enabled() -> bool:
86
+ if sys.platform != "win32":
87
+ return False
88
+ try:
89
+ import winreg
90
+
91
+ with winreg.OpenKey(
92
+ winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem"
93
+ ) as key:
94
+ return bool(winreg.QueryValueEx(key, "LongPathsEnabled")[0] == 1)
95
+ except (ImportError, OSError):
96
+ return False
97
+
98
+
99
+ def executable(tree: Path) -> list[str]:
100
+ return [str(tree / ("pi.exe" if os.name == "nt" else "pi"))]
101
+
102
+
103
+ def healthy(
104
+ tree: Path,
105
+ version: str,
106
+ probe: Callable[[list[str]], tuple[int, str]],
107
+ loads_extensions: Callable[[list[str]], bool],
108
+ ) -> bool:
109
+ """The Pi at ``tree`` reports ``version`` and loads an extension. 0.1.0.dev38 installed
110
+ Pi 1.5.2 there without its dependencies: it passes the first and fails the second."""
111
+ code, output = probe([*executable(tree), "--version"])
112
+ return code == 0 and version in output and loads_extensions(executable(tree))
113
+
114
+
115
+ def retire(target: Path) -> None:
116
+ """Move an owned Pi aside and delete it; a file still in use on Windows only leaves the
117
+ hidden sibling behind, under the runtime root that uninstall removes. The sibling's name
118
+ is barely longer than the version's, so no file below it passes Windows' 260 characters
119
+ where the installed one did not."""
120
+ aside = target.with_name(f".old-{secrets.token_hex(2)}")
121
+ target.rename(aside)
79
122
  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()
@@ -25,6 +25,7 @@ import shlex
25
25
  import shutil
26
26
  import socket
27
27
  import stat
28
+ import struct
28
29
  import subprocess
29
30
  import sys
30
31
  import urllib.error
@@ -303,10 +304,18 @@ def _posix_owned(pid: int, root: str) -> bool | None:
303
304
  return False
304
305
 
305
306
 
306
- def parse_darwin_ps(text: str, me: str, args: Callable[[int], str]) -> list[dict[str, object]]:
307
+ def parse_darwin_ps(
308
+ text: str,
309
+ me: str,
310
+ args: Callable[[int], str],
311
+ parent: Callable[[int], int | None] | None = None,
312
+ footprint: Callable[[int], int | None] = lambda pid: None,
313
+ ) -> list[dict[str, object]]:
307
314
  """Serving engines from ``ps -axo pid=,rss=,user=,comm=`` on macOS. Every process there shares
308
- the one Metal GPU, so each is listed on it with its resident memory. Python servers need
309
- their module/script argument to identify the engine; no arguments or model paths are kept."""
315
+ the one Metal GPU, so each is listed on it with its resident memory, and (when macOS tells
316
+ its physical footprint) the part of it that is file cache. Python servers need their
317
+ module/script argument to identify the engine; no arguments or model paths are kept.
318
+ ``parent`` gives a process's parent, for an engine its deployment's launcher started."""
310
319
  found: list[dict[str, object]] = []
311
320
  for line in text.splitlines():
312
321
  cols = line.split(None, 3)
@@ -316,17 +325,19 @@ def parse_darwin_ps(text: str, me: str, args: Callable[[int], str]) -> list[dict
316
325
  name, argv = _darwin_engine(comm, pid, args)
317
326
  if name is None:
318
327
  continue
319
- owned = user == me and _beside_deployment(argv, pid)
320
- found.append(
321
- {
322
- "gpu_uuid": METAL_UUID,
323
- "pid": pid,
324
- "name": name,
325
- "used_bytes": rss << 10,
326
- "owned": owned,
327
- "in_suite": owned,
328
- }
329
- )
328
+ owned = user == me and _beside_deployment(argv, pid, parent)
329
+ row: dict[str, object] = {
330
+ "gpu_uuid": METAL_UUID,
331
+ "pid": pid,
332
+ "name": name,
333
+ "used_bytes": rss << 10,
334
+ "owned": owned,
335
+ "in_suite": owned,
336
+ }
337
+ physical = footprint(pid)
338
+ if physical is not None:
339
+ row["cached_bytes"] = max(0, (rss << 10) - physical)
340
+ found.append(row)
330
341
  return found
331
342
 
332
343
 
@@ -348,20 +359,62 @@ def _darwin_engine(
348
359
  return (match.group(0).lower() if match else None), argv
349
360
 
350
361
 
351
- def _beside_deployment(argv: Sequence[str], pid: int) -> bool:
362
+ def _receipt_pids(directory: str) -> set[int]:
363
+ """The live processes a deployment directory's own receipts name (nohup, launchd)."""
364
+ held: set[int] = set()
365
+ state, pid = process_identity.status(directory + "/server.pid")
366
+ if state == "active" and pid is not None:
367
+ held.add(pid)
368
+ if os.path.isfile(directory + "/launchd.plist"):
369
+ try:
370
+ state, pid = remote_ops_launchd.status(directory)
371
+ if state == "active" and pid is not None:
372
+ held.add(pid)
373
+ except (OSError, RuntimeError):
374
+ pass
375
+ return held
376
+
377
+
378
+ def _beside_deployment(
379
+ argv: Sequence[str], pid: int, parent: Callable[[int], int | None] | None = None
380
+ ) -> bool:
381
+ """A deployment's receipt names this process, or names its parent: a launcher in front of
382
+ the server (slot_cache.py) is the recorded process and the server is its child, as the
383
+ Linux check follows a process's ancestors to the recorded command (_posix_owned)."""
352
384
  values = (arg.split("=", 1)[-1] for arg in argv[:256])
385
+ held: set[int] = set()
353
386
  for directory in {os.path.dirname(v) for v in values if v[:1] == "/"}:
354
- if not os.path.isfile(directory + "/deployment.json"):
355
- continue
356
- if process_identity.status(directory + "/server.pid") == ("active", pid):
357
- return True
358
- if os.path.isfile(directory + "/launchd.plist"):
359
- try:
360
- if remote_ops_launchd.status(directory) == ("active", pid):
361
- return True
362
- except (OSError, RuntimeError):
363
- pass
364
- return False
387
+ if os.path.isfile(directory + "/deployment.json"):
388
+ held |= _receipt_pids(directory)
389
+ if pid in held:
390
+ return True
391
+ if not held or parent is None:
392
+ return False
393
+ above = parent(pid)
394
+ return above is not None and above > 1 and above in held
395
+
396
+
397
+ LIBPROC = "/usr/lib/libproc.dylib"
398
+ # struct rusage_info_v0: a 16-byte uuid, then ten uint64 counters; ri_wired_size,
399
+ # ri_resident_size and ri_phys_footprint are the 6th, 7th and 8th.
400
+ _RUSAGE_V0_BYTES = 16 + 10 * 8
401
+
402
+
403
+ def darwin_footprint(pid: int) -> int | None:
404
+ """The process's physical footprint (Activity Monitor's "Memory"): its anonymous, wired and
405
+ compressed memory, without the clean file-backed pages it maps; at least its wired memory.
406
+ None when macOS does not tell (another user's process)."""
407
+ try:
408
+ import ctypes
409
+
410
+ libproc = ctypes.cdll.LoadLibrary(LIBPROC)
411
+ buffer = ctypes.create_string_buffer(_RUSAGE_V0_BYTES)
412
+ if libproc.proc_pid_rusage(ctypes.c_int(pid), ctypes.c_int(0), buffer) != 0:
413
+ return None
414
+ except (OSError, AttributeError, ImportError):
415
+ return None
416
+ wired, _resident, physical = struct.unpack_from("<3Q", buffer.raw, 16 + 5 * 8)
417
+ return int(max(wired, physical))
365
418
 
366
419
 
367
420
  def _darwin_processes() -> tuple[list[dict[str, object]] | None, str | None]:
@@ -376,8 +429,12 @@ def _darwin_processes() -> tuple[list[dict[str, object]] | None, str | None]:
376
429
  raise OSError("process arguments unavailable")
377
430
  return text if done == 0 else ""
378
431
 
432
+ def parent(pid: int) -> int | None:
433
+ done, text, _ = _run(["/bin/ps", "-o", "ppid=", "-p", str(pid)])
434
+ return int(text) if done == 0 and text.strip().isdigit() else None
435
+
379
436
  try:
380
- return parse_darwin_ps(out, me, args), None
437
+ return parse_darwin_ps(out, me, args, parent, darwin_footprint), None
381
438
  except OSError:
382
439
  return None, "failed"
383
440