@simplexai/localmodels-linux-x64 0.1.0-dev.50 → 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 (33) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +31 -31
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/catalog.json +1988 -16
  5. package/modules/localmodels/deploy.py +29 -134
  6. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +132 -0
  7. package/modules/localmodels/harness_probe.py +38 -22
  8. package/modules/localmodels/library_gateway.py +17 -1
  9. package/modules/localmodels/library_model.py +5 -0
  10. package/modules/localmodels/library_poly.py +1 -0
  11. package/modules/localmodels/library_status.py +96 -31
  12. package/modules/localmodels/plan_envelope.py +234 -3
  13. package/modules/localmodels/process_identity.py +19 -9
  14. package/modules/localmodels/process_identity_darwin.py +155 -0
  15. package/modules/localmodels/remote_ops_service.py +11 -13
  16. package/modules/localmodels/runtime_cli.py +8 -8
  17. package/modules/localmodels/runtime_install.py +25 -1
  18. package/modules/localmodels/stack_cli.py +39 -0
  19. package/modules/localmodels/stack_compose.py +12 -43
  20. package/modules/localmodels/stack_plan.py +55 -3
  21. package/modules/localmodels/stack_suite.py +51 -12
  22. package/modules/localmodels/{strata-poly-serve-0.1.45-poly.9.txt → strata-poly-serve-0.2.20-poly.1.txt} +2 -2
  23. package/modules/localmodels/strata_poly_server.py +19 -0
  24. package/modules/localmodels/suite.py +26 -1
  25. package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/METADATA +1 -1
  26. package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/RECORD +28 -28
  27. package/package.json +1 -1
  28. package/tool.json +1 -1
  29. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +0 -75
  30. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/WHEEL +0 -0
  31. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/entry_points.txt +0 -0
  32. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/licenses/NOTICE +0 -0
  33. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -7,6 +7,7 @@ from __future__ import annotations
7
7
  import datetime as dt
8
8
  import re
9
9
  import urllib.request
10
+ from collections.abc import Mapping
10
11
  from dataclasses import dataclass, field
11
12
  from typing import cast
12
13
 
