@simplexai/localmodels-linux-arm64 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.
Files changed (113) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +105 -98
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +104 -43
  5. package/modules/localmodels/app.py +1 -1
  6. package/modules/localmodels/apple_sensors.py +431 -0
  7. package/modules/localmodels/bifrost_admin.py +83 -8
  8. package/modules/localmodels/bifrost_checks.py +2 -2
  9. package/modules/localmodels/bifrost_config.py +235 -13
  10. package/modules/localmodels/bifrost_log.py +166 -0
  11. package/modules/localmodels/bifrost_models.py +1 -1
  12. package/modules/localmodels/budget.py +1 -1
  13. package/modules/localmodels/catalog.json +192 -77
  14. package/modules/localmodels/catalog.py +20 -3
  15. package/modules/localmodels/catalog_add.py +42 -11
  16. package/modules/localmodels/custom_hub.py +983 -0
  17. package/modules/localmodels/custom_hub_http.py +579 -0
  18. package/modules/localmodels/custom_probe.py +451 -0
  19. package/modules/localmodels/deploy.py +27 -5
  20. package/modules/localmodels/deploy_steps.py +5 -0
  21. package/modules/localmodels/download-mirrors.json +8 -0
  22. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  23. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  24. package/modules/localmodels/engines.py +38 -8
  25. package/modules/localmodels/estimator.py +60 -7
  26. package/modules/localmodels/frontend.py +26 -21
  27. package/modules/localmodels/gateway.py +48 -3
  28. package/modules/localmodels/gateway_app_bifrost.py +4 -4
  29. package/modules/localmodels/gateway_bifrost.py +128 -21
  30. package/modules/localmodels/gguf.py +6 -0
  31. package/modules/localmodels/host_sensors.py +704 -0
  32. package/modules/localmodels/hosts.py +99 -12
  33. package/modules/localmodels/library_cli.py +181 -3
  34. package/modules/localmodels/library_convert.py +34 -0
  35. package/modules/localmodels/library_custom.py +831 -0
  36. package/modules/localmodels/library_elastic.py +182 -127
  37. package/modules/localmodels/library_gateway.py +193 -40
  38. package/modules/localmodels/library_jobs.py +92 -18
  39. package/modules/localmodels/library_kept.py +50 -6
  40. package/modules/localmodels/library_model.py +254 -2
  41. package/modules/localmodels/library_pricing.py +97 -8
  42. package/modules/localmodels/library_serve.py +196 -66
  43. package/modules/localmodels/library_smoke.py +315 -0
  44. package/modules/localmodels/library_state.py +81 -2
  45. package/modules/localmodels/library_status.py +144 -8
  46. package/modules/localmodels/metal.py +1 -1
  47. package/modules/localmodels/metal_probe.py +4 -4
  48. package/modules/localmodels/nvml_ctypes.py +431 -0
  49. package/modules/localmodels/plan_envelope.py +18 -7
  50. package/modules/localmodels/process_identity_linux.py +39 -0
  51. package/modules/localmodels/records.py +1 -0
  52. package/modules/localmodels/remote_ops.py +57 -8
  53. package/modules/localmodels/remote_ops_download.py +205 -53
  54. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  55. package/modules/localmodels/remote_ops_ranges.py +2 -5
  56. package/modules/localmodels/remote_ops_service.py +95 -37
  57. package/modules/localmodels/remote_ops_verify.py +22 -5
  58. package/modules/localmodels/runtime-lock.json +19 -19
  59. package/modules/localmodels/runtime_auth.py +4 -1
  60. package/modules/localmodels/service_control.py +32 -1
  61. package/modules/localmodels/service_wiring.py +237 -12
  62. package/modules/localmodels/service_worker.py +6 -2
  63. package/modules/localmodels/services_cli.py +35 -27
  64. package/modules/localmodels/setup_inspection.py +47 -70
  65. package/modules/localmodels/setup_inspection_harness.py +159 -15
  66. package/modules/localmodels/setup_text.py +14 -0
  67. package/modules/localmodels/setup_upgrade.py +1 -1
  68. package/modules/localmodels/source_byok.py +9 -7
  69. package/modules/localmodels/source_byok_probe.py +6 -1
  70. package/modules/localmodels/stack.py +9 -1
  71. package/modules/localmodels/stack_binding.py +3 -35
  72. package/modules/localmodels/stack_cleanup.py +4 -0
  73. package/modules/localmodels/stack_compose.py +18 -2
  74. package/modules/localmodels/stack_lifecycle.py +26 -3
  75. package/modules/localmodels/stack_memory.py +1 -0
  76. package/modules/localmodels/stack_plan.py +6 -2
  77. package/modules/localmodels/stack_ports.py +2 -0
  78. package/modules/localmodels/stack_remove.py +10 -1
  79. package/modules/localmodels/stack_up.py +33 -7
  80. package/modules/localmodels/stack_update.py +3 -1
  81. package/modules/localmodels/stack_view.py +77 -53
  82. package/modules/localmodels/stack_view_demo.py +36 -5
  83. package/modules/localmodels/stack_view_events.py +147 -12
  84. package/modules/localmodels/stack_view_gpu.py +97 -17
  85. package/modules/localmodels/stack_view_llm.py +15 -0
  86. package/modules/localmodels/stack_view_measure.py +4 -1
  87. package/modules/localmodels/stack_view_schema.py +54 -8
  88. package/modules/localmodels/stack_view_serve.py +40 -3
  89. package/modules/localmodels/stack_view_slots.py +89 -10
  90. package/modules/localmodels/stack_view_telemetry.py +163 -0
  91. package/modules/localmodels/stack_view_text.py +5 -2
  92. package/modules/localmodels/stack_view_tick.py +658 -0
  93. package/modules/localmodels/stack_view_words.py +4 -0
  94. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  95. package/modules/localmodels/suite.py +45 -27
  96. package/modules/localmodels/telemetry_math.py +538 -0
  97. package/modules/localmodels/transport.py +13 -2
  98. package/modules/localmodels/web/view/view.js +1 -1
  99. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/METADATA +1 -1
  100. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/RECORD +102 -95
  101. package/package.json +1 -1
  102. package/tool.json +1 -1
  103. package/modules/localmodels/bifrost_datasheet.py +0 -53
  104. package/modules/localmodels/bifrost_provider.py +0 -88
  105. package/modules/localmodels/bifrost_unit.py +0 -99
  106. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  107. package/modules/localmodels/gateway_switch.py +0 -51
  108. package/modules/localmodels/library_floor.py +0 -78
  109. package/modules/localmodels/service_stop.py +0 -52
  110. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/WHEEL +0 -0
  111. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/entry_points.txt +0 -0
  112. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/NOTICE +0 -0
  113. /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,431 @@
