setup, telemetry: two Mac fixes found by the Mac test run (M1, M2)

M1: `setup.py --family deepseek41` (or a DeepSeek model name) on a Mac printed
nothing and stopped with metal/setup_mac.py's own argument error: setup.py
handed a Mac over before its retired-name check. The check now comes first:
the same sentence (retired.NOT_OFFERED) and exit 2 as on Linux and Windows.

M2: a plan on a Mac read the IOKit registry (ioreg) several times (9 for
three card-memory questions in the test, 3 in a real `strata serve --plan`).
serve/telemetry._Metal keeps the registry's static facts once per process and
the registry text for 1 s (one read serves the questions of the same moment;
the server's telemetry polls stay live), and a real Mac reader's card memory
is the Metal working set. test_no_acquisition's rule on a Mac: at most one
read-only GPU probe, no network; its two Mac-only start cases are skipped
(a plain start on a Mac is metal/setup_mac.py by design).

Tests: tests/terminal/test_mac_setup_and_probe.py (runs anywhere): head 4/4;
the code before fails M1 and M2 (9 reads != 1), p2003-20261116-2158-e836.
Mac m1002 under lockrun: the touched files 0 failures
(m1002-20261116-2256-f4e6); Linux p2003 222 + 14 pass.
This commit is contained in:
Niko1221 committed 2026-11-16 23:15:40 +01:00
1 parent a76f2f136a
commit fe5917a283
5 files changed
+115 -10

No files matched your search

+24 -7
View File
@@ -299,27 +299,44 @@ class _Metal:
"die, so there is no PCIe link to show; the engine's own figures are in its log")
cmd = ("ioreg", "-l", "-w0", "-r", "-c", "IOAccelerator")
_first: list = [] # (M2 11-16) the registry as the first reader of this process saw it: the nodes and the name do not change
def __init__(self, index=0, run=None):
self.index = index
self._run = run or self._ioreg
self.nodes = len(self._blocks())
if run is None: # the real registry: read once per process for what does not change (a plan asked it six times)
if not _Metal._first:
_Metal._first.append(self._ioreg())
text = _Metal._first[0]
blocks = self._blocks(text)
else:
blocks = self._blocks()
self.nodes = len(blocks)
self._name = None
b = self._block()
b = blocks[index] if 0 <= index < len(blocks) else None
if b:
m = re.search(r'"model" = "([^"]+)"', b)
self._name = m.group(1) if m else None
_recent: list = [] # (M2) [monotonic time, text]: one registry read serves the questions of the same moment
FRESH_S = 1.0 # the server's telemetry polls every few seconds, so its readings stay live
@staticmethod
def _ioreg():
now = time.monotonic()
if _Metal._recent and now - _Metal._recent[0][0] < _Metal.FRESH_S:
return _Metal._recent[0][1]
try:
return subprocess.run(list(_Metal.cmd), capture_output=True, text=True, timeout=10).stdout or ""
text = subprocess.run(list(_Metal.cmd), capture_output=True, text=True, timeout=10).stdout or ""
except (OSError, subprocess.SubprocessError):
return ""
text = ""
_Metal._recent[:] = [(time.monotonic(), text)]
return text
def _blocks(self):
"""The accelerator nodes, in the registry's order: every node that carries a PerformanceStatistics."""
def _blocks(self, text=None):
"""The accelerator nodes, in the registry's order: every node that carries a PerformanceStatistics. `text`: a registry already read."""
try:
out = self._run() or ""
out = (self._run() if text is None else text) or ""
except OSError: # ioreg missing, or a caller's runner that raises
return []
return [b for b in re.split(r"^\s*\+-o ", out, flags=re.M) if '"PerformanceStatistics"' in b]
+2 -2
View File
@@ -9462,8 +9462,6 @@ def main() -> int:
_pf.adopt_user_defaults()
except Exception:
pass
if sys.platform == "darwin" and not CONTROL: # a Mac: metal/setup_mac.py (the Metal engine); the app (Control mode) goes on below
return mac_setup(sys.argv[1:])
_peek = lambda flag: next((v.split("=", 1)[1] if v.startswith(flag + "=") else sys.argv[i + 2] if i + 2 < len(sys.argv) else None # noqa: E731
for i, v in enumerate(sys.argv[1:]) if v == flag or v.startswith(flag + "=")), None)
from strata_control import retired
@@ -9471,6 +9469,8 @@ def main() -> int:
and (not _peek("--family") or retired.is_name(_peek("--family")))):
say(" " + retired.NOT_OFFERED) # DeepSeek: no longer offered (strata_control/retired.py)
return 2
if sys.platform == "darwin" and not CONTROL: # a Mac: metal/setup_mac.py (the Metal engine); the app (Control mode) goes on below.
return mac_setup(sys.argv[1:]) # (after the retired names above, so a Mac gets the same sentence and exit 2, M1 11-16)
if (_peek("--family") and _peek("--family") not in {**FAMILIES, **OWN_PATH_FAMILIES}) \
or (_peek("--model") and not _peek("--family") and model_alias(_peek("--model")) not in MODELS
and not any(model_alias(_peek("--model")) in f["models"] for f in OWN_PATH_FAMILIES.values())):
+4
View File
@@ -817,6 +817,10 @@ def card_vram_mib(cfg: dict[str, Any], backend: str | None, archs: Any = None) -
reader = gpu_reader((indices or [0])[0], amd=(backend == "hip"))
if not reader.ok():
return None
from serve import telemetry as _tm
if isinstance(reader, _tm._Metal): # (M2) a Mac's total is the Metal working set: no live registry read for it
total = _tm.metal_working_set()
return float(int(total) >> 20) if total else None
total = reader.read().get("mem_total")
return float(int(total) >> 20) if total else None
except Exception: # noqa: BLE001 - an unreadable card means "not known to be resident"
@@ -0,0 +1,80 @@
"""Two Mac fixes found by the Mac test run (11-16):
M1: `setup.py --family deepseek41` (or a DeepSeek model name) on a Mac printed nothing and stopped with metal/setup_mac.py's own argument error; the
retired names are now checked before the Mac hand-over: the same sentence and exit 2 as on Linux and Windows.
M2: a plan on a Mac read the IOKit registry (`ioreg`) six times; the registry's static facts are read once per process and a Mac's card memory
is the Metal working set, so one read is left.
Both run anywhere: the Mac is named with sys.platform and the probes are counted, nothing real is started."""
from __future__ import annotations
import contextlib
import io
import sys
import unittest
from unittest import mock
from serve import telemetry
from strata_control import drafting
class RetiredNamesOnAMac(unittest.TestCase):
def test_the_same_sentence_and_exit_before_the_mac_hand_over(self):
import setup
for argv in (("--family", "deepseek41"), ("--model", "IST-DAS-2.25bpw"), ("--model=ISTA-DAS-Coder",)):
out = io.StringIO()
with mock.patch.object(sys, "argv", ["setup.py", *argv, "--yes"]), mock.patch.object(setup.sys, "platform", "darwin"), \
mock.patch.object(setup, "CONTROL", False), \
mock.patch.object(setup, "mac_setup", side_effect=AssertionError("the Mac setup must not be reached")), \
contextlib.redirect_stdout(out):
code = setup.main()
self.assertEqual(code, 2, argv)
self.assertIn("Strata no longer offers DeepSeek models. Run `strata launch` to choose one of the Qwen models.", out.getvalue())
def test_a_qwen_run_still_goes_to_the_mac_setup(self):
import setup
with mock.patch.object(sys, "argv", ["setup.py", "--yes"]), mock.patch.object(setup.sys, "platform", "darwin"), \
mock.patch.object(setup, "CONTROL", False), mock.patch.object(setup, "mac_setup", return_value=0) as mac:
self.assertEqual(setup.main(), 0)
mac.assert_called_once_with(["--yes"])
REGISTRY = ('+-o AGXAcceleratorG16X <class AGXAcceleratorG16X>\n "model" = "Apple M5 Max"\n'
' "PerformanceStatistics" = {"Device Utilization %"=12,"In use system memory"=123456}\n')
class OneRegistryRead(unittest.TestCase):
def test_a_plan_reads_the_registry_once(self):
calls = []
def run(argv, *a, **kw):
calls.append(list(argv))
return mock.Mock(stdout=REGISTRY, returncode=0)
with mock.patch.object(telemetry.sys, "platform", "darwin"), mock.patch.object(drafting.sys, "platform", "darwin"), \
mock.patch.object(telemetry._Metal, "_first", [], create=True), mock.patch.object(telemetry._Metal, "_recent", [], create=True), mock.patch.object(telemetry.subprocess, "run", side_effect=run), \
mock.patch.object(telemetry, "metal_working_set", return_value=48 << 30):
for _ in range(3): # the plan asks for the card's memory more than once
self.assertEqual(drafting.card_vram_mib({"gpu": 0}, "metal", []), float(48 << 10))
ioreg = [c for c in calls if c and c[0] == "ioreg"]
self.assertEqual(len(ioreg), 1, ioreg)
def test_live_readings_still_read_the_registry_each_time(self):
calls = []
def run(argv, *a, **kw):
calls.append(list(argv))
return mock.Mock(stdout=REGISTRY, returncode=0)
with mock.patch.object(telemetry.sys, "platform", "darwin"), mock.patch.object(telemetry._Metal, "_first", [], create=True), mock.patch.object(telemetry._Metal, "_recent", [], create=True), \
mock.patch.object(telemetry.subprocess, "run", side_effect=run), mock.patch.object(telemetry, "metal_working_set", return_value=1):
clock = [1000.0]
with mock.patch.object(telemetry.time, "monotonic", side_effect=lambda: clock[0]):
g = telemetry.gpu_reader(0)
self.assertEqual((g.ok(), g.name()), (True, "Apple M5 Max"))
before = len(calls)
for _ in range(2): # the server's polls, seconds apart
clock[0] += 2.0
self.assertEqual(g.read()["util"], 12)
self.assertEqual(len(calls) - before, 2, "the server's telemetry keeps reading the load live")
if __name__ == "__main__":
unittest.main()
+5 -1
View File
@@ -216,6 +216,7 @@ class StartNeverAcquiresTests(unittest.TestCase):
code = e
return code, out.getvalue(), started
@unittest.skipIf(sys.platform == "darwin", 'a plain start on a Mac is metal/setup_mac.py by design')
def test_a_start_with_an_old_engine_makes_no_request_and_runs_no_installer(self):
rec = _Recorder()
code, text, started = self.run_setup(rec, "--yes", "--no-browser")
@@ -241,6 +242,7 @@ class StartNeverAcquiresTests(unittest.TestCase):
if p != self.cfg: # a start touches the config (most recently used)
self.assertEqual(p.stat().st_mtime_ns, ns, p)
@unittest.skipIf(sys.platform == "darwin", 'a plain start on a Mac is metal/setup_mac.py by design')
def test_a_card_the_engine_has_no_code_for_is_a_typed_error_naming_the_command(self):
rec = _Recorder()
card = {"index": 0, "name": "RTX 5090", "arch": "120", "vram_gb": 32.0, "driver": "580.0"}
@@ -322,7 +324,9 @@ class CliServeIsOfflineTests(unittest.TestCase):
stem = Path(argv[0]).stem.lower()
return stem in probes or (stem in ("powershell", "pwsh") and any("Get-CimInstance" in a for a in argv))
self.assertEqual(rec.network, [])
self.assertEqual([a for a in rec.programs if not read_only(a)], [])
ioreg = [a for a in rec.programs if Path(a[0]).name == "ioreg"]
self.assertLessEqual(len(ioreg), 1, "a Mac: at most one read-only GPU probe (the IOKit registry) for a plan (M2)")
self.assertEqual([a for a in rec.programs if not read_only(a) and Path(a[0]).name != "ioreg"], [])
self.assertNotIn("setup", sys.modules.get("strata_cli.cli").__dict__.get("__name__", ""))
def test_strata_install_without_the_installer_is_a_typed_error(self):