@@ -33,6 +34,7 @@ from localmodels.library_model import (
33
34
  DebugInfo,
34
35
  Download,
35
36
  DownloadSource,
37
+ Engine,
36
38
  Holder,
37
39
  Host,
38
40
  LibraryError,
@@ -297,6 +299,56 @@ def _loading(job: Job) -> Load:
297
299
  return {"step": step, "done_steps": done_steps, "total_steps": total_steps}
298
300
 
299
301
 
302
+ def _apply_engine_meta(lib: Library, found: Row, model: Model, plan: Plan | None) -> None:
303
+ engine_doc = plan["engine"] if plan is not None else None
304
+ engine = _engine_kind(
305
+ model.entry.runtime, str(engine_doc.get("build") or "") if engine_doc else ""
306
+ )
307
+ found["engine"] = engine
308
+ found["engine_label"] = (
309
+ _format_engine_label(engine_doc)
310
+ if engine_doc is not None
311
+ else _fallback_engine_label(model)
312
+ )
313
+ raw_slots = plan["launch"].get("slots") if plan is not None else None
314
+ parsed_slots = int(str(raw_slots)) if raw_slots is not None else 0
315
+ found["concurrency"] = (
316
+ parsed_slots
317
+ if parsed_slots >= 1
318
+ else (1 if engine in ("polystrata", "strata") else library_pricing.posture().slots)
319
+ )
320
+ if plan is not None and engine in ("polystrata", "strata"):
321
+ host_ram = library_pricing.host_ram_bytes(plan, lib.catalog)
322
+ if host_ram > 0:
323
+ found["host_ram_bytes"] = host_ram
324
+
325
+
326
+ def _apply_record_meta(
327
+ found: Row,
328
+ model: Model,
329
+ record: Record | None,
330
+ state: str,
331
+ problem: Problem | None,
332
+ ) -> None:
333
+ if state != "absent":
334
+ if (selector := pi_model_of(model, record)) is not None:
335
+ found["pi_model"] = selector
336
+ if record is not None:
337
+ if state == "loaded" and (reg := record.get("registration")):
338
+ found["endpoint"] = {
339
+ "base_url": str(record["plan"]["endpoint"]["base_url"]),
340
+ "gateway_model": reg["model"],
341
+ }
342
+ if (speed := record.get("tokens_per_second")) is not None:
343
+ found["tokens_per_second"] = round(speed, 1)
344
+ if (prefill := record.get("prompt_tokens_per_second")) is not None:
345
+ found["prompt_tokens_per_second"] = round(prefill, 1)
346
+ if state == "idle" and (note := record.get("note")):
347
+ found["note"] = note
348
+ if state == "failed" and problem is not None:
349
+ found["error"] = problem
350
+
351
+
300
352
  def row(lib: Library, model: Model) -> Row:
301
353
  record = lib.records.get(model.id)
302
354
  priced = lib.judge(model)
@@ -353,23 +405,8 @@ def row(lib: Library, model: Model) -> Row:
353
405
  elif state == "loading" and job is not None and alive:
354
406
  found["load"] = _loading(job)
355
407
  found.update(card(model, found["vision"]))
356
- if state != "absent":
357
- if (selector := pi_model_of(model, record)) is not None:
358
- found["pi_model"] = selector
359
- if record is not None:
360
- if state == "loaded" and (reg := record.get("registration")):
361
- found["endpoint"] = {
362
- "base_url": str(record["plan"]["endpoint"]["base_url"]),
363
- "gateway_model": reg["model"],
364
- }
365
- if (speed := record.get("tokens_per_second")) is not None:
366
- found["tokens_per_second"] = round(speed, 1)
367
- if (prefill := record.get("prompt_tokens_per_second")) is not None:
368
- found["prompt_tokens_per_second"] = round(prefill, 1)
369
- if state == "idle" and (note := record.get("note")):
370
- found["note"] = note
371
- if state == "failed" and problem is not None:
372
- found["error"] = problem
408
+ _apply_engine_meta(lib, found, model, plan)
409
+ _apply_record_meta(found, model, record, state, problem)
373
410
  return found
374
411
 
375
412
 
@@ -445,6 +482,41 @@ def _pressure_label(level: object) -> MemoryPressure | None:
445
482
  return "critical"
446
483
 
447
484
 
485
+ _BACKEND_LABELS = {"cuda": "CUDA", "metal": "Metal", "cpu": "CPU"}
486
+
487
+
488
+ def _engine_kind(runtime: str, build: str = "") -> Engine:
489
+ if runtime == "strata-poly" or build.startswith("strata-poly"):
490
+ return "polystrata"
491
+ if runtime == "strata" or build.startswith("strata"):
492
+ return "strata"
493
+ return "llama.cpp"
494
+
495
+
496
+ def _format_engine_label(engine: Mapping[str, object]) -> str:
497
+ build = str(engine.get("build") or "")
498
+ if build.startswith("strata-poly-"):
499
+ label = f"PolyStrata {build.removeprefix('strata-poly-')}".strip()
500
+ elif build.startswith("strata-"):
501
+ label = f"Strata {build.removeprefix('strata-')}".strip()
502
+ else:
503
+ label = f"llama.cpp {build}".strip()
504
+ if (kind := engine.get("backend")) in _BACKEND_LABELS:
505
+ label += f" · {_BACKEND_LABELS[str(kind)]}"
506
+ return label
507
+
508
+
509
+ def _fallback_engine_label(model: Model) -> str:
510
+ tag = model.entry.engine or ""
511
+ if model.entry.runtime == "strata-poly":
512
+ version = tag.removeprefix("strata-poly-")
513
+ return f"PolyStrata {version}".strip() if version else "PolyStrata"
514
+ if model.entry.runtime == "strata":
515
+ version = tag.removeprefix("strata-")
516
+ return f"Strata {version}".strip() if version else "Strata"
517
+ return f"llama.cpp {tag}".strip() if tag else "llama.cpp"
518
+
519
+
448
520
  def host(lib: Library) -> Host:
449
521
  facts = lib.facts
450
522
  shown = library_pricing.visible(facts) # the cards the pools may use
@@ -454,20 +526,13 @@ def host(lib: Library) -> Host:
454
526
  or " ".join(str(os_info.get(k) or "") for k in ("system", "release")).strip()
455
527
  )