1
+ """Persistent ctypes binding to NVIDIA NVML (libnvidia-ml.so.1 / nvml.dll).
2
+
3
+ Provides zero-fork, read-only GPU telemetry (compute utilization, memory controller utilization,
4
+ VRAM total/used/free, temperature, power draw & limit, and per-process VRAM) on Linux and Windows.
5
+ Falls back cleanly (returning None) whenever NVML is unavailable or fails, without raising.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import atexit
11
+ import ctypes
12
+ import os
13
+ import sys
14
+ import threading
15
+ import time
16
+ from typing import Any, TypedDict
17
+
18
+ NVML_SUCCESS = 0
19
+ NVML_ERROR_UNINITIALIZED = 1
20
+ NVML_ERROR_INSUFFICIENT_SIZE = 7
21
+ NVML_ERROR_GPU_IS_LOST = 15
22
+ NVML_TEMPERATURE_GPU = 0
23
+ NVML_VALUE_NOT_AVAILABLE = 0xFFFFFFFFFFFFFFFF # 2**64 - 1 (WDDM / unsupported)
24
+ _RESET_ERRORS = frozenset({NVML_ERROR_UNINITIALIZED, NVML_ERROR_GPU_IS_LOST})
25
+ _RETRY_COOLDOWN_S = 30.0
26
+ _MAX_PROCESS_SLOTS = 256
27
+ _NAME_BUF_SIZE = 96
28
+
29
+
30
+ class NvmlProcess(TypedDict):
31
+ pid: int
32
+ used_bytes: int | None
33
+ kind: str # compute | graphics
34
+
35
+
36
+ class NvmlDeviceSample(TypedDict):
37
+ index: int
38
+ name: str
39
+ util_pct: float | None
40
+ mem_ctrl_util_pct: float | None
41
+ vram_total_bytes: int | None
42
+ vram_used_bytes: int | None
43
+ vram_free_bytes: int | None
44
+ temp_c: float | None
45
+ power_w: float | None
46
+ power_limit_w: float | None
47
+ processes: list[NvmlProcess]
48
+ basis: str # live
49
+
50
+
51
+ class _NvmlUtilization(ctypes.Structure):
52
+ _fields_ = [("gpu", ctypes.c_uint), ("memory", ctypes.c_uint)]
53
+
54
+
55
+ class _NvmlMemory(ctypes.Structure):
56
+ _fields_ = [
57
+ ("total", ctypes.c_ulonglong),
58
+ ("free", ctypes.c_ulonglong),
59
+ ("used", ctypes.c_ulonglong),
60
+ ]
61
+
62
+
63
+ class _NvmlProcessInfoV2(ctypes.Structure):
64
+ _fields_ = [
65
+ ("pid", ctypes.c_uint),
66
+ ("usedGpuMemory", ctypes.c_ulonglong),
67
+ ("gpuInstanceId", ctypes.c_uint),
68
+ ("computeInstanceId", ctypes.c_uint),
69
+ ]
70
+
71
+
72
+ def _candidate_libraries(platform: str | None = None) -> tuple[str, ...]:
73
+ plat = sys.platform if platform is None else platform
74
+ if plat == "win32":
75
+ candidates = ["nvml.dll"]
76
+ sys_root = os.environ.get("SystemRoot", r"C:\Windows")
77
+ prog_files = os.environ.get("ProgramFiles", r"C:\Program Files")
78
+ candidates.append(os.path.join(sys_root, "System32", "nvml.dll"))
79
+ candidates.append(os.path.join(prog_files, "NVIDIA Corporation", "NVSMI", "nvml.dll"))
80
+ return tuple(candidates)
81
+ if plat.startswith("linux"):
82
+ return ("libnvidia-ml.so.1", "libnvidia-ml.so")
83
+ return ()
84
+
85
+
86
+ def _load_library(platform: str | None = None) -> Any | None:
87
+ plat = sys.platform if platform is None else platform
88
+ # nvml.h exports cdecl symbols on both Linux and Windows; CDLL matches nvidia-ml-py/pynvml.
89
+ for name in _candidate_libraries(plat):
90
+ try:
91
+ return ctypes.CDLL(name)
92
+ except OSError:
93
+ continue
94
+ return None
95
+
96
+
97
+ def _resolve_fn(lib: Any, *names: str) -> Any | None:
98
+ for name in names:
99
+ fn = getattr(lib, name, None)
100
+ if fn is not None:
101
+ return fn
102
+ return None
103
+
104
+
105
+ def _set_proto(fn: Any, argtypes: list[Any], restype: Any = ctypes.c_int) -> None:
106
+ if fn is not None and hasattr(fn, "argtypes") and hasattr(fn, "restype"):
107
+ fn.argtypes = argtypes
108
+ fn.restype = restype
109
+
110
+
111
+ def _bind_prototypes(lib: Any) -> None:
112
+ """Bind explicit ctypes argtypes/restype on every NVML C entry point we invoke."""
113
+ c_uint_p = ctypes.POINTER(ctypes.c_uint)
114
+ c_void_pp = ctypes.POINTER(ctypes.c_void_p)
115
+ proc_p = ctypes.POINTER(_NvmlProcessInfoV2)
116
+ specs: list[tuple[tuple[str, ...], list[Any]]] = [
117
+ (("nvmlInit_v2", "nvmlInit"), []),
118
+ (("nvmlShutdown",), []),
119
+ (("nvmlDeviceGetCount_v2", "nvmlDeviceGetCount"), [c_uint_p]),
120
+ (
121
+ ("nvmlDeviceGetHandleByIndex_v2", "nvmlDeviceGetHandleByIndex"),
122
+ [ctypes.c_uint, c_void_pp],
123
+ ),
124
+ (("nvmlDeviceGetName",), [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint]),
125
+ (
126
+ ("nvmlDeviceGetUtilizationRates",),
127
+ [ctypes.c_void_p, ctypes.POINTER(_NvmlUtilization)],
128
+ ),
129
+ (("nvmlDeviceGetMemoryInfo",), [ctypes.c_void_p, ctypes.POINTER(_NvmlMemory)]),
130
+ (("nvmlDeviceGetTemperature",), [ctypes.c_void_p, ctypes.c_uint, c_uint_p]),
131
+ (("nvmlDeviceGetPowerUsage",), [ctypes.c_void_p, c_uint_p]),
132
+ (
133
+ ("nvmlDeviceGetEnforcedPowerLimit", "nvmlDeviceGetPowerManagementLimit"),
134
+ [ctypes.c_void_p, c_uint_p],
135
+ ),
136
+ (
137
+ (
138
+ "nvmlDeviceGetComputeRunningProcesses_v3",
139
+ "nvmlDeviceGetComputeRunningProcesses_v2",
140
+ ),
141
+ [ctypes.c_void_p, c_uint_p, proc_p],
142
+ ),
143
+ (
144
+ (
145
+ "nvmlDeviceGetGraphicsRunningProcesses_v3",
146
+ "nvmlDeviceGetGraphicsRunningProcesses_v2",
147
+ ),
148
+ [ctypes.c_void_p, c_uint_p, proc_p],
149
+ ),
150
+ ]
151
+ for names, argtypes in specs:
152
+ _set_proto(_resolve_fn(lib, *names), argtypes)
153
+
154
+
155
+ class _NvmlSession:
156
+ """Lazy, process-lifetime NVML handle guarded by a lock with cooldown retry & loss recovery."""
157
+
158
+ def __init__(self) -> None:
159
+ self._lock = threading.Lock()
160
+ self._lib: Any | None = None
161
+ self._initialized = False
162
+ self._failed_until = 0.0
163
+
164
+ def reset(self) -> None:
165
+ with self._lock:
166
+ self._shutdown_locked()
167
+ self._failed_until = 0.0
168
+
169
+ def _shutdown_locked(self) -> None:
170
+ if self._initialized and self._lib is not None:
171
+ shutdown = _resolve_fn(self._lib, "nvmlShutdown")
172
+ if shutdown is not None:
173
+ try:
174
+ shutdown()
175
+ except (OSError, ValueError):
176
+ pass
177
+ self._initialized = False
178
+ self._lib = None
179
+
180
+ def _ensure_locked(self) -> Any | None:
181
+ if self._initialized and self._lib is not None:
182
+ return self._lib
183
+ now = time.monotonic()
184
+ if now < self._failed_until:
185
+ return None
186
+ lib = _load_library()
187
+ if lib is None:
188
+ self._failed_until = now + _RETRY_COOLDOWN_S
189
+ return None
190
+ _bind_prototypes(lib)
191
+ init_fn = _resolve_fn(lib, "nvmlInit_v2", "nvmlInit")
192
+ if init_fn is None:
193
+ self._failed_until = now + _RETRY_COOLDOWN_S
194
+ return None
195
+ try:
196
+ rc = int(init_fn())
197
+ except (OSError, ValueError, TypeError):
198
+ self._failed_until = now + _RETRY_COOLDOWN_S
199
+ return None
200
+ if rc != NVML_SUCCESS:
201
+ self._failed_until = now + _RETRY_COOLDOWN_S
202
+ return None
203
+ self._lib = lib
204
+ self._initialized = True
205
+ self._failed_until = 0.0
206
+ return lib
207
+
208
+ def read_all(self, *, include_processes: bool = True) -> list[NvmlDeviceSample] | None:
209
+ with self._lock:
210
+ lib = self._ensure_locked()
211
+ if lib is None:
212
+ return None
213
+ devices, needs_reset = _query_devices(lib, include_processes=include_processes)
214
+ if needs_reset:
215
+ self._shutdown_locked()
216
+ self._failed_until = 0.0
217
+ return devices
218
+
219
+ def shutdown(self) -> None:
220
+ with self._lock:
221
+ self._shutdown_locked()
222
+
223
+
224
+ def _query_name(lib: Any, handle: ctypes.c_void_p, index: int) -> str:
225
+ fn = _resolve_fn(lib, "nvmlDeviceGetName")
226
+ if fn is None:
227
+ return f"GPU {index}"
228
+ buf = ctypes.create_string_buffer(_NAME_BUF_SIZE)
229
+ try:
230
+ if int(fn(handle, buf, ctypes.c_uint(_NAME_BUF_SIZE))) == NVML_SUCCESS:
231
+ return buf.value.decode("utf-8", "replace").strip() or f"GPU {index}"
232
+ except (OSError, ValueError, TypeError):
233
+ pass
234
+ return f"GPU {index}"
235
+
236
+
237
+ def _query_utilization(lib: Any, handle: ctypes.c_void_p) -> tuple[float | None, float | None]:
238
+ fn = _resolve_fn(lib, "nvmlDeviceGetUtilizationRates")
239
+ if fn is None:
240
+ return None, None
241
+ util = _NvmlUtilization()
242
+ try:
243
+ if int(fn(handle, ctypes.byref(util))) == NVML_SUCCESS:
244
+ gpu = float(util.gpu) if 0 <= util.gpu <= 100 else None
245
+ mem = float(util.memory) if 0 <= util.memory <= 100 else None
246
+ return gpu, mem
247
+ except (OSError, ValueError, TypeError):
248
+ pass
249
+ return None, None
250
+
251
+
252
+ def _query_memory(lib: Any, handle: ctypes.c_void_p) -> tuple[int | None, int | None, int | None]:
253
+ fn = _resolve_fn(lib, "nvmlDeviceGetMemoryInfo")
254
+ if fn is None:
255
+ return None, None, None
256
+ info = _NvmlMemory()
257
+ try:
258
+ if int(fn(handle, ctypes.byref(info))) == NVML_SUCCESS:
259
+ return int(info.total), int(info.used), int(info.free)
260
+ except (OSError, ValueError, TypeError):
261
+ pass
262
+ return None, None, None
263
+
264
+
265
+ def _query_temp(lib: Any, handle: ctypes.c_void_p) -> float | None:
266
+ fn = _resolve_fn(lib, "nvmlDeviceGetTemperature")
267
+ if fn is None:
268
+ return None
269
+ temp = ctypes.c_uint(0)
270
+ try:
271
+ if int(fn(handle, ctypes.c_uint(NVML_TEMPERATURE_GPU), ctypes.byref(temp))) == NVML_SUCCESS:
272
+ return float(temp.value)
273
+ except (OSError, ValueError, TypeError):
274
+ pass
275
+ return None
276
+
277
+
278
+ def _query_power(lib: Any, handle: ctypes.c_void_p) -> tuple[float | None, float | None]:
279
+ usage_w: float | None = None
280
+ limit_w: float | None = None
281
+ fn_usage = _resolve_fn(lib, "nvmlDeviceGetPowerUsage")
282
+ if fn_usage is not None:
283
+ mw = ctypes.c_uint(0)
284
+ try:
285
+ if int(fn_usage(handle, ctypes.byref(mw))) == NVML_SUCCESS:
286
+ usage_w = round(mw.value / 1000.0, 2)
287
+ except (OSError, ValueError, TypeError):
288
+ pass
289
+ fn_limit = _resolve_fn(
290
+ lib, "nvmlDeviceGetEnforcedPowerLimit", "nvmlDeviceGetPowerManagementLimit"
291
+ )
292
+ if fn_limit is not None:
293
+ mw_limit = ctypes.c_uint(0)
294
+ try:
295
+ if int(fn_limit(handle, ctypes.byref(mw_limit))) == NVML_SUCCESS and mw_limit.value > 0:
296
+ limit_w = round(mw_limit.value / 1000.0, 2)
297
+ except (OSError, ValueError, TypeError):
298
+ pass
299
+ return usage_w, limit_w
300
+
301
+
302
+ def _query_processes_of_kind(
303
+ lib: Any, handle: ctypes.c_void_p, fn_names: tuple[str, ...], kind: str
304
+ ) -> list[NvmlProcess]:
305
+ fn = _resolve_fn(lib, *fn_names)
306
+ if fn is None:
307
+ return []
308
+ count = ctypes.c_uint(_MAX_PROCESS_SLOTS)
309
+ buf = (_NvmlProcessInfoV2 * _MAX_PROCESS_SLOTS)()
310
+ try:
311
+ rc = int(fn(handle, ctypes.byref(count), buf))
312
+ except (OSError, ValueError, TypeError):
313
+ return []
314
+ if rc == NVML_ERROR_INSUFFICIENT_SIZE and count.value > 0:
315
+ capped = min(int(count.value), 1024)
316
+ count = ctypes.c_uint(capped)
317
+ buf = (_NvmlProcessInfoV2 * capped)()
318
+ try:
319
+ rc = int(fn(handle, ctypes.byref(count), buf))
320
+ except (OSError, ValueError, TypeError):
321
+ return []
322
+ if rc != NVML_SUCCESS:
323
+ return []
324
+ found: list[NvmlProcess] = []
325
+ for i in range(min(int(count.value), len(buf))):
326
+ raw_mem = int(buf[i].usedGpuMemory)
327
+ used = None if raw_mem == NVML_VALUE_NOT_AVAILABLE else raw_mem
328
+ found.append({"pid": int(buf[i].pid), "used_bytes": used, "kind": kind})
329
+ return found
330
+
331
+
332
+ def _query_processes(lib: Any, handle: ctypes.c_void_p) -> list[NvmlProcess]:
333
+ compute = _query_processes_of_kind(
334
+ lib,
335
+ handle,
336
+ (
337
+ "nvmlDeviceGetComputeRunningProcesses_v3",
338
+ "nvmlDeviceGetComputeRunningProcesses_v2",
339
+ ),
340
+ "compute",
341
+ )
342
+ graphics = _query_processes_of_kind(
343
+ lib,
344
+ handle,
345
+ (
346
+ "nvmlDeviceGetGraphicsRunningProcesses_v3",
347
+ "nvmlDeviceGetGraphicsRunningProcesses_v2",
348
+ ),
349
+ "graphics",
350
+ )
351
+ seen: dict[int, NvmlProcess] = {}
352
+ for proc in (*compute, *graphics):
353
+ prev = seen.get(proc["pid"])
354
+ if prev is None or (prev["used_bytes"] is None and proc["used_bytes"] is not None):
355
+ seen[proc["pid"]] = proc
356
+ return list(seen.values())
357
+
358
+
359
+ def _query_devices(
360
+ lib: Any, *, include_processes: bool = True
361
+ ) -> tuple[list[NvmlDeviceSample] | None, bool]:
362
+ count_fn = _resolve_fn(lib, "nvmlDeviceGetCount_v2", "nvmlDeviceGetCount")
363
+ handle_fn = _resolve_fn(lib, "nvmlDeviceGetHandleByIndex_v2", "nvmlDeviceGetHandleByIndex")
364
+ if count_fn is None or handle_fn is None:
365
+ return None, False
366
+ count = ctypes.c_uint(0)
367
+ try:
368
+ rc = int(count_fn(ctypes.byref(count)))
369
+ except (OSError, ValueError, TypeError):
370
+ return None, False
371
+ if rc != NVML_SUCCESS:
372
+ return None, rc in _RESET_ERRORS
373
+ devices: list[NvmlDeviceSample] = []
374
+ for index in range(int(count.value)):
375
+ handle = ctypes.c_void_p()
376
+ try:
377
+ h_rc = int(handle_fn(ctypes.c_uint(index), ctypes.byref(handle)))
378
+ except (OSError, ValueError, TypeError):
379
+ continue
380
+ if h_rc != NVML_SUCCESS:
381
+ if h_rc in _RESET_ERRORS:
382
+ return None, True
383
+ continue
384
+ util_pct, mem_ctrl_pct = _query_utilization(lib, handle)
385
+ total_b, used_b, free_b = _query_memory(lib, handle)
386
+ power_w, power_limit_w = _query_power(lib, handle)
387
+ devices.append(
388
+ {
389
+ "index": index,
390
+ "name": _query_name(lib, handle, index),
391
+ "util_pct": util_pct,
392
+ "mem_ctrl_util_pct": mem_ctrl_pct,
393
+ "vram_total_bytes": total_b,
394
+ "vram_used_bytes": used_b,
395
+ "vram_free_bytes": free_b,
396
+ "temp_c": _query_temp(lib, handle),
397
+ "power_w": power_w,
398
+ "power_limit_w": power_limit_w,
399
+ "processes": _query_processes(lib, handle) if include_processes else [],
400
+ "basis": "live",
401
+ }
402
+ )
403
+ return devices, False
404
+
405
+
406
+ _SESSION = _NvmlSession()
407
+ atexit.register(_SESSION.shutdown)
408
+
409
+
410
+ def read_devices(*, include_processes: bool = True) -> list[NvmlDeviceSample] | None:
411
+ """Read live NVML metrics for all NVIDIA GPUs; None when NVML is unavailable."""
412
+ return _SESSION.read_all(include_processes=include_processes)
413
+
414
+
415
+ def read_process_vram() -> dict[int, int] | None:
416
+ """Per-PID VRAM bytes summed across NVIDIA GPUs via NVML; None when NVML is unavailable."""
417
+ devices = _SESSION.read_all(include_processes=True)
418
+ if devices is None:
419
+ return None
420
+ used: dict[int, int] = {}
421
+ for dev in devices:
422
+ for proc in dev["processes"]:
423
+ mem = proc["used_bytes"]
424
+ if mem is not None and mem > 0:
425
+ used[proc["pid"]] = used.get(proc["pid"], 0) + mem
426
+ return used
427
+
428
+
429
+ def reset_session() -> None:
430
+ """Reset the cached NVML session (for unit tests and driver reload recovery)."""
431
+ _SESSION.reset()
@@ -325,7 +325,10 @@ def service_name(base_dir: str, name: str) -> str:
325
325
 
326
326
 
327
327
  def _same_dir(a: str, b: str) -> bool:
328
- return os.path.normpath(os.path.expanduser(a)) == os.path.normpath(os.path.expanduser(b))
328
+ def norm(path: str) -> str:
329
+ return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
330
+
331
+ return norm(a) == norm(b)
329
332
 
330
333
 
331
334
  def resolved_name(model_id: str, port: int, base_dir: str, taken: Mapping[str, str]) -> str:
@@ -361,14 +364,20 @@ def cpu_threads(facts: HostFacts) -> int:
361
364
 
362
365
 
363
366
  def verified_in_place(f: ReusableFile) -> bool:
364
- """An existing destination with the download action's matching SHA256 receipt."""
367
+ """An existing destination with the download action's matching SHA256 receipt (or exact size
368
+ plus GGUF magic header when the hub published no SHA256)."""
365
369
  path = Path(f["dest"]).expanduser()
