@simplexai/localmodels-win32-x64 0.1.0-dev.58 → 0.1.0-dev.60
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +105 -98
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +104 -43
- package/modules/localmodels/app.py +1 -1
- package/modules/localmodels/apple_sensors.py +431 -0
- package/modules/localmodels/bifrost_admin.py +83 -8
- package/modules/localmodels/bifrost_checks.py +2 -2
- package/modules/localmodels/bifrost_config.py +235 -13
- package/modules/localmodels/bifrost_log.py +166 -0
- package/modules/localmodels/bifrost_models.py +1 -1
- package/modules/localmodels/budget.py +1 -1
- package/modules/localmodels/catalog.json +192 -77
- package/modules/localmodels/catalog.py +20 -3
- package/modules/localmodels/catalog_add.py +42 -11
- package/modules/localmodels/custom_hub.py +983 -0
- package/modules/localmodels/custom_hub_http.py +579 -0
- package/modules/localmodels/custom_probe.py +451 -0
- package/modules/localmodels/deploy.py +27 -5
- package/modules/localmodels/deploy_steps.py +5 -0
- package/modules/localmodels/download-mirrors.json +8 -0
- package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
- package/modules/localmodels/engines.py +38 -8
- package/modules/localmodels/estimator.py +60 -7
- package/modules/localmodels/frontend.py +26 -21
- package/modules/localmodels/gateway.py +48 -3
- package/modules/localmodels/gateway_app_bifrost.py +4 -4
- package/modules/localmodels/gateway_bifrost.py +128 -21
- package/modules/localmodels/gguf.py +6 -0
- package/modules/localmodels/host_sensors.py +704 -0
- package/modules/localmodels/hosts.py +99 -12
- package/modules/localmodels/library_cli.py +181 -3
- package/modules/localmodels/library_convert.py +34 -0
- package/modules/localmodels/library_custom.py +831 -0
- package/modules/localmodels/library_elastic.py +182 -127
- package/modules/localmodels/library_gateway.py +193 -40
- package/modules/localmodels/library_jobs.py +92 -18
- package/modules/localmodels/library_kept.py +50 -6
- package/modules/localmodels/library_model.py +254 -2
- package/modules/localmodels/library_pricing.py +97 -8
- package/modules/localmodels/library_serve.py +196 -66
- package/modules/localmodels/library_smoke.py +315 -0
- package/modules/localmodels/library_state.py +81 -2
- package/modules/localmodels/library_status.py +144 -8
- package/modules/localmodels/metal.py +1 -1
- package/modules/localmodels/metal_probe.py +4 -4
- package/modules/localmodels/nvml_ctypes.py +431 -0
- package/modules/localmodels/plan_envelope.py +18 -7
- package/modules/localmodels/process_identity_linux.py +39 -0
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/remote_ops.py +57 -8
- package/modules/localmodels/remote_ops_download.py +205 -53
- package/modules/localmodels/remote_ops_mirrors.py +43 -2
- package/modules/localmodels/remote_ops_ranges.py +2 -5
- package/modules/localmodels/remote_ops_service.py +95 -37
- package/modules/localmodels/remote_ops_verify.py +22 -5
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_auth.py +4 -1
- package/modules/localmodels/service_control.py +32 -1
- package/modules/localmodels/service_wiring.py +237 -12
- package/modules/localmodels/service_worker.py +6 -2
- package/modules/localmodels/services_cli.py +35 -27
- package/modules/localmodels/setup_inspection.py +47 -70
- package/modules/localmodels/setup_inspection_harness.py +159 -15
- package/modules/localmodels/setup_text.py +14 -0
- package/modules/localmodels/setup_upgrade.py +1 -1
- package/modules/localmodels/source_byok.py +9 -7
- package/modules/localmodels/source_byok_probe.py +6 -1
- package/modules/localmodels/stack.py +9 -1
- package/modules/localmodels/stack_binding.py +3 -35
- package/modules/localmodels/stack_cleanup.py +4 -0
- package/modules/localmodels/stack_compose.py +18 -2
- package/modules/localmodels/stack_lifecycle.py +26 -3
- package/modules/localmodels/stack_memory.py +1 -0
- package/modules/localmodels/stack_plan.py +6 -2
- package/modules/localmodels/stack_ports.py +2 -0
- package/modules/localmodels/stack_remove.py +10 -1
- package/modules/localmodels/stack_up.py +33 -7
- package/modules/localmodels/stack_update.py +3 -1
- package/modules/localmodels/stack_view.py +77 -53
- package/modules/localmodels/stack_view_demo.py +36 -5
- package/modules/localmodels/stack_view_events.py +147 -12
- package/modules/localmodels/stack_view_gpu.py +97 -17
- package/modules/localmodels/stack_view_llm.py +15 -0
- package/modules/localmodels/stack_view_measure.py +4 -1
- package/modules/localmodels/stack_view_schema.py +54 -8
- package/modules/localmodels/stack_view_serve.py +40 -3
- package/modules/localmodels/stack_view_slots.py +89 -10
- package/modules/localmodels/stack_view_telemetry.py +163 -0
- package/modules/localmodels/stack_view_text.py +5 -2
- package/modules/localmodels/stack_view_tick.py +658 -0
- package/modules/localmodels/stack_view_words.py +4 -0
- package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
- package/modules/localmodels/suite.py +45 -27
- package/modules/localmodels/telemetry_math.py +538 -0
- package/modules/localmodels/transport.py +13 -2
- package/modules/localmodels/web/view/view.js +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/RECORD +102 -95
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/bifrost_datasheet.py +0 -53
- package/modules/localmodels/bifrost_provider.py +0 -88
- package/modules/localmodels/bifrost_unit.py +0 -99
- package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
- package/modules/localmodels/gateway_switch.py +0 -51
- package/modules/localmodels/library_floor.py +0 -78
- package/modules/localmodels/service_stop.py +0 -52
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
"""Cross-platform non-sudo host sensors: CPU overall/per-core %, disk read I/O, memory pressure,
|
|
2
|
+
and watchdog exit health.
|
|
3
|
+
|
|
4
|
+
Platform branches:
|
|
5
|
+
- Linux: ``/proc/stat``, ``/proc/diskstats``, ``/proc/meminfo``, ``/proc/pressure/memory``
|
|
6
|
+
- macOS: ``host_processor_info`` (ctypes), ``IOBlockStorageDriver`` (ioreg), ``apple_sensors``
|
|
7
|
+
- Windows: ``GetSystemTimes`` (ctypes) and ``GlobalMemoryStatusEx`` (per-core CPU and disk I/O
|
|
8
|
+
currently degrade to ``basis: "none"``)
|
|
9
|
+
|
|
10
|
+
Unavailable sensors always return ``value: None, basis: "none"`` and never fabricate numbers.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import ctypes
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import sys
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, TypedDict
|
|
24
|
+
|
|
25
|
+
_PROC = Path("/proc")
|
|
26
|
+
_SECTOR_BYTES = 512
|
|
27
|
+
_BYTES_PER_MB = 1_000_000.0
|
|
28
|
+
# Whole physical block devices on Linux (excludes partitions and loop/ram/dm to avoid double counts).
|
|
29
|
+
_WHOLE_DISK_RE = re.compile(r"^(?:nvme\d+n\d+|sd[a-z]+|vd[a-z]+|hd[a-z]+|xvd[a-z]+|mmcblk\d+)$")
|
|
30
|
+
_OOM_MARKERS = ("out of memory", "oom-kill", "oom_kill", "cudamalloc failed", "bad_alloc")
|
|
31
|
+
_OOM_WORD_RE = re.compile(r"\boom\b")
|
|
32
|
+
_STARVED_MARKERS = ("memory_starved", "memory pressure", "low memory", "jetsam", "mem_pressure")
|
|
33
|
+
|
|
34
|
+
# Module-level previous sample cache for instantaneous deltas across in-process ticks.
|
|
35
|
+
_PREV_SAMPLE_LOCK = threading.Lock()
|
|
36
|
+
_PREV_SAMPLE: dict[str, Any] = {}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SensorFigure(TypedDict):
|
|
40
|
+
value: float | None
|
|
41
|
+
basis: str # live | measured | estimate | demo | none
|
|
42
|
+
note: str
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CoreUsage(TypedDict):
|
|
46
|
+
core: int
|
|
47
|
+
util_pct: float
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class CpuSensors(TypedDict):
|
|
51
|
+
overall_pct: SensorFigure
|
|
52
|
+
per_core: list[CoreUsage]
|
|
53
|
+
logical_cores: int | None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class DiskSensors(TypedDict):
|
|
57
|
+
read_mb_s: SensorFigure
|
|
58
|
+
write_mb_s: SensorFigure
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class MemoryPressure(TypedDict):
|
|
62
|
+
level: str # nominal | elevated | critical | unknown
|
|
63
|
+
basis: str # live | measured | demo | none
|
|
64
|
+
available_ratio: float | None
|
|
65
|
+
psi_some_avg10: float | None
|
|
66
|
+
swap_used_bytes: int | None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class WatchdogHealth(TypedDict):
|
|
70
|
+
status: str # clean | oom | memory_starved | crashed | unknown
|
|
71
|
+
basis: str # live | measured | demo | none
|
|
72
|
+
detail: str
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class HostSensors(TypedDict):
|
|
76
|
+
cpu: CpuSensors
|
|
77
|
+
disk: DiskSensors
|
|
78
|
+
memory_pressure: MemoryPressure
|
|
79
|
+
watchdog: WatchdogHealth
|
|
80
|
+
collector: str
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _fig(value: float | None, basis: str, note: str, digits: int = 1) -> SensorFigure:
|
|
84
|
+
if value is None:
|
|
85
|
+
return {"value": None, "basis": "none", "note": note}
|
|
86
|
+
return {"value": round(value, digits), "basis": basis, "note": note}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# --------------------------------------------------------------------------- Linux pure parsers
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def parse_proc_stat(text: str) -> dict[str, tuple[int, int]]:
|
|
93
|
+
"""Parse ``/proc/stat`` into ``{cpu_name: (total_ticks, active_ticks)}``."""
|
|
94
|
+
samples: dict[str, tuple[int, int]] = {}
|
|
95
|
+
for line in text.splitlines():
|
|
96
|
+
if not line.startswith("cpu"):
|
|
97
|
+
continue
|
|
98
|
+
parts = line.split()
|
|
99
|
+
name = parts[0]
|
|
100
|
+
if name != "cpu" and not name[3:].isdigit():
|
|
101
|
+
continue
|
|
102
|
+
try:
|
|
103
|
+
fields = [int(tok) for tok in parts[1:]]
|
|
104
|
+
except ValueError:
|
|
105
|
+
continue
|
|
106
|
+
if len(fields) < 4:
|
|
107
|
+
continue
|
|
108
|
+
idle = fields[3] + (fields[4] if len(fields) > 4 else 0)
|
|
109
|
+
total = sum(fields)
|
|
110
|
+
samples[name] = (total, max(0, total - idle))
|
|
111
|
+
return samples
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def diff_cpu_samples(
|
|
115
|
+
prev: Mapping[str, tuple[int, int]], curr: Mapping[str, tuple[int, int]]
|
|
116
|
+
) -> tuple[float | None, list[CoreUsage]]:
|
|
117
|
+
"""Compute overall and per-core CPU utilization % from two tick snapshots."""
|
|
118
|
+
overall: float | None = None
|
|
119
|
+
if "cpu" in prev and "cpu" in curr:
|
|
120
|
+
dt_total = curr["cpu"][0] - prev["cpu"][0]
|
|
121
|
+
dt_active = curr["cpu"][1] - prev["cpu"][1]
|
|
122
|
+
if dt_total > 0:
|
|
123
|
+
overall = min(100.0, max(0.0, (dt_active / dt_total) * 100.0))
|
|
124
|
+
cores: list[CoreUsage] = []
|
|
125
|
+
for key in sorted(
|
|
126
|
+
(k for k in curr if k.startswith("cpu") and k[3:].isdigit()),
|
|
127
|
+
key=lambda k: int(k[3:]),
|
|
128
|
+
):
|
|
129
|
+
if key not in prev:
|
|
130
|
+
continue
|
|
131
|
+
dt_total = curr[key][0] - prev[key][0]
|
|
132
|
+
dt_active = curr[key][1] - prev[key][1]
|
|
133
|
+
if dt_total > 0:
|
|
134
|
+
pct = round(min(100.0, max(0.0, (dt_active / dt_total) * 100.0)), 1)
|
|
135
|
+
cores.append({"core": int(key[3:]), "util_pct": pct})
|
|
136
|
+
return overall, cores
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def parse_proc_diskstats(text: str) -> tuple[int, int]:
|
|
140
|
+
"""Sum ``(read_bytes, write_bytes)`` across physical block devices in ``/proc/diskstats``."""
|
|
141
|
+
read_sectors = 0
|
|
142
|
+
write_sectors = 0
|
|
143
|
+
for line in text.splitlines():
|
|
144
|
+
parts = line.split()
|
|
145
|
+
if len(parts) < 10:
|
|
146
|
+
continue
|
|
147
|
+
name = parts[2]
|
|
148
|
+
if not _WHOLE_DISK_RE.match(name):
|
|
149
|
+
continue
|
|
150
|
+
try:
|
|
151
|
+
read_sectors += int(parts[5])
|
|
152
|
+
write_sectors += int(parts[9])
|
|
153
|
+
except ValueError:
|
|
154
|
+
continue
|
|
155
|
+
return read_sectors * _SECTOR_BYTES, write_sectors * _SECTOR_BYTES
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def diff_disk_bytes(
|
|
159
|
+
prev: tuple[int, int], curr: tuple[int, int], elapsed_s: float
|
|
160
|
+
) -> tuple[float | None, float | None]:
|
|
161
|
+
"""Convert two cumulative ``(read_bytes, write_bytes)`` counters over ``elapsed_s`` to MB/s."""
|
|
162
|
+
if elapsed_s <= 0:
|
|
163
|
+
return None, None
|
|
164
|
+
dr = curr[0] - prev[0]
|
|
165
|
+
dw = curr[1] - prev[1]
|
|
166
|
+
read_mb_s = max(0.0, dr / elapsed_s / _BYTES_PER_MB) if dr >= 0 else None
|
|
167
|
+
write_mb_s = max(0.0, dw / elapsed_s / _BYTES_PER_MB) if dw >= 0 else None
|
|
168
|
+
return read_mb_s, write_mb_s
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def parse_proc_meminfo(text: str) -> dict[str, int]:
|
|
172
|
+
"""Parse ``/proc/meminfo`` KiB fields into bytes."""
|
|
173
|
+
found: dict[str, int] = {}
|
|
174
|
+
for line in text.splitlines():
|
|
175
|
+
key, _, rest = line.partition(":")
|
|
176
|
+
tokens = rest.split()
|
|
177
|
+
if not tokens or not tokens[0].isdigit():
|
|
178
|
+
continue
|
|
179
|
+
if key in ("MemTotal", "MemAvailable", "SwapTotal", "SwapFree"):
|
|
180
|
+
found[key] = int(tokens[0]) << 10
|
|
181
|
+
return found
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def parse_psi_some_avg10(text: str) -> float | None:
|
|
185
|
+
"""Parse ``some avg10=<float>`` from ``/proc/pressure/memory``."""
|
|
186
|
+
match = re.search(r"^some\b.*\bavg10=([\d.]+)", text, re.MULTILINE)
|
|
187
|
+
if not match:
|
|
188
|
+
return None
|
|
189
|
+
try:
|
|
190
|
+
return float(match.group(1))
|
|
191
|
+
except ValueError:
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def classify_memory_pressure(
|
|
196
|
+
*,
|
|
197
|
+
available_ratio: float | None,
|
|
198
|
+
psi_some_avg10: float | None = None,
|
|
199
|
+
swap_used_bytes: int | None = None,
|
|
200
|
+
basis: str = "live",
|
|
201
|
+
) -> MemoryPressure:
|
|
202
|
+
"""Derive canonical memory pressure level from available ratio and optional PSI."""
|
|
203
|
+
if available_ratio is None and psi_some_avg10 is None:
|
|
204
|
+
return {
|
|
205
|
+
"level": "unknown",
|
|
206
|
+
"basis": "none",
|
|
207
|
+
"available_ratio": None,
|
|
208
|
+
"psi_some_avg10": None,
|
|
209
|
+
"swap_used_bytes": swap_used_bytes,
|
|
210
|
+
}
|
|
211
|
+
if (psi_some_avg10 is not None and psi_some_avg10 >= 25.0) or (
|
|
212
|
+
available_ratio is not None and available_ratio <= 0.10
|
|
213
|
+
):
|
|
214
|
+
level = "critical"
|
|
215
|
+
elif (psi_some_avg10 is not None and psi_some_avg10 >= 5.0) or (
|
|
216
|
+
available_ratio is not None and available_ratio <= 0.22
|
|
217
|
+
):
|
|
218
|
+
level = "elevated"
|
|
219
|
+
else:
|
|
220
|
+
level = "nominal"
|
|
221
|
+
return {
|
|
222
|
+
"level": level,
|
|
223
|
+
"basis": basis,
|
|
224
|
+
"available_ratio": round(available_ratio, 3) if available_ratio is not None else None,
|
|
225
|
+
"psi_some_avg10": round(psi_some_avg10, 2) if psi_some_avg10 is not None else None,
|
|
226
|
+
"swap_used_bytes": swap_used_bytes,
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
# --------------------------------------------------------------------------- macOS pure parsers
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def parse_macos_disk_stats(text: str) -> tuple[int, int] | None:
|
|
234
|
+
"""Sum ``("Bytes (Read)", "Bytes (Write)")`` from ``ioreg -r -c IOBlockStorageDriver``."""
|
|
235
|
+
reads = [int(m) for m in re.findall(r'"Bytes \(Read\)"\s*=\s*(\d+)', text)]
|
|
236
|
+
writes = [int(m) for m in re.findall(r'"Bytes \(Write\)"\s*=\s*(\d+)', text)]
|
|
237
|
+
if not reads and not writes:
|
|
238
|
+
return None
|
|
239
|
+
return sum(reads), sum(writes)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _read_macos_cpu_ticks() -> dict[str, tuple[int, int]] | None:
|
|
243
|
+
"""Read per-core CPU ticks via macOS ``host_processor_info(PROCESSOR_CPU_LOAD_INFO)``."""
|
|
244
|
+
if sys.platform != "darwin":
|
|
245
|
+
return None
|
|
246
|
+
from localmodels import apple_sensors
|
|
247
|
+
|
|
248
|
+
try:
|
|
249
|
+
libc = ctypes.cdll.LoadLibrary("/usr/lib/libSystem.B.dylib")
|
|
250
|
+
libc.mach_host_self.argtypes = []
|
|
251
|
+
libc.mach_host_self.restype = ctypes.c_uint
|
|
252
|
+
libc.host_processor_info.argtypes = [
|
|
253
|
+
ctypes.c_uint,
|
|
254
|
+
ctypes.c_int,
|
|
255
|
+
ctypes.POINTER(ctypes.c_uint),
|
|
256
|
+
ctypes.POINTER(ctypes.POINTER(ctypes.c_uint32)),
|
|
257
|
+
ctypes.POINTER(ctypes.c_uint),
|
|
258
|
+
]
|
|
259
|
+
libc.host_processor_info.restype = ctypes.c_int
|
|
260
|
+
libc.vm_deallocate.argtypes = [ctypes.c_uint, ctypes.c_void_p, ctypes.c_size_t]
|
|
261
|
+
libc.vm_deallocate.restype = ctypes.c_int
|
|
262
|
+
|
|
263
|
+
host = int(libc.mach_host_self())
|
|
264
|
+
num_cpu = ctypes.c_uint(0)
|
|
265
|
+
info_ptr = ctypes.POINTER(ctypes.c_uint32)()
|
|
266
|
+
info_cnt = ctypes.c_uint(0)
|
|
267
|
+
# PROCESSOR_CPU_LOAD_INFO = 2; 4 natural_t states per core: user, system, idle, nice
|
|
268
|
+
rc = int(
|
|
269
|
+
libc.host_processor_info(
|
|
270
|
+
host,
|
|
271
|
+
2,
|
|
272
|
+
ctypes.byref(num_cpu),
|
|
273
|
+
ctypes.byref(info_ptr),
|
|
274
|
+
ctypes.byref(info_cnt),
|
|
275
|
+
)
|
|
276
|
+
)
|
|
277
|
+
if rc != 0:
|
|
278
|
+
return None
|
|
279
|
+
try:
|
|
280
|
+
n_cpus = int(num_cpu.value)
|
|
281
|
+
if not bool(info_ptr) or n_cpus <= 0 or int(info_cnt.value) < n_cpus * 4:
|
|
282
|
+
return None
|
|
283
|
+
samples: dict[str, tuple[int, int]] = {}
|
|
284
|
+
tot_all = 0
|
|
285
|
+
act_all = 0
|
|
286
|
+
for idx in range(n_cpus):
|
|
287
|
+
base = idx * 4
|
|
288
|
+
user = int(info_ptr[base])
|
|
289
|
+
system = int(info_ptr[base + 1])
|
|
290
|
+
idle = int(info_ptr[base + 2])
|
|
291
|
+
nice = int(info_ptr[base + 3])
|
|
292
|
+
total = user + system + idle + nice
|
|
293
|
+
active = user + system + nice
|
|
294
|
+
samples[f"cpu{idx}"] = (total, active)
|
|
295
|
+
tot_all += total
|
|
296
|
+
act_all += active
|
|
297
|
+
samples["cpu"] = (tot_all, act_all)
|
|
298
|
+
return samples
|
|
299
|
+
finally:
|
|
300
|
+
if bool(info_ptr):
|
|
301
|
+
libc.vm_deallocate(
|
|
302
|
+
apple_sensors.mach_task_self(libc),
|
|
303
|
+
ctypes.cast(info_ptr, ctypes.c_void_p),
|
|
304
|
+
int(info_cnt.value) * ctypes.sizeof(ctypes.c_uint32),
|
|
305
|
+
)
|
|
306
|
+
except (OSError, AttributeError, ValueError):
|
|
307
|
+
return None
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _read_macos_disk_bytes() -> tuple[int, int] | None:
|
|
311
|
+
if sys.platform != "darwin":
|
|
312
|
+
return None
|
|
313
|
+
import subprocess
|
|
314
|
+
|
|
315
|
+
try:
|
|
316
|
+
proc = subprocess.run(
|
|
317
|
+
["/usr/sbin/ioreg", "-r", "-c", "IOBlockStorageDriver", "-k", "Statistics"],
|
|
318
|
+
capture_output=True,
|
|
319
|
+
text=True,
|
|
320
|
+
timeout=1.5,
|
|
321
|
+
check=False,
|
|
322
|
+
)
|
|
323
|
+
return parse_macos_disk_stats(proc.stdout) if proc.returncode == 0 else None
|
|
324
|
+
except (OSError, subprocess.SubprocessError):
|
|
325
|
+
return None
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
# --------------------------------------------------------------------------- Windows collectors
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class _WinFileTime(ctypes.Structure):
|
|
332
|
+
_fields_ = [("dwLowDateTime", ctypes.c_uint32), ("dwHighDateTime", ctypes.c_uint32)]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _ft_int(ft: _WinFileTime) -> int:
|
|
336
|
+
return (int(ft.dwHighDateTime) << 32) | int(ft.dwLowDateTime)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def parse_windows_system_times(
|
|
340
|
+
prev: tuple[int, int, int], curr: tuple[int, int, int]
|
|
341
|
+
) -> float | None:
|
|
342
|
+
"""Compute overall Windows CPU % from two ``(idle, kernel, user)`` FILETIME tuples."""
|
|
343
|
+
d_idle = curr[0] - prev[0]
|
|
344
|
+
d_kernel = curr[1] - prev[1]
|
|
345
|
+
d_user = curr[2] - prev[2]
|
|
346
|
+
total = d_kernel + d_user
|
|
347
|
+
if total <= 0:
|
|
348
|
+
return None
|
|
349
|
+
active = max(0, total - d_idle)
|
|
350
|
+
return round(min(100.0, (active / total) * 100.0), 1)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _read_windows_system_times() -> tuple[int, int, int] | None:
|
|
354
|
+
if sys.platform != "win32":
|
|
355
|
+
return None
|
|
356
|
+
try:
|
|
357
|
+
win_dll: Any = getattr(ctypes, "WinDLL", None)
|
|
358
|
+
if win_dll is None:
|
|
359
|
+
return None
|
|
360
|
+
k32: Any = win_dll("kernel32", use_last_error=True)
|
|
361
|
+
idle, kernel, user = _WinFileTime(), _WinFileTime(), _WinFileTime()
|
|
362
|
+
if not k32.GetSystemTimes(ctypes.byref(idle), ctypes.byref(kernel), ctypes.byref(user)):
|
|
363
|
+
return None
|
|
364
|
+
return _ft_int(idle), _ft_int(kernel), _ft_int(user)
|
|
365
|
+
except (OSError, AttributeError, ValueError):
|
|
366
|
+
return None
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _read_windows_memory_pressure() -> MemoryPressure:
|
|
370
|
+
if sys.platform != "win32":
|
|
371
|
+
return classify_memory_pressure(available_ratio=None)
|
|
372
|
+
try:
|
|
373
|
+
win_dll: Any = getattr(ctypes, "WinDLL", None)
|
|
374
|
+
if win_dll is None:
|
|
375
|
+
return classify_memory_pressure(available_ratio=None)
|
|
376
|
+
mem = (ctypes.c_uint64 * 8)(64)
|
|
377
|
+
k32: Any = win_dll("kernel32", use_last_error=True)
|
|
378
|
+
if not k32.GlobalMemoryStatusEx(ctypes.byref(mem)):
|
|
379
|
+
return classify_memory_pressure(available_ratio=None)
|
|
380
|
+
total, avail = int(mem[1]), int(mem[2])
|
|
381
|
+
ratio = (avail / total) if total > 0 else None
|
|
382
|
+
return classify_memory_pressure(available_ratio=ratio, basis="live")
|
|
383
|
+
except (OSError, AttributeError, ValueError):
|
|
384
|
+
return classify_memory_pressure(available_ratio=None)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
# --------------------------------------------------------------------------- Watchdog classifier
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def classify_watchdog_exit(
|
|
391
|
+
*,
|
|
392
|
+
states: Mapping[str, tuple[str, str]] | None = None,
|
|
393
|
+
exit_code: int | None = None,
|
|
394
|
+
signal_num: int | None = None,
|
|
395
|
+
oom_killed: bool = False,
|
|
396
|
+
log_summary: str = "",
|
|
397
|
+
) -> WatchdogHealth:
|
|
398
|
+
"""Classify the last abnormal exit or current service watchdog state cleanly."""
|
|
399
|
+
lower = log_summary.lower()
|
|
400
|
+
if oom_killed or any(m in lower for m in _OOM_MARKERS) or _OOM_WORD_RE.search(lower):
|
|
401
|
+
return {
|
|
402
|
+
"status": "oom",
|
|
403
|
+
"basis": "live",
|
|
404
|
+
"detail": "Service terminated due to out-of-memory condition",
|
|
405
|
+
}
|
|
406
|
+
if any(m in lower for m in _STARVED_MARKERS):
|
|
407
|
+
return {
|
|
408
|
+
"status": "memory_starved",
|
|
409
|
+
"basis": "live",
|
|
410
|
+
"detail": "Service suffered host or GPU memory starvation",
|
|
411
|
+
}
|
|
412
|
+
if signal_num == 9 or exit_code == 137:
|
|
413
|
+
return {
|
|
414
|
+
"status": "oom",
|
|
415
|
+
"basis": "live",
|
|
416
|
+
"detail": "Process killed with SIGKILL (exit 137 / possible OOM)",
|
|
417
|
+
}
|
|
418
|
+
if (exit_code is not None and exit_code != 0) or (signal_num is not None and signal_num > 0):
|
|
419
|
+
return {
|
|
420
|
+
"status": "crashed",
|
|
421
|
+
"basis": "live",
|
|
422
|
+
"detail": f"Process exited abnormally (code={exit_code}, signal={signal_num})",
|
|
423
|
+
}
|
|
424
|
+
if states:
|
|
425
|
+
failed = [name for name, (st, _h) in states.items() if st == "failed"]
|
|
426
|
+
if failed:
|
|
427
|
+
return {
|
|
428
|
+
"status": "crashed",
|
|
429
|
+
"basis": "live",
|
|
430
|
+
"detail": f"Failed service(s): {', '.join(sorted(failed))}",
|
|
431
|
+
}
|
|
432
|
+
return {"status": "clean", "basis": "live", "detail": "All deployed services healthy"}
|
|
433
|
+
if exit_code == 0:
|
|
434
|
+
return {"status": "clean", "basis": "live", "detail": "Last service exit was clean"}
|
|
435
|
+
return {"status": "unknown", "basis": "none", "detail": "No deployed services observed"}
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
# --------------------------------------------------------------------------- Unified collector
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _read_text(path: Path) -> str | None:
|
|
442
|
+
try:
|
|
443
|
+
return path.read_text(encoding="utf-8", errors="replace")
|
|
444
|
+
except OSError:
|
|
445
|
+
return None
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _collect_linux(
|
|
449
|
+
prev_state: dict[str, Any], now_mono: float, proc: Path
|
|
450
|
+
) -> tuple[CpuSensors, DiskSensors, MemoryPressure, dict[str, Any]]:
|
|
451
|
+
stat_text = _read_text(proc / "stat")
|
|
452
|
+
disk_text = _read_text(proc / "diskstats")
|
|
453
|
+
mem_text = _read_text(proc / "meminfo")
|
|
454
|
+
psi_text = _read_text(proc / "pressure" / "memory")
|
|
455
|
+
|
|
456
|
+
curr_cpu = parse_proc_stat(stat_text) if stat_text else {}
|
|
457
|
+
curr_disk = parse_proc_diskstats(disk_text) if disk_text else None
|
|
458
|
+
prev_cpu = prev_state.get("cpu")
|
|
459
|
+
prev_disk = prev_state.get("disk")
|
|
460
|
+
prev_at = prev_state.get("at")
|
|
461
|
+
|
|
462
|
+
# On a cold sample with no prior snapshot, take one tiny 20 ms delta so live CPU % is real.
|
|
463
|
+
if not isinstance(prev_cpu, dict) and curr_cpu:
|
|
464
|
+
time.sleep(0.02)
|
|
465
|
+
now_mono = time.monotonic()
|
|
466
|
+
stat_text2 = _read_text(proc / "stat")
|
|
467
|
+
disk_text2 = _read_text(proc / "diskstats")
|
|
468
|
+
if stat_text2:
|
|
469
|
+
prev_cpu = curr_cpu
|
|
470
|
+
curr_cpu = parse_proc_stat(stat_text2)
|
|
471
|
+
if disk_text2 and curr_disk is not None:
|
|
472
|
+
prev_disk = curr_disk
|
|
473
|
+
curr_disk = parse_proc_diskstats(disk_text2)
|
|
474
|
+
prev_at = now_mono - 0.02
|
|
475
|
+
|
|
476
|
+
overall: float | None = None
|
|
477
|
+
per_core: list[CoreUsage] = []
|
|
478
|
+
if isinstance(prev_cpu, dict) and curr_cpu:
|
|
479
|
+
overall, per_core = diff_cpu_samples(prev_cpu, curr_cpu)
|
|
480
|
+
|
|
481
|
+
read_mb_s: float | None = None
|
|
482
|
+
write_mb_s: float | None = None
|
|
483
|
+
if (
|
|
484
|
+
isinstance(prev_disk, list | tuple)
|
|
485
|
+
and len(prev_disk) == 2
|
|
486
|
+
and curr_disk is not None
|
|
487
|
+
and isinstance(prev_at, int | float)
|
|
488
|
+
):
|
|
489
|
+
elapsed = now_mono - float(prev_at)
|
|
490
|
+
read_mb_s, write_mb_s = diff_disk_bytes(
|
|
491
|
+
(int(prev_disk[0]), int(prev_disk[1])), curr_disk, elapsed
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
mem_info = parse_proc_meminfo(mem_text) if mem_text else {}
|
|
495
|
+
total_mem = mem_info.get("MemTotal", 0)
|
|
496
|
+
avail_mem = mem_info.get("MemAvailable")
|
|
497
|
+
ratio = (avail_mem / total_mem) if total_mem > 0 and avail_mem is not None else None
|
|
498
|
+
swap_used = (
|
|
499
|
+
max(0, mem_info["SwapTotal"] - mem_info["SwapFree"])
|
|
500
|
+
if "SwapTotal" in mem_info and "SwapFree" in mem_info
|
|
501
|
+
else None
|
|
502
|
+
)
|
|
503
|
+
psi = parse_psi_some_avg10(psi_text) if psi_text else None
|
|
504
|
+
pressure = classify_memory_pressure(
|
|
505
|
+
available_ratio=ratio,
|
|
506
|
+
psi_some_avg10=psi,
|
|
507
|
+
swap_used_bytes=swap_used,
|
|
508
|
+
basis="live" if ratio is not None or psi is not None else "none",
|
|
509
|
+
)
|
|
510
|
+
|
|
511
|
+
next_state = {"at": now_mono, "cpu": curr_cpu, "disk": list(curr_disk) if curr_disk else None}
|
|
512
|
+
cpu_sensors: CpuSensors = {
|
|
513
|
+
"overall_pct": _fig(overall, "live", "/proc/stat overall CPU utilization"),
|
|
514
|
+
"per_core": per_core,
|
|
515
|
+
"logical_cores": os.cpu_count(),
|
|
516
|
+
}
|
|
517
|
+
disk_sensors: DiskSensors = {
|
|
518
|
+
"read_mb_s": _fig(read_mb_s, "live", "/proc/diskstats read throughput"),
|
|
519
|
+
"write_mb_s": _fig(write_mb_s, "live", "/proc/diskstats write throughput"),
|
|
520
|
+
}
|
|
521
|
+
return cpu_sensors, disk_sensors, pressure, next_state
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _collect_macos(
|
|
525
|
+
prev_state: dict[str, Any], now_mono: float
|
|
526
|
+
) -> tuple[CpuSensors, DiskSensors, MemoryPressure, dict[str, Any]]:
|
|
527
|
+
curr_cpu = _read_macos_cpu_ticks() or {}
|
|
528
|
+
curr_disk = _read_macos_disk_bytes()
|
|
529
|
+
prev_cpu = prev_state.get("cpu")
|
|
530
|
+
prev_disk = prev_state.get("disk")
|
|
531
|
+
prev_at = prev_state.get("at")
|
|
532
|
+
|
|
533
|
+
overall, per_core = (
|
|
534
|
+
diff_cpu_samples(prev_cpu, curr_cpu)
|
|
535
|
+
if isinstance(prev_cpu, dict) and curr_cpu
|
|
536
|
+
else (None, [])
|
|
537
|
+
)
|
|
538
|
+
read_mb_s: float | None = None
|
|
539
|
+
write_mb_s: float | None = None
|
|
540
|
+
if (
|
|
541
|
+
isinstance(prev_disk, list | tuple)
|
|
542
|
+
and len(prev_disk) == 2
|
|
543
|
+
and curr_disk is not None
|
|
544
|
+
and isinstance(prev_at, int | float)
|
|
545
|
+
):
|
|
546
|
+
read_mb_s, write_mb_s = diff_disk_bytes(
|
|
547
|
+
(int(prev_disk[0]), int(prev_disk[1])), curr_disk, now_mono - float(prev_at)
|
|
548
|
+
)
|
|
549
|
+
from localmodels import apple_sensors
|
|
550
|
+
|
|
551
|
+
level, basis, swap_used = apple_sensors.read_memory_pressure()
|
|
552
|
+
pressure: MemoryPressure = {
|
|
553
|
+
"level": level,
|
|
554
|
+
"basis": basis,
|
|
555
|
+
"available_ratio": None,
|
|
556
|
+
"psi_some_avg10": None,
|
|
557
|
+
"swap_used_bytes": swap_used,
|
|
558
|
+
}
|
|
559
|
+
next_state = {"at": now_mono, "cpu": curr_cpu, "disk": list(curr_disk) if curr_disk else None}
|
|
560
|
+
return (
|
|
561
|
+
{
|
|
562
|
+
"overall_pct": _fig(overall, "live", "host_processor_info CPU utilization"),
|
|
563
|
+
"per_core": per_core,
|
|
564
|
+
"logical_cores": os.cpu_count(),
|
|
565
|
+
},
|
|
566
|
+
{
|
|
567
|
+
"read_mb_s": _fig(read_mb_s, "live", "IOBlockStorageDriver read throughput"),
|
|
568
|
+
"write_mb_s": _fig(write_mb_s, "live", "IOBlockStorageDriver write throughput"),
|
|
569
|
+
},
|
|
570
|
+
pressure,
|
|
571
|
+
next_state,
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _collect_windows(
|
|
576
|
+
prev_state: dict[str, Any], now_mono: float
|
|
577
|
+
) -> tuple[CpuSensors, DiskSensors, MemoryPressure, dict[str, Any]]:
|
|
578
|
+
curr_times = _read_windows_system_times()
|
|
579
|
+
prev_times = prev_state.get("win_cpu")
|
|
580
|
+
overall: float | None = None
|
|
581
|
+
if isinstance(prev_times, list | tuple) and len(prev_times) == 3 and curr_times is not None:
|
|
582
|
+
overall = parse_windows_system_times(
|
|
583
|
+
(int(prev_times[0]), int(prev_times[1]), int(prev_times[2])), curr_times
|
|
584
|
+
)
|
|
585
|
+
pressure = _read_windows_memory_pressure()
|
|
586
|
+
next_state = {"at": now_mono, "win_cpu": list(curr_times) if curr_times else None}
|
|
587
|
+
return (
|
|
588
|
+
{
|
|
589
|
+
"overall_pct": _fig(overall, "live", "GetSystemTimes overall CPU utilization"),
|
|
590
|
+
"per_core": [],
|
|
591
|
+
"logical_cores": os.cpu_count(),
|
|
592
|
+
},
|
|
593
|
+
{
|
|
594
|
+
"read_mb_s": _fig(None, "none", "Windows PDH disk read sensor unavailable"),
|
|
595
|
+
"write_mb_s": _fig(None, "none", "Windows PDH disk write sensor unavailable"),
|
|
596
|
+
},
|
|
597
|
+
pressure,
|
|
598
|
+
next_state,
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def read_live_ram_available_bytes(proc: Path = _PROC) -> int | None:
|
|
603
|
+
"""Fast (< 1 ms) live host available RAM reading for steady-state ticks."""
|
|
604
|
+
if sys.platform.startswith("linux"):
|
|
605
|
+
text = _read_text(proc / "meminfo")
|
|
606
|
+
if text:
|
|
607
|
+
return parse_proc_meminfo(text).get("MemAvailable")
|
|
608
|
+
elif sys.platform == "win32":
|
|
609
|
+
try:
|
|
610
|
+
win_dll: Any = getattr(ctypes, "WinDLL", None)
|
|
611
|
+
if win_dll is None:
|
|
612
|
+
return None
|
|
613
|
+
mem = (ctypes.c_uint64 * 8)(64)
|
|
614
|
+
k32: Any = win_dll("kernel32", use_last_error=True)
|
|
615
|
+
if k32.GlobalMemoryStatusEx(ctypes.byref(mem)):
|
|
616
|
+
return int(mem[2])
|
|
617
|
+
except (OSError, AttributeError, ValueError):
|
|
618
|
+
return None
|
|
619
|
+
return None
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def collect(
|
|
623
|
+
*,
|
|
624
|
+
liveness: Mapping[str, tuple[str, str]] | None = None,
|
|
625
|
+
prev_state: dict[str, Any] | None = None,
|
|
626
|
+
proc: Path = _PROC,
|
|
627
|
+
) -> tuple[HostSensors, dict[str, Any]]:
|
|
628
|
+
"""Collect cross-platform host sensors and return ``(sensors, next_delta_state)``."""
|
|
629
|
+
now_mono = time.monotonic()
|
|
630
|
+
if prev_state is None:
|
|
631
|
+
with _PREV_SAMPLE_LOCK:
|
|
632
|
+
state_in: dict[str, Any] = dict(_PREV_SAMPLE)
|
|
633
|
+
else:
|
|
634
|
+
state_in = prev_state
|
|
635
|
+
if sys.platform.startswith("linux"):
|
|
636
|
+
cpu, disk, pressure, state_out = _collect_linux(state_in, now_mono, proc)
|
|
637
|
+
collector = "NVML · /proc/stat · /proc/diskstats · /proc/meminfo"
|
|
638
|
+
elif sys.platform == "darwin":
|
|
639
|
+
cpu, disk, pressure, state_out = _collect_macos(state_in, now_mono)
|
|
640
|
+
collector = "AppleSMC · host_processor_info · IOBlockStorageDriver"
|
|
641
|
+
elif sys.platform == "win32":
|
|
642
|
+
cpu, disk, pressure, state_out = _collect_windows(state_in, now_mono)
|
|
643
|
+
collector = "NVML · GetSystemTimes · GlobalMemoryStatusEx"
|
|
644
|
+
else:
|
|
645
|
+
cpu = {
|
|
646
|
+
"overall_pct": _fig(None, "none", "Unsupported platform"),
|
|
647
|
+
"per_core": [],
|
|
648
|
+
"logical_cores": os.cpu_count(),
|
|
649
|
+
}
|
|
650
|
+
disk = {
|
|
651
|
+
"read_mb_s": _fig(None, "none", "Unsupported platform"),
|
|
652
|
+
"write_mb_s": _fig(None, "none", "Unsupported platform"),
|
|
653
|
+
}
|
|
654
|
+
pressure = classify_memory_pressure(available_ratio=None)
|
|
655
|
+
state_out = {"at": now_mono}
|
|
656
|
+
collector = "none"
|
|
657
|
+
|
|
658
|
+
if prev_state is None:
|
|
659
|
+
with _PREV_SAMPLE_LOCK:
|
|
660
|
+
_PREV_SAMPLE.clear()
|
|
661
|
+
_PREV_SAMPLE.update(state_out)
|
|
662
|
+
|
|
663
|
+
watchdog = classify_watchdog_exit(states=liveness)
|
|
664
|
+
sensors: HostSensors = {
|
|
665
|
+
"cpu": cpu,
|
|
666
|
+
"disk": disk,
|
|
667
|
+
"memory_pressure": pressure,
|
|
668
|
+
"watchdog": watchdog,
|
|
669
|
+
"collector": collector,
|
|
670
|
+
}
|
|
671
|
+
return sensors, state_out
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def demo(busy: bool) -> HostSensors:
|
|
675
|
+
"""Synthetic host sensors for ``stack view --demo``, explicitly labelled ``demo``."""
|
|
676
|
+
overall = 46.0 if busy else 8.0
|
|
677
|
+
cores: list[CoreUsage] = [
|
|
678
|
+
{"core": idx, "util_pct": round(min(98.0, max(3.0, overall + (idx % 4 - 1.5) * 6.0)), 1)}
|
|
679
|
+
for idx in range(8)
|
|
680
|
+
]
|
|
681
|
+
return {
|
|
682
|
+
"cpu": {
|
|
683
|
+
"overall_pct": _fig(overall, "demo", "Demo data, not a measurement"),
|
|
684
|
+
"per_core": cores,
|
|
685
|
+
"logical_cores": 8,
|
|
686
|
+
},
|
|
687
|
+
"disk": {
|
|
688
|
+
"read_mb_s": _fig(32.0 if busy else 2.5, "demo", "Demo data, not a measurement"),
|
|
689
|
+
"write_mb_s": _fig(4.0 if busy else 0.5, "demo", "Demo data, not a measurement"),
|
|
690
|
+
},
|
|
691
|
+
"memory_pressure": {
|
|
692
|
+
"level": "nominal",
|
|
693
|
+
"basis": "demo",
|
|
694
|
+
"available_ratio": 0.62,
|
|
695
|
+
"psi_some_avg10": 0.0,
|
|
696
|
+
"swap_used_bytes": 0,
|
|
697
|
+
},
|
|
698
|
+
"watchdog": {
|
|
699
|
+
"status": "clean",
|
|
700
|
+
"basis": "demo",
|
|
701
|
+
"detail": "Demo data, not a measurement",
|
|
702
|
+
},
|
|
703
|
+
"collector": "demo",
|
|
704
|
+
}
|