456
528
  engines = [p.plan["engine"] for p in lib.priced.values() if p.plan is not None]
457
- engine = next(
458
- (e for e in engines if not str(e.get("build") or "").startswith("strata")),
459
- engines[0] if engines else None,
460
- )
461
- backend = {"cuda": "CUDA", "metal": "Metal", "cpu": "CPU"}
462
- engine_label = "llama.cpp"
463
- if engine is not None:
464
- build = str(engine.get("build") or "")
465
- if build.startswith("strata-poly-"):
466
- engine_label = f"PolyStrata {build.removeprefix('strata-poly-')}".strip()
467
- else:
468
- engine_label = f"llama.cpp {build}".strip()
469
- if (kind := engine.get("backend")) in backend:
470
- engine_label += f" · {backend[str(kind)]}"
529
+ by_family: dict[Engine, str] = {}
530
+ for engine in engines:
531
+ family = _engine_kind("", str(engine.get("build") or ""))
532
+ by_family.setdefault(family, _format_engine_label(engine))
533
+ engine_order: tuple[Engine, ...] = ("llama.cpp", "polystrata", "strata")
534
+ ordered = [by_family[f] for f in engine_order if f in by_family]
535
+ engine_label = " + ".join(ordered) if ordered else "llama.cpp"
471
536
  found: Host = {
472
537
  "platform": platform_name(facts),
473
538
  "arch": ARCH.get(str(facts.get("arch")), str(facts.get("arch"))),
@@ -8,17 +8,34 @@ from __future__ import annotations
8
8
  import datetime as dt
9
9
  import functools
10
10
  import hashlib
11
+ import http.client
11
12
  import json
12
13
  import os
13
14
  import re
15
+ import sys
16
+ import time
17
+ import urllib.error
14
18
  import urllib.parse
15
- from collections.abc import Mapping
19
+ import urllib.request
20
+ from collections.abc import Callable, Mapping, Sequence
16
21
  from dataclasses import dataclass
17
22
  from pathlib import Path
23
+ from typing import TypedDict
18
24
 
25
+ from localmodels import catalog as cat
26
+ from localmodels import region
19
27
  from localmodels.budget import gib
28
+ from localmodels.contracts import decode
20
29
  from localmodels.probe import HostFacts
21
- from localmodels.records import Launch, ModelSpec, Plan, ReleaseEngine, ReusableFile, ServicePlan
30
+ from localmodels.records import (
31
+ Launch,
32
+ ModelSpec,
33
+ PinnedFile,
34
+ Plan,
35
+ ReleaseEngine,
36
+ ReusableFile,
37
+ ServicePlan,
38
+ )
22
39
  from localmodels.remote_ops import Source
23
40
 
24
41
  PLAN_SCHEMA = "localmodels.deployment-plan/v1"
@@ -27,6 +44,219 @@ PLAN_SCHEMA = "localmodels.deployment-plan/v1"
27
44
  class PlanError(ValueError):
28
45
  """The deployment cannot be planned as requested; the message says why."""
29
46
 
47
+ def __init__(self, message: str, *, cause_code: str | None = None) -> None:
48
+ super().__init__(message)
49
+ self.cause_code = cause_code
50
+
51
+
52
+ _COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")
53
+ _HF_GET_ATTEMPTS = 3
54
+ _HF_RETRY_DELAYS_S = (0.25, 0.75)
55
+
56
+
57
+ class HubUnreachableError(PlanError):
58
+ """The Hub API could not be reached over the network."""
59
+
60
+ def __init__(self, failures: Sequence[tuple[str, str]]) -> None:
61
+ self.failures = tuple(failures)
62
+ if len(self.failures) == 1:
63
+ host, reason = self.failures[0]
64
+ where = f"{host} to look up the model files ({reason})"
65
+ else:
66
+ where = (
67
+ " or ".join(f"{host} ({reason})" for host, reason in self.failures)
68
+ + " to look up the model files"
69
+ )
70
+ super().__init__(
71
+ f"cannot reach {where}; "
72
+ "name a reachable Hub with --hf-endpoint URL or HF_ENDPOINT (a mirror such as "
73
+ "https://hf-mirror.com), or plan from the catalog's pins with --offline",
74
+ cause_code="HUB_UNREACHABLE",
75
+ )
76
+
77
+
78
+ def _is_timeout(exc: BaseException) -> bool:
79
+ return isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError)
80
+
81
+
82
+ def hf_get(url: str) -> object:
83
+ """One Hub API document. Transient non-timeout disconnects retry briefly; timeouts fail over
84
+ immediately so a blackholed host does not stall."""
85
+ req = urllib.request.Request(url, headers={"User-Agent": "localmodels-plan"})
86
+ for attempt in range(_HF_GET_ATTEMPTS):
87
+ try:
88
+ with urllib.request.urlopen(req, timeout=20) as r:
89
+ return json.load(r)
90
+ except urllib.error.HTTPError:
91
+ raise # the Hub answered: a missing repo or revision is the caller's to report
92
+ except (OSError, http.client.HTTPException) as exc:
93
+ if _is_timeout(exc) or attempt + 1 >= _HF_GET_ATTEMPTS:
94
+ host = urllib.parse.urlsplit(url).netloc
95
+ raise HubUnreachableError([(host, str(getattr(exc, "reason", exc)))]) from exc
96
+ time.sleep(_HF_RETRY_DELAYS_S[attempt])
97
+ raise AssertionError("unreachable Hub retry loop")
98
+
99
+
100
+ def hub_get(
101
+ api: str,
102
+ path: str,
103
+ *,
104
+ mint: bool = False,
105
+ fetch: Callable[[str], object] = hf_get,
106
+ ) -> object:
107
+ """One Hub API document across region-ordered endpoints, preserving every failed host's reason."""
108
+ endpoints = [api.rstrip("/")] if mint else region.hub_endpoints(api)
109
+ failures: list[tuple[str, str]] = []
110
+ for index, endpoint in enumerate(endpoints):
111
+ try:
112
+ doc = fetch(endpoint + path)
113
+ except PlanError as exc:
114
+ if isinstance(exc, HubUnreachableError):
115
+ failures.extend(exc.failures)
116
+ else:
117
+ failures.append((urllib.parse.urlsplit(endpoint).netloc, str(exc)))
118
+ if index + 1 < len(endpoints):
119
+ continue
120
+ if mint and not region.explicit_hub(api):
121
+ what = path.split("/api/models/")[-1]
122
+ raise PlanError(
123
+ region.MINT_REFUSAL.format(what=what),
124
+ cause_code="HUB_UNREACHABLE",
125
+ ) from exc
126
+ if len(failures) > 1:
127
+ raise HubUnreachableError(failures) from exc
128
+ raise
129
+ if index:
130
+ region.fallback_to(region.side_of_endpoint(endpoint))
131
+ return doc
132
+ raise AssertionError("unreachable Hub loop")
133
+
134
+
135
+ class _Revision(TypedDict):
136
+ sha: str
137
+
138
+
139
+ class _LfsFile(TypedDict):
140
+ size: int
141
+ oid: str
142
+
143
+
144
+ class _TreeEntry(TypedDict):
145
+ path: str
146
+
147
+
148
+ class _OptionalTreeEntry(_TreeEntry, total=False):
149
+ lfs: _LfsFile
150
+
151
+
152
+ def _can_use_catalog_pin(asset: cat.AssetFile, api: str) -> bool:
153
+ return (
154
+ asset.sha256 is not None
155
+ and bool(_COMMIT_SHA.fullmatch(asset.revision))
156
+ and not region.explicit_hub(api)
157
+ )
158
+
159
+
160
+ def _pinned_from_catalog(repo: str, asset: cat.AssetFile) -> PinnedFile:
161
+ assert asset.sha256 is not None
162
+ return {
163
+ "repo": repo,
164
+ "path": asset.path,
165
+ "revision": asset.revision,
166
+ "size_bytes": asset.size_bytes,
167
+ "sha256": asset.sha256,
168
+ "local_name": asset.local_name,
169
+ }
170
+
171
+
172
+ def resolve_files(
173
+ assets: list[tuple[str, cat.AssetFile]],
174
+ api: str,
175
+ *,
176
+ fetch_hub: Callable[..., object] = hub_get,
177
+ ) -> list[PinnedFile]:
178
+ """Pin each asset via the Hub API, falling back to exact catalog pins when the default Hub is
179
+ unreachable over the network."""
180
+ revisions: dict[tuple[str, str, bool], str] = {}
181
+ trees: dict[tuple[str, str, str, bool], dict[str, _OptionalTreeEntry]] = {}
182
+ pinned: list[PinnedFile] = []
183
+ hub_offline = False
184
+ noticed_repos: set[str] = set()
185
+ for repo, asset in assets:
186
+ mint = asset.sha256 is None
187
+ fallback_ok = _can_use_catalog_pin(asset, api)
188
+ if hub_offline and fallback_ok:
189
+ pinned.append(_pinned_from_catalog(repo, asset))
190
+ continue
191
+ key = (repo, asset.revision, mint)
192
+ try:
193
+ if key not in revisions:
194
+ doc = decode(
195
+ fetch_hub(
196
+ api,
197
+ f"/api/models/{repo}/revision/{urllib.parse.quote(asset.revision)}",
198
+ mint=mint,
199
+ ),
200
+ _Revision,
201
+ )
202
+ revisions[key] = doc["sha"]
203
+ commit = revisions[key]
204
+ directory = asset.path.rsplit("/", 1)[0] if "/" in asset.path else ""
205
+ tkey = (repo, commit, directory, mint)
206
+ if tkey not in trees:
207
+ path = f"/api/models/{repo}/tree/{commit}" + (
208
+ f"/{urllib.parse.quote(directory)}" if directory else ""
209
+ )
210
+ entries = fetch_hub(api, path, mint=mint)
211
+ if not isinstance(entries, list):
212
+ raise PlanError("Hub tree must be an array")
213
+ parsed = [decode(e, _OptionalTreeEntry) for e in entries]
214
+ trees[tkey] = {e["path"]: e for e in parsed}
215
+ except HubUnreachableError:
216
+ if not fallback_ok:
217
+ raise
218
+ hub_offline = True
219
+ if repo not in noticed_repos:
220
+ noticed_repos.add(repo)
221
+ print(
222
+ f"localmodels: Hub unreachable; using catalog pins for {repo}",
223
+ file=sys.stderr,
224
+ )
225
+ pinned.append(_pinned_from_catalog(repo, asset))
226
+ continue
227
+ entry = trees[tkey].get(asset.path)
228
+ if entry is None or not entry.get("lfs"):
229
+ raise PlanError(f"{asset.path} not found in {repo}@{commit[:12]}")
230
+ if int(entry["lfs"]["size"]) != asset.size_bytes:
231
+ raise PlanError(
232
+ f"{asset.path} size {entry['lfs']['size']} != catalog size {asset.size_bytes}"
233
+ )
234
+ if asset.sha256 is not None and entry["lfs"]["oid"] != asset.sha256:
235
+ raise PlanError(f"{asset.path} on the Hub has a SHA256 the catalog does not pin")
236
+ pinned.append(
237
+ {
238
+ "repo": repo,
239
+ "path": asset.path,
240
+ "revision": commit,
241
+ "size_bytes": asset.size_bytes,
242
+ "sha256": entry["lfs"]["oid"],
243
+ "local_name": asset.local_name,
244
+ }
245
+ )
246
+ return pinned
247
+
248
+
249
+ def catalog_pins(assets: list[tuple[str, cat.AssetFile]], _api: str) -> list[PinnedFile]:
250
+ """Each asset at the commit and SHA256 the catalog pins, asking the Hub nothing."""
251
+ pinned: list[PinnedFile] = []
252
+ for repo, asset in assets:
253
+ if asset.sha256 is None:
254
+ raise PlanError(
255
+ f"catalog pins no commit and SHA256 for {repo}/{asset.path}; cannot plan it offline"
256
+ )
257
+ pinned.append(_pinned_from_catalog(repo, asset))
258
+ return pinned
259
+
30
260
 