366
370
  try:
367
- return (
368
- path.is_file()
369
- and path.stat().st_size == f["size_bytes"]
370
- and Path(str(path) + ".sha256").read_text().strip() == f["sha256"]
371
- )
371
+ if not path.is_file() or path.stat().st_size != f["size_bytes"]:
372
+ return False
373
+ if not f["sha256"]:
374
+ if f["size_bytes"] <= 0:
375
+ return False
376
+ if path.name.lower().endswith(".gguf"):
377
+ with path.open("rb") as handle:
378
+ return handle.read(4) == b"GGUF"
379
+ return True
380
+ return Path(str(path) + ".sha256").read_text().strip() == f["sha256"]
372
381
  except (OSError, UnicodeError):
373
382
  return False
374
383
 
@@ -447,6 +456,8 @@ def plan_envelope(
447
456
  for key in ("limits", "slice", "slice_limits", "config_files"):
448
457
  if key in service:
449
458
  svc[key] = service[key]
459
+ if "autostart" in service:
460
+ svc["autostart"] = service["autostart"]
450
461
  return {
451
462
  "schema": PLAN_SCHEMA,
452
463
  "name": where.name,
@@ -6,6 +6,7 @@ import os
6
6
  import shlex
7
7
  import shutil
8
8
  import subprocess
9
+ import sys
9
10
  import time
10
11
  from pathlib import Path
11
12
 
@@ -165,3 +166,41 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
165
166
  return argv_matches(actual, process.joinpath("exe"), expected, root)
166
167
  except (OSError, ValueError, UnicodeError):
167
168
  return False
169
+
170
+
171
+ def bind_to_parent(parent: object) -> None:
172
+ """End this local POSIX streaming helper when its controller dies (e.g. SIGKILL), matching
173
+ Windows's kill-on-close job object so an orphan never keeps writing ``.part`` files after
174
+ ``cancel`` or a resumed download took over."""
175
+ if not isinstance(parent, int) or isinstance(parent, bool) or parent <= 1 or os.name == "nt":
176
+ return
177
+ armed = False
178
+ if sys.platform.startswith("linux"):
179
+ try:
180
+ import ctypes
181
+ import signal
182
+
183
+ libc = ctypes.CDLL(None)
184
+ libc.prctl.argtypes = (
185
+ ctypes.c_int,
186
+ ctypes.c_ulong,
187
+ ctypes.c_ulong,
188
+ ctypes.c_ulong,
189
+ ctypes.c_ulong,
190
+ )
191
+ libc.prctl.restype = ctypes.c_int
192
+ armed = libc.prctl(1, signal.SIGKILL, 0, 0, 0) == 0 # PR_SET_PDEATHSIG = 1
193
+ except (OSError, AttributeError):
194
+ armed = False
195
+ if os.getppid() != parent:
196
+ os._exit(1)
197
+ if not armed:
198
+ import threading
199
+
200
+ def _watch() -> None:
201
+ while True:
202
+ time.sleep(0.2)
203
+ if os.getppid() != parent:
204
+ os._exit(1)
205
+
206
+ threading.Thread(target=_watch, name="parent-watch", daemon=True).start()
@@ -109,6 +109,7 @@ class Launch(RequiredLaunch, total=False):
109
109
  slice: str # the suite slice that bounds every component together
110
110
  slice_limits: dict[str, str]
111
111
  config_files: dict[str, str] # {path: content} written beside the launch script
112
+ autostart: bool # False skips systemd enable on boot (standby_on_restart custom models)
112
113
 
113
114
 
114
115
  class RequiredService(TypedDict):
@@ -25,6 +25,7 @@ import hashlib
25
25
  import ipaddress
26
26
  import json
27
27
  import os
28
+ import re
28
29
  import shutil
29
30
  import socket
30
31
  import subprocess
@@ -139,6 +140,7 @@ class _DownloadParams(TypedDict):
139
140
  class DownloadParams(_DownloadParams, total=False):
140
141
  preparation: StrataPreparation
141
142
  region: str # cn or global: the order of the download sources (region.py)
143
+ auth_headers: dict[str, str] # host -> Authorization header value (in-memory only via stdin)
142
144
 
143
145
 
144
146
  class _Install(ServiceParams):
@@ -152,6 +154,7 @@ class InstallParams(_Install, total=False):
152
154
  slice: str # the systemd --user slice the unit runs in, with its own limits
153
155
  slice_limits: dict[str, str]
154
156
  config_files: dict[str, str] # {path: content}, e.g. a Strata serve profile
157
+ autostart: bool # False skips systemd --user enable on boot
155
158
 
156
159
 
157
160
  class _Verify(ServiceParams):
@@ -167,6 +170,7 @@ class VerifyParams(_Verify, total=False):
167
170
  vision: bool # the LLM loads a picture reader: a synthetic picture must be read too
168
171
  window: int # stack agent LLM: /props n_ctx must be at least the planned window
169
172
  weights_on_gpu: bool # none stay in host memory: Windows gets back what they were read through
173
+ smoke: bool # minimal smoke-test completion ("Reply with OK.", max_tokens=16)
170
174
 
171
175
 
172
176
  class RemoveParams(ServiceParams, total=False):
@@ -406,7 +410,40 @@ def _transfer_once(
406
410
  remote_ops_download.transfer(source, part, size, label, ranged)
407
411
 
408
412
 
413
+ _SECRET_RE = re.compile(
414
+ r"(?:Bearer\s+\S+|hf_[A-Za-z0-9]{6,}|ms[-_][A-Za-z0-9_-]{6,})",
415
+ re.IGNORECASE,
416
+ )
417
+
418
+
419
+ def redact_text(text: str) -> str:
420
+ """Strip Bearer credentials and hub token patterns from logs and errors."""
421
+ return _SECRET_RE.sub("[REDACTED]", text)
422
+
423
+
424
+ def gguf_magic_ok(path: str, label: str) -> bool:
425
+ """Verify the 4-byte GGUF magic header for .gguf files."""
426
+ if not label.lower().endswith(".gguf"):
427
+ return True
428
+ try:
429
+ with open(path, "rb") as handle:
430
+ return handle.read(4) == b"GGUF"
431
+ except OSError:
432
+ return False
433
+
434
+
409
435
  def _existing_verified(dest: str, marker: str, sha256: str, size: int, label: str) -> bool:
436
+ if not sha256:
437
+ if (
438
+ size > 0
439
+ and os.path.exists(dest)
440
+ and os.path.getsize(dest) == size
441
+ and gguf_magic_ok(dest, label)
442
+ ):
443
+ emit("log", message="verified, skipping " + label)
444
+ return True
445
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
446
+ return False
410
447
  if os.path.exists(dest) and os.path.exists(marker) and _read(marker).strip() == sha256:
411
448
  emit("log", message="verified, skipping " + label)
412
449
  return True
@@ -491,7 +528,10 @@ def fetch(
491
528
  failed.append(source)
492
529
  continue
493
530
  except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
494
- emit("log", message=f"download from {source['source']} stopped, {label}: {exc}")
531
+ emit(
532
+ "log",
533
+ message=f"download from {source['source']} stopped, {label}: {redact_text(str(exc))}",
534
+ )
495
535
  error = exc
496
536
  failed.append(source)
497
537
  continue
@@ -505,8 +545,11 @@ def fetch(
505
545
  continue
506
546
  remote_ops_download.discard(part + ".ranges") # the record only; part is renamed
507
547
  os.replace(part, dest)
508
- _write(marker, sha256)
509
- _store_cached(dest, sha256, size)
548
+ if sha256:
549
+ _write(marker, sha256)
550
+ _store_cached(dest, sha256, size)
551
+ else:
552
+ _write(marker, _sha256(dest, label))
510
553
  switch = _fallback(region, source, failed, probe_speeds)
511
554
  extra = {"region_fallback": switch} if switch else {}
512
555
  emit("log", message=f"downloaded and verified {label} from {source['source']}", **extra)
@@ -520,8 +563,13 @@ def _check_part(
520
563
  part: str, sha256: str, size: int, label: str, source_name: str
521
564
  ) -> Exception | None:
522
565
  got_size = os.path.getsize(part)
523
- if got_size != size:
566
+ if size <= 0 or got_size != size:
524
567
  return RuntimeError(f"{label} size mismatch: {got_size} != {size}")
568
+ if not sha256:
569
+ if not gguf_magic_ok(part, label):
570
+ emit("log", message=f"{label} from {source_name} failed the GGUF magic check")
571
+ return RuntimeError(f"{label} is not a valid GGUF file (bad magic)")
572
+ return None
525
573
  actual = _sha256(part, label)
526
574
  if actual != sha256:
527
575
  emit("log", message=f"{label} from {source_name} failed the SHA256 check")
@@ -619,6 +667,8 @@ def unpack(archive: str, directory: str, keep: tuple[str, ...] = ()) -> None:
619
667
  member.mode |= 0o700
620
668
  elif member.isfile():
621
669
  member.mode |= 0o200
670
+ if member.issym() or member.islnk():
671
+ remote_ops_download.clear_link(os.path.join(directory, name))
622
672
  tar.extract(member, directory)
623
673
 
624
674
 
@@ -729,9 +779,8 @@ ACTIONS: Actions = {
729
779
 
730
780
 
731
781
  def main(argv: list[str]) -> int:
732
- # Like the controller: never leave a group- or world-writable file under a login umask of
733
- # 0002; the controller's ownership checks refuse such files.
734
- os.umask(os.umask(0o022) | 0o022)
782
+ remote_ops_download.bind_to_parent(globals().get("_PARENT_PID"))
783
+ os.umask(os.umask(0o022) | 0o022) # never leave group/world-writable files under umask 0002
735
784
  encoded = globals().get("_PARAMS_B64") or (argv[2] if len(argv) == 3 else None)
736
785
  if len(argv) not in (2, 3) or argv[1] not in ACTIONS or encoded is None:
737
786
  sys.stderr.write("usage: remote_ops.py {{{}}} [PARAMS_B64]\n".format("|".join(ACTIONS)))
@@ -740,7 +789,7 @@ def main(argv: list[str]) -> int:
740
789
  try:
741
790
  run(json.loads(base64.b64decode(encoded).decode("utf-8")))
742
791
  except Exception as exc: # report every failure as an event the controller can show
743
- emit("error", message=str(exc), type=type(exc).__name__)
792
+ emit("error", message=redact_text(str(exc)), type=type(exc).__name__)
744
793
  return 1
745
794
  return 0
746
795