31
261
  def deployment_name(model_id: str, port: int) -> str:
32
262
  return re.sub(r"[^a-z0-9.-]+", "-", f"{model_id}-{port}".lower())
@@ -154,7 +384,8 @@ def require_disk(facts: HostFacts, files: list[ReusableFile], *, local: bool = F
154
384
  if free is not None and total > free:
155
385
  raise PlanError(
156
386
  f"not enough disk space: needs {gib(total)}, {facts['disk']['path']} has only "
157
- f"{gib(free)} free"
387
+ f"{gib(free)} free",
388
+ cause_code="DISK_INSUFFICIENT",
158
389
  )
159
390
 
160
391
 
@@ -264,13 +264,17 @@ def image_path(pid: int) -> str | None:
264
264
  return found[1] or None if found else None
265
265
 
266
266
 
267
- def listener_pids(port: int) -> set[int] | None:
268
- """Windows: PIDs listening on TCP ``port`` (IPv4/IPv6 iphlpapi tables), or None on failure."""
267
+ def listener_pids(port: int, *, host: str = "127.0.0.1") -> set[int] | None:
268
+ """Windows: PIDs listening on TCP ``port`` conflicting with ``host``, or None on failure."""
269
+ import ipaddress
269
270
  import struct
270
271
 
271
272
  iphlpapi = ctypes.WinDLL("iphlpapi") # type: ignore[attr-defined]
272
273
  owners: set[int] = set()
273
- for family, row_size, port_at, pid_at in ((2, 24, 8, 20), (23, 56, 20, 52)):
274
+ for family, row_size, addr_at, addr_len, port_at, pid_at in (
275
+ (2, 24, 4, 4, 8, 20),
276
+ (23, 56, 0, 16, 20, 52),
277
+ ):
274
278
  size = ctypes.c_ulong(0)
275
279
  # TCP_TABLE_OWNER_PID_LISTENER = 3; first call sizes the buffer.
276
280
  iphlpapi.GetExtendedTcpTable(None, ctypes.byref(size), False, family, 3, 0)
@@ -286,7 +290,15 @@ def listener_pids(port: int) -> set[int] | None:
286
290
  for index in range(count):
287
291
  row = 4 + index * row_size
288
292
  local_port = struct.unpack_from(">H", raw, row + port_at)[0]
289
- if local_port == port:
293
+ if local_port != port:
294
+ continue
295
+ addr_bytes = raw[row + addr_at : row + addr_at + addr_len]
296
+ bound = (
297
+ ipaddress.IPv4Address(addr_bytes)
298
+ if addr_len == 4
299
+ else ipaddress.IPv6Address(addr_bytes)
300
+ )
301
+ if process_identity_darwin.address_conflicts(bound, host):
290
302
  owners.add(struct.unpack_from("<I", raw, row + pid_at)[0])
291
303
  return owners
292
304
 
@@ -681,7 +693,7 @@ def listener_owned(port: int, pid: int | None) -> bool:
681
693
  return False
682
694
  try:
683
695
  res = subprocess.run(
684
- ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"],
696
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"],
685
697
  capture_output=True,
686
698
  text=True,
687
699
  timeout=5,
@@ -689,10 +701,8 @@ def listener_owned(port: int, pid: int | None) -> bool:
689
701
  )
690
702
  except (OSError, subprocess.TimeoutExpired):
691
703
  return False
692
- owners = {
693
- int(ln[1:]) for ln in res.stdout.splitlines() if ln.startswith("p") and ln[1:].isdigit()
694
- }
695
- return res.returncode == 0 and owners == {pid}
704
+ parsed = process_identity_darwin.parse_lsof_listeners(res.stdout, port, "127.0.0.1")
705
+ return res.returncode == 0 and parsed is not None and parsed[0] == {pid}
696
706
 
697
707
 
698
708
  def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
@@ -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