@simplexai/localmodels-darwin-x64 0.1.0-dev.107 → 0.1.0-dev.109
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/NOTICE +13 -6
- package/README.md +1 -1
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +54 -50
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/catalog.json +682 -67
- package/modules/localmodels/catalog.py +11 -1
- package/modules/localmodels/catalog_recipes.py +26 -3
- package/modules/localmodels/chat_template.py +6 -0
- package/modules/localmodels/chat_templates/qwen4-35b-a3b.jinja +223 -0
- package/modules/localmodels/debug_stub_server.py +1 -1
- package/modules/localmodels/download-mirrors.json +23 -34
- package/modules/localmodels/engine_adapters/llama_cpp.py +11 -5
- package/modules/localmodels/engine_adapters/strata_poly.py +1 -1
- package/modules/localmodels/engines-b12973.json +248 -0
- package/modules/localmodels/library_cli.py +68 -1
- package/modules/localmodels/library_direct.py +2 -0
- package/modules/localmodels/library_elastic.py +1 -1
- package/modules/localmodels/library_model.py +4 -0
- package/modules/localmodels/library_order.py +44 -1
- package/modules/localmodels/library_presentation.py +1 -0
- package/modules/localmodels/library_pricing.py +1 -2
- package/modules/localmodels/library_unload.py +274 -0
- package/modules/localmodels/probe.py +98 -7
- package/modules/localmodels/service_roots.py +148 -0
- package/modules/localmodels/service_upgrade.py +46 -1
- package/modules/localmodels/services_cli.py +8 -28
- package/modules/localmodels/speech_workers.py +4 -4
- package/modules/localmodels/stack_args.py +11 -4
- package/modules/localmodels/stack_down.py +368 -42
- package/modules/localmodels/stack_memory.py +1 -1
- package/modules/localmodels/stack_preflight.py +2 -2
- package/modules/localmodels/stack_view_llm.py +2 -2
- package/modules/localmodels/suite.py +4 -0
- package/modules/localmodels/tts-moss.txt +78 -53
- package/modules/localmodels/tts_backend_speechcpp.py +2 -2
- package/modules/localmodels/tts_catalog.py +2 -2
- package/modules/localmodels/tts_cli.py +3 -3
- package/modules/localmodels/tts_jobs.py +1 -3
- package/modules/localmodels/tts_model.py +3 -3
- package/modules/localmodels/tts_moss_presets.json +1 -1
- package/modules/localmodels/tts_sidecar.py +7 -3
- package/modules/localmodels/tts_state.py +15 -0
- package/modules/localmodels/tts_worker_kokoro.py +939 -255
- package/modules/localmodels/tts_worker_moss.py +25 -9
- package/modules/localmodels/tts_workers.py +17 -21
- package/modules/{simplex_localmodels-0.1.0.dev107.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev107.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/RECORD +49 -45
- package/modules/{simplex_localmodels-0.1.0.dev107.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/licenses/NOTICE +13 -6
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev107.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev107.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev107.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/licenses/LICENSE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev107.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""``library unload --all``: unload every active library model and cancel active library jobs.
|
|
2
|
+
|
|
3
|
+
Composes with ``library_serve.stop`` and ``library_state`` / ``library_jobs`` without requiring
|
|
4
|
+
hardware probing or catalog resolution, so retired, custom, and legacy on-disk records unload
|
|
5
|
+
cleanly. Idle records and failed-download jobs (with resumable partials) are safely skipped.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Literal, TypedDict
|
|
13
|
+
|
|
14
|
+
from localmodels import (
|
|
15
|
+
cli_help,
|
|
16
|
+
console,
|
|
17
|
+
library_jobs,
|
|
18
|
+
library_serve,
|
|
19
|
+
library_state,
|
|
20
|
+
runtime_index,
|
|
21
|
+
)
|
|
22
|
+
from localmodels.library_model import DETAIL_LIMIT, ERROR_CODES, LibraryError
|
|
23
|
+
from localmodels.library_state import Job
|
|
24
|
+
from localmodels.transport import Executor
|
|
25
|
+
|
|
26
|
+
UNLOAD_ALL_SCHEMA: Literal["localmodels.library-unload-all/v1"] = (
|
|
27
|
+
"localmodels.library-unload-all/v1"
|
|
28
|
+
)
|
|
29
|
+
Out = Callable[[str], None]
|
|
30
|
+
|
|
31
|
+
PreviousState = Literal["loaded", "starting", "failed", "loading", "downloading", "smoke_test"]
|
|
32
|
+
UnloadAction = Literal["unloaded", "cancelled"]
|
|
33
|
+
SkipReason = Literal["already_idle", "failed_download"]
|
|
34
|
+
|
|
35
|
+
_DOWNLOAD_STOP_GRACE_S = 20.0
|
|
36
|
+
_ACTIVE_JOB_GRACE_POSIX_S = 5.0
|
|
37
|
+
_ACTIVE_JOB_GRACE_WINDOWS_S = 2.0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class UnloadAllItem(TypedDict):
|
|
41
|
+
id: str
|
|
42
|
+
previous_state: PreviousState
|
|
43
|
+
action: UnloadAction
|
|
44
|
+
detail: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class UnloadAllSkipped(TypedDict):
|
|
48
|
+
id: str
|
|
49
|
+
state: Literal["idle", "failed"]
|
|
50
|
+
reason: SkipReason
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class UnloadAllError(TypedDict):
|
|
54
|
+
id: str
|
|
55
|
+
code: str
|
|
56
|
+
detail: str
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class UnloadAllReport(TypedDict):
|
|
60
|
+
schema: Literal["localmodels.library-unload-all/v1"]
|
|
61
|
+
ok: bool
|
|
62
|
+
unloaded: list[UnloadAllItem]
|
|
63
|
+
skipped: list[UnloadAllSkipped]
|
|
64
|
+
errors: list[UnloadAllError]
|
|
65
|
+
runtime_index_refreshed: bool
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _previous_job_state(kind: str) -> PreviousState:
|
|
69
|
+
if kind == "download":
|
|
70
|
+
return "downloading"
|
|
71
|
+
if kind == "smoke_test":
|
|
72
|
+
return "smoke_test"
|
|
73
|
+
return "loading"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _previous_record_state(raw: str) -> PreviousState:
|
|
77
|
+
if raw == "starting":
|
|
78
|
+
return "starting"
|
|
79
|
+
if raw == "failed":
|
|
80
|
+
return "failed"
|
|
81
|
+
return "loaded"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _job_grace_seconds(kind: str) -> float:
|
|
85
|
+
if kind == "download":
|
|
86
|
+
return _DOWNLOAD_STOP_GRACE_S
|
|
87
|
+
return _ACTIVE_JOB_GRACE_WINDOWS_S if sys.platform == "win32" else _ACTIVE_JOB_GRACE_POSIX_S
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _stop_active_job(model_id: str, job: Job, base_dir: str) -> PreviousState:
|
|
91
|
+
"""Cancel an in-flight download, load, or smoke-test job using its verified process receipt."""
|
|
92
|
+
kind = job["kind"]
|
|
93
|
+
if kind in ("unload", "remove"):
|
|
94
|
+
raise LibraryError("JOB_RUNNING", f"{model_id} has a running {kind}", failed=True)
|
|
95
|
+
|
|
96
|
+
with library_state.locked():
|
|
97
|
+
current_job = library_state.read_job(model_id)
|
|
98
|
+
if current_job is None or current_job.get("id") != job.get("id"):
|
|
99
|
+
return _previous_job_state(kind)
|
|
100
|
+
if not library_state.job_alive(model_id):
|
|
101
|
+
if kind != "download" or library_state.load(model_id) is not None:
|
|
102
|
+
library_state.clear_job(model_id)
|
|
103
|
+
return _previous_job_state(kind)
|
|
104
|
+
identity = library_state.receipt(model_id)
|
|
105
|
+
library_state.mark_cancelled(current_job)
|
|
106
|
+
|
|
107
|
+
if identity is not None:
|
|
108
|
+
try:
|
|
109
|
+
library_state.stop_process(identity, grace=_job_grace_seconds(kind))
|
|
110
|
+
except (OSError, RuntimeError) as exc:
|
|
111
|
+
code = "INVALID_STATE" if kind == "download" else "ENGINE_START_FAILED"
|
|
112
|
+
raise LibraryError(code, f"cannot stop active {kind}: {exc}", failed=True) from None
|
|
113
|
+
elif library_state.job_alive(model_id):
|
|
114
|
+
raise LibraryError(
|
|
115
|
+
"ENGINE_START_FAILED",
|
|
116
|
+
f"cannot stop active {kind}: missing process receipt",
|
|
117
|
+
failed=True,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
with library_state.locked():
|
|
121
|
+
committed = library_state.load(model_id) is not None
|
|
122
|
+
if library_state.current(job) and not library_state.job_alive(model_id):
|
|
123
|
+
if kind == "download" and not committed:
|
|
124
|
+
gone = library_jobs.leftovers(job)
|
|
125
|
+
library_jobs.delete_weights(gone, library_jobs.in_use(model_id))
|
|
126
|
+
library_jobs.prune_empty_custom_dirs(gone, job.get("base_dir") or base_dir)
|
|
127
|
+
library_state.clear_job(model_id)
|
|
128
|
+
else:
|
|
129
|
+
library_state.clear_job(model_id)
|
|
130
|
+
|
|
131
|
+
return _previous_job_state(kind)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _inspect_and_handle_job(
|
|
135
|
+
model_id: str, base_dir: str
|
|
136
|
+
) -> tuple[PreviousState | None, UnloadAllSkipped | None]:
|
|
137
|
+
"""Handle any live or stale job for ``model_id``; returns ``(cancelled_state, skipped)``."""
|
|
138
|
+
with library_state.locked():
|
|
139
|
+
job = library_state.read_job(model_id)
|
|
140
|
+
if job is None:
|
|
141
|
+
return None, None
|
|
142
|
+
alive = library_state.job_alive(model_id)
|
|
143
|
+
record = library_state.load(model_id)
|
|
144
|
+
if not alive:
|
|
145
|
+
if job["kind"] == "download" and record is None:
|
|
146
|
+
return None, {
|
|
147
|
+
"id": model_id,
|
|
148
|
+
"state": "failed",
|
|
149
|
+
"reason": "failed_download",
|
|
150
|
+
}
|
|
151
|
+
library_state.clear_job(model_id)
|
|
152
|
+
return None, None
|
|
153
|
+
cancelled_state = _stop_active_job(model_id, job, base_dir)
|
|
154
|
+
return cancelled_state, None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _unload_one(
|
|
158
|
+
model_id: str,
|
|
159
|
+
base_dir: str,
|
|
160
|
+
executor: Executor,
|
|
161
|
+
) -> tuple[UnloadAllItem | None, UnloadAllSkipped | None]:
|
|
162
|
+
"""Best-effort unload/cancel of one model id; raises ``LibraryError`` on failure."""
|
|
163
|
+
cancelled_state, skipped = _inspect_and_handle_job(model_id, base_dir)
|
|
164
|
+
if skipped is not None:
|
|
165
|
+
return None, skipped
|
|
166
|
+
|
|
167
|
+
with library_state.locked():
|
|
168
|
+
record = library_state.load(model_id)
|
|
169
|
+
if record is None:
|
|
170
|
+
if cancelled_state is None:
|
|
171
|
+
return None, None
|
|
172
|
+
return {
|
|
173
|
+
"id": model_id,
|
|
174
|
+
"previous_state": cancelled_state,
|
|
175
|
+
"action": "cancelled",
|
|
176
|
+
"detail": "",
|
|
177
|
+
}, None
|
|
178
|
+
if record["state"] == "idle":
|
|
179
|
+
if cancelled_state is not None:
|
|
180
|
+
return {
|
|
181
|
+
"id": model_id,
|
|
182
|
+
"previous_state": cancelled_state,
|
|
183
|
+
"action": "cancelled",
|
|
184
|
+
"detail": "",
|
|
185
|
+
}, None
|
|
186
|
+
return None, {"id": model_id, "state": "idle", "reason": "already_idle"}
|
|
187
|
+
library_state.refuse_busy(model_id, "unload")
|
|
188
|
+
prev_state = cancelled_state or _previous_record_state(record["state"])
|
|
189
|
+
claim = library_state.acquire("unload", model_id, record["pool"], 0, [])
|
|
190
|
+
|
|
191
|
+
with library_state.held([claim]):
|
|
192
|
+
library_serve.stop(record, executor)
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
"id": model_id,
|
|
196
|
+
"previous_state": prev_state,
|
|
197
|
+
"action": "unloaded",
|
|
198
|
+
"detail": "",
|
|
199
|
+
}, None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _error_entry(model_id: str, exc: Exception) -> UnloadAllError:
|
|
203
|
+
if isinstance(exc, LibraryError):
|
|
204
|
+
code = exc.code if exc.code in ERROR_CODES else "ENGINE_START_FAILED"
|
|
205
|
+
detail = exc.detail
|
|
206
|
+
else:
|
|
207
|
+
code = "ENGINE_START_FAILED"
|
|
208
|
+
detail = str(exc) or type(exc).__name__
|
|
209
|
+
return {"id": model_id, "code": code, "detail": detail[-DETAIL_LIMIT:]}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def unload_all(base_dir: str = cli_help.DEFAULT_BASE_DIR) -> UnloadAllReport:
|
|
213
|
+
"""Unload every active/loaded library model and cancel active jobs (best-effort)."""
|
|
214
|
+
records = library_state.records()
|
|
215
|
+
jobs = library_state.jobs()
|
|
216
|
+
model_ids = sorted({record["id"] for record in records} | set(jobs))
|
|
217
|
+
|
|
218
|
+
unloaded: list[UnloadAllItem] = []
|
|
219
|
+
skipped: list[UnloadAllSkipped] = []
|
|
220
|
+
errors: list[UnloadAllError] = []
|
|
221
|
+
|
|
222
|
+
if model_ids:
|
|
223
|
+
executor = library_jobs.executor()
|
|
224
|
+
for model_id in model_ids:
|
|
225
|
+
try:
|
|
226
|
+
item, skip = _unload_one(model_id, base_dir, executor)
|
|
227
|
+
except (LibraryError, OSError, RuntimeError, ValueError) as exc:
|
|
228
|
+
errors.append(_error_entry(model_id, exc))
|
|
229
|
+
continue
|
|
230
|
+
if item is not None:
|
|
231
|
+
unloaded.append(item)
|
|
232
|
+
elif skip is not None:
|
|
233
|
+
skipped.append(skip)
|
|
234
|
+
|
|
235
|
+
refreshed = runtime_index.refresh() is not None
|
|
236
|
+
return {
|
|
237
|
+
"schema": UNLOAD_ALL_SCHEMA,
|
|
238
|
+
"ok": not errors,
|
|
239
|
+
"unloaded": unloaded,
|
|
240
|
+
"skipped": skipped,
|
|
241
|
+
"errors": errors,
|
|
242
|
+
"runtime_index_refreshed": refreshed,
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def print_report(report: UnloadAllReport, out: Out = print) -> int:
|
|
247
|
+
"""Print a concise human-readable summary of ``library unload --all``."""
|
|
248
|
+
t = console.term(sys.stdout)
|
|
249
|
+
for item in report["unloaded"]:
|
|
250
|
+
out(
|
|
251
|
+
f"{t.mark('ok')} {item['id']} {item['action']} (was {item['previous_state']})"
|
|
252
|
+
+ (f": {item['detail']}" if item["detail"] else "")
|
|
253
|
+
)
|
|
254
|
+
for skip in report["skipped"]:
|
|
255
|
+
reason = "already idle" if skip["reason"] == "already_idle" else "failed download kept"
|
|
256
|
+
out(f"{t.mark('skip')} {skip['id']} skipped ({reason})")
|
|
257
|
+
for err in report["errors"]:
|
|
258
|
+
out(f"{t.mark('fail')} {err['id']} {err['code']}: {err['detail']}")
|
|
259
|
+
if not report["unloaded"] and not report["skipped"] and not report["errors"]:
|
|
260
|
+
out("No library models or active jobs under this state directory")
|
|
261
|
+
if report["ok"]:
|
|
262
|
+
count = len(report["unloaded"])
|
|
263
|
+
out(
|
|
264
|
+
t.paint(
|
|
265
|
+
f"Unloaded {count} active library model(s); downloaded weights remain on disk",
|
|
266
|
+
"green",
|
|
267
|
+
"bold",
|
|
268
|
+
)
|
|
269
|
+
if count
|
|
270
|
+
else t.paint("No active library models were running", "green", "bold")
|
|
271
|
+
)
|
|
272
|
+
return 0
|
|
273
|
+
out(t.paint("Some library models could not be unloaded", "red", "bold"))
|
|
274
|
+
return 1
|
|
@@ -209,6 +209,8 @@ _DRIVER_RE = re.compile(r"\b(?:Driver|KMD)\s+Version\s*:\s*(\d+(?:\.\d+)*)", re.
|
|
|
209
209
|
HOST_LIBRARIES = ("libgomp.so.1",)
|
|
210
210
|
DETAIL_FIELDS = ("compute_cap", "memory.reserved", "display_active") # nvidia-smi names
|
|
211
211
|
_UNLIMITED = 1 << 60 # cgroup v1 reports "no limit" as a page-aligned LONG_MAX
|
|
212
|
+
_PROC_SELF_CGROUP = "/proc/self/cgroup"
|
|
213
|
+
_V1_CPU_CONTROLLERS = ("cpu", "cpu,cpuacct", "cpuacct,cpu")
|
|
212
214
|
|
|
213
215
|
|
|
214
216
|
def _run(
|
|
@@ -579,9 +581,21 @@ def environment(root: str = "/") -> str:
|
|
|
579
581
|
return "bare" if init is not None else "unknown"
|
|
580
582
|
|
|
581
583
|
|
|
584
|
+
def _cgroup_rows(root: str) -> list[list[str]]:
|
|
585
|
+
return [r.split(":", 2) for r in (_text(_at(root, _PROC_SELF_CGROUP)) or "").splitlines()]
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _cgroup_levels(mount: str, path: str) -> list[str]:
|
|
589
|
+
# Without a cgroup namespace the path is the host's, mounted as a container's root: walk up.
|
|
590
|
+
parts = [p for p in path.strip().split("/") if p]
|
|
591
|
+
return [
|
|
592
|
+
d for n in range(len(parts), -1, -1) if os.path.isdir(d := os.path.join(mount, *parts[:n]))
|
|
593
|
+
]
|
|
594
|
+
|
|
595
|
+
|
|
582
596
|
def cgroup_memory(root: str = "/") -> CgroupMemory | None:
|
|
583
597
|
"""Memory ceiling of this process's cgroup (tightest limit-usage headroom across ancestors)."""
|
|
584
|
-
rows =
|
|
598
|
+
rows = _cgroup_rows(root)
|
|
585
599
|
v1 = next((r[2] for r in rows if len(r) == 3 and "memory" in r[1].split(",")), None)
|
|
586
600
|
if v1 is not None:
|
|
587
601
|
spec = ("/sys/fs/cgroup/memory", v1, ("memory.limit_in_bytes", "memory.usage_in_bytes"), 1)
|
|
@@ -593,11 +607,7 @@ def cgroup_memory(root: str = "/") -> CgroupMemory | None:
|
|
|
593
607
|
|
|
594
608
|
|
|
595
609
|
def _tightest(mount: str, path: str, files: tuple[str, str], v: int) -> CgroupMemory:
|
|
596
|
-
|
|
597
|
-
parts = [p for p in path.strip().split("/") if p]
|
|
598
|
-
levels = [
|
|
599
|
-
d for n in range(len(parts), -1, -1) if os.path.isdir(d := os.path.join(mount, *parts[:n]))
|
|
600
|
-
]
|
|
610
|
+
levels = _cgroup_levels(mount, path)
|
|
601
611
|
readable = bool(levels)
|
|
602
612
|
best: tuple[int | None, int | None, int | None] = (None, None, None)
|
|
603
613
|
for level in levels:
|
|
@@ -615,6 +625,87 @@ def _tightest(mount: str, path: str, files: tuple[str, str], v: int) -> CgroupMe
|
|
|
615
625
|
return {"version": v, "limit_bytes": best[1], "usage_bytes": best[2], "readable": readable}
|
|
616
626
|
|
|
617
627
|
|
|
628
|
+
def _tighter_ratio(
|
|
629
|
+
current: tuple[int, int] | None, quota: int, period: int
|
|
630
|
+
) -> tuple[int, int] | None:
|
|
631
|
+
if quota <= 0 or period <= 0:
|
|
632
|
+
return current
|
|
633
|
+
if current is None or quota * current[1] < current[0] * period:
|
|
634
|
+
return (quota, period)
|
|
635
|
+
return current
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _cgroup_v2_cpu_ratio(root: str, path: str) -> tuple[int, int] | None:
|
|
639
|
+
best: tuple[int, int] | None = None
|
|
640
|
+
for level in _cgroup_levels(_at(root, "/sys/fs/cgroup"), path):
|
|
641
|
+
parts = (_text(os.path.join(level, "cpu.max")) or "").split()
|
|
642
|
+
if len(parts) < 2 or parts[0] == "max":
|
|
643
|
+
continue
|
|
644
|
+
try:
|
|
645
|
+
best = _tighter_ratio(best, int(parts[0]), int(parts[1]))
|
|
646
|
+
except ValueError:
|
|
647
|
+
continue
|
|
648
|
+
return best
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _cgroup_v1_cpu_ratio(root: str, controller: str, path: str) -> tuple[int, int] | None:
|
|
652
|
+
mounts = [
|
|
653
|
+
_at(root, f"/sys/fs/cgroup/{name}")
|
|
654
|
+
for name in dict.fromkeys((controller, *_V1_CPU_CONTROLLERS))
|
|
655
|
+
if name in _V1_CPU_CONTROLLERS
|
|
656
|
+
]
|
|
657
|
+
best: tuple[int, int] | None = None
|
|
658
|
+
for mount in mounts:
|
|
659
|
+
if not os.path.isdir(mount):
|
|
660
|
+
continue
|
|
661
|
+
for level in _cgroup_levels(mount, path):
|
|
662
|
+
raw_q = (_text(os.path.join(level, "cpu.cfs_quota_us")) or "").strip()
|
|
663
|
+
raw_p = (_text(os.path.join(level, "cpu.cfs_period_us")) or "").strip()
|
|
664
|
+
if not raw_q or not raw_p:
|
|
665
|
+
continue
|
|
666
|
+
try:
|
|
667
|
+
best = _tighter_ratio(best, int(raw_q), int(raw_p))
|
|
668
|
+
except ValueError:
|
|
669
|
+
continue
|
|
670
|
+
return best
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def cgroup_cpu_quota(root: str = "/") -> int | None:
|
|
674
|
+
"""Effective logical CPU cap from this process's cgroup v1/v2 CPU quota, or None."""
|
|
675
|
+
rows = _cgroup_rows(root)
|
|
676
|
+
best: tuple[int, int] | None = None
|
|
677
|
+
v1 = next(((r[1], r[2]) for r in rows if len(r) == 3 and "cpu" in r[1].split(",")), None)
|
|
678
|
+
if v1 is not None and (ratio := _cgroup_v1_cpu_ratio(root, v1[0], v1[1])) is not None:
|
|
679
|
+
best = _tighter_ratio(best, ratio[0], ratio[1])
|
|
680
|
+
v2 = next((r[2] for r in rows if len(r) == 3 and r[:2] == ["0", ""]), None)
|
|
681
|
+
if v2 is not None and (ratio := _cgroup_v2_cpu_ratio(root, v2)) is not None:
|
|
682
|
+
best = _tighter_ratio(best, ratio[0], ratio[1])
|
|
683
|
+
if best is None:
|
|
684
|
+
return None
|
|
685
|
+
quota, period = best
|
|
686
|
+
return max(1, (quota + period - 1) // period)
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def logical_cores(root: str = "/") -> int | None:
|
|
690
|
+
"""Effective logical CPUs for this process, capped by Linux affinity and cgroup quota."""
|
|
691
|
+
count = os.cpu_count()
|
|
692
|
+
if not sys.platform.startswith("linux"):
|
|
693
|
+
return count
|
|
694
|
+
caps: list[int] = [count] if isinstance(count, int) and count > 0 else []
|
|
695
|
+
getaffinity = getattr(os, "sched_getaffinity", None)
|
|
696
|
+
if callable(getaffinity):
|
|
697
|
+
try:
|
|
698
|
+
affinity = len(getaffinity(0))
|
|
699
|
+
if affinity > 0:
|
|
700
|
+
caps.append(affinity)
|
|
701
|
+
except OSError:
|
|
702
|
+
pass
|
|
703
|
+
quota = cgroup_cpu_quota(root)
|
|
704
|
+
if quota is not None and quota > 0:
|
|
705
|
+
caps.append(quota)
|
|
706
|
+
return min(caps) if caps else count
|
|
707
|
+
|
|
708
|
+
|
|
618
709
|
def parse_field_csv(text: str) -> dict[int, str]:
|
|
619
710
|
"""{index: value} of an ``index,FIELD`` query; [N/A] and [Not Supported] cells left out."""
|
|
620
711
|
rows = csv.reader(text.strip().splitlines(), skipinitialspace=True)
|
|
@@ -733,7 +824,7 @@ def collect(
|
|
|
733
824
|
"libc": " ".join(platform.libc_ver()).strip(),
|
|
734
825
|
},
|
|
735
826
|
"python": platform.python_version(),
|
|
736
|
-
"cpu": {"model": _cpu_model(), "logical_cores":
|
|
827
|
+
"cpu": {"model": _cpu_model(), "logical_cores": logical_cores()},
|
|
737
828
|
"ram": {
|
|
738
829
|
**(metal_probe.ram_status() if sys.platform == "darwin" else {}),
|
|
739
830
|
"total_bytes": ram_total,
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Discovery and private registry of optional ``foundations`` controller roots.
|
|
2
|
+
|
|
3
|
+
``foundations ensure`` records its ``--root`` under ``$LOCALMODELS_STATE/foundations/roots.json``
|
|
4
|
+
so ``stack down --all`` can cleanly stop active controllers without requiring callers to track
|
|
5
|
+
every root separately. Legacy installations that predate this registry are also discovered across
|
|
6
|
+
standard sibling/parent layouts, strictly verified against ``control.json["stateDir"]``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from collections.abc import Sequence
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from localmodels import hosts, service_control, service_upgrade
|
|
18
|
+
|
|
19
|
+
ROOTS_SCHEMA = "localmodels.foundations-roots/v1"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def roots_path(state_dir: Path | None = None) -> Path:
|
|
23
|
+
base = hosts.state_dir() if state_dir is None else state_dir
|
|
24
|
+
return base / "foundations" / "roots.json"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _lock_path(state_dir: Path | None = None) -> Path:
|
|
28
|
+
base = hosts.state_dir() if state_dir is None else state_dir
|
|
29
|
+
return base / "foundations" / ".roots.lock"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _norm_key(path: str | Path) -> str:
|
|
33
|
+
return os.path.normcase(os.path.realpath(os.path.expanduser(str(path))))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _same_path(raw: object, target: Path) -> bool:
|
|
37
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
38
|
+
return False
|
|
39
|
+
return _norm_key(raw) == _norm_key(target)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def read_registered_roots(state_dir: Path | None = None) -> list[Path]:
|
|
43
|
+
"""Read controller roots previously registered under ``state_dir`` (ignores corrupt files)."""
|
|
44
|
+
path = roots_path(state_dir)
|
|
45
|
+
try:
|
|
46
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
47
|
+
except (OSError, ValueError):
|
|
48
|
+
return []
|
|
49
|
+
entries = raw.get("roots") if isinstance(raw, dict) else raw
|
|
50
|
+
if not isinstance(entries, list):
|
|
51
|
+
return []
|
|
52
|
+
found: list[Path] = []
|
|
53
|
+
seen: set[str] = set()
|
|
54
|
+
for item in entries:
|
|
55
|
+
if not isinstance(item, str) or not item.strip():
|
|
56
|
+
continue
|
|
57
|
+
candidate = Path(os.path.expanduser(item))
|
|
58
|
+
if not candidate.is_absolute():
|
|
59
|
+
continue
|
|
60
|
+
key = _norm_key(candidate)
|
|
61
|
+
if key not in seen:
|
|
62
|
+
seen.add(key)
|
|
63
|
+
found.append(candidate)
|
|
64
|
+
return found
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def register_root(state_dir: Path, root: Path) -> None:
|
|
68
|
+
"""Atomically record ``root`` under ``state_dir/foundations/roots.json`` (best-effort)."""
|
|
69
|
+
resolved_root = Path(os.path.abspath(os.path.expanduser(str(root))))
|
|
70
|
+
target_key = _norm_key(resolved_root)
|
|
71
|
+
parent = roots_path(state_dir).parent
|
|
72
|
+
with contextlib.suppress(OSError, ValueError):
|
|
73
|
+
if not parent.exists():
|
|
74
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
if os.name != "nt":
|
|
76
|
+
parent.chmod(0o700)
|
|
77
|
+
with hosts.file_lock(_lock_path(state_dir)):
|
|
78
|
+
existing = read_registered_roots(state_dir)
|
|
79
|
+
if any(_norm_key(entry) == target_key for entry in existing):
|
|
80
|
+
return
|
|
81
|
+
updated = [str(entry) for entry in existing] + [str(resolved_root)]
|
|
82
|
+
hosts.save_private(
|
|
83
|
+
roots_path(state_dir),
|
|
84
|
+
{"schema": ROOTS_SCHEMA, "roots": updated},
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _legacy_candidates(state_dir: Path) -> list[Path]:
|
|
89
|
+
"""Well-known controller root locations relative to ``state_dir`` for pre-registry installs."""
|
|
90
|
+
resolved = Path(os.path.abspath(os.path.expanduser(str(state_dir))))
|
|
91
|
+
candidates: list[Path] = [
|
|
92
|
+
resolved / "foundations",
|
|
93
|
+
resolved.parent,
|
|
94
|
+
resolved.parent / "model-services",
|
|
95
|
+
]
|
|
96
|
+
if resolved.parent.parent != resolved.parent:
|
|
97
|
+
candidates.append(resolved.parent.parent / "model-services")
|
|
98
|
+
return candidates
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _matches_state_dir(candidate: Path, state_dir: Path, *, registered: bool) -> bool:
|
|
102
|
+
if candidate.is_symlink():
|
|
103
|
+
return False
|
|
104
|
+
control_path = candidate / "control.json"
|
|
105
|
+
if not control_path.is_file() or control_path.is_symlink():
|
|
106
|
+
return False
|
|
107
|
+
try:
|
|
108
|
+
config = service_control.read_configuration(candidate)
|
|
109
|
+
except (OSError, ValueError):
|
|
110
|
+
if not registered:
|
|
111
|
+
return False
|
|
112
|
+
lock_path = candidate / "worker.lock"
|
|
113
|
+
if not lock_path.exists() or lock_path.is_symlink():
|
|
114
|
+
return False
|
|
115
|
+
try:
|
|
116
|
+
return not service_upgrade.idle(candidate)
|
|
117
|
+
except OSError:
|
|
118
|
+
return False
|
|
119
|
+
return _same_path(config.get("stateDir"), state_dir)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def discover_roots(
|
|
123
|
+
state_dir: Path | None = None,
|
|
124
|
+
explicit: Sequence[Path] = (),
|
|
125
|
+
) -> list[tuple[Path, bool]]:
|
|
126
|
+
"""Return deduplicated ``(root, is_explicit)`` controller roots belonging to ``state_dir``."""
|
|
127
|
+
base = hosts.state_dir() if state_dir is None else state_dir
|
|
128
|
+
found: list[tuple[Path, bool]] = []
|
|
129
|
+
seen: set[str] = set()
|
|
130
|
+
|
|
131
|
+
for raw in explicit:
|
|
132
|
+
candidate = Path(os.path.abspath(os.path.expanduser(str(raw))))
|
|
133
|
+
key = _norm_key(candidate)
|
|
134
|
+
if key not in seen:
|
|
135
|
+
seen.add(key)
|
|
136
|
+
found.append((candidate, True))
|
|
137
|
+
|
|
138
|
+
registered = read_registered_roots(base)
|
|
139
|
+
registered_keys = {_norm_key(entry) for entry in registered}
|
|
140
|
+
for candidate in [*registered, *_legacy_candidates(base)]:
|
|
141
|
+
key = _norm_key(candidate)
|
|
142
|
+
if key in seen:
|
|
143
|
+
continue
|
|
144
|
+
if _matches_state_dir(candidate, base, registered=key in registered_keys):
|
|
145
|
+
seen.add(key)
|
|
146
|
+
found.append((candidate, False))
|
|
147
|
+
|
|
148
|
+
return found
|
|
@@ -22,8 +22,17 @@ import urllib.error
|
|
|
22
22
|
import urllib.request
|
|
23
23
|
from collections.abc import Callable
|
|
24
24
|
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
25
26
|
|
|
26
|
-
from localmodels import
|
|
27
|
+
from localmodels import (
|
|
28
|
+
process_identity,
|
|
29
|
+
process_windows,
|
|
30
|
+
runtime_io,
|
|
31
|
+
service_autostart,
|
|
32
|
+
service_control,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
STOP_SCHEMA = "localmodels.service-controller-stop/v1"
|
|
27
36
|
|
|
28
37
|
GRACE = 15.0 # an install in progress finishes its current step before the worker exits
|
|
29
38
|
KILL_AFTER = 10.0 # after SIGTERM, before SIGKILL
|
|
@@ -426,3 +435,39 @@ def retire_implicit_jobs(root: Path) -> None:
|
|
|
426
435
|
CHANGED, "another model controller took the lock during the upgrade"
|
|
427
436
|
) from None
|
|
428
437
|
raise
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def stop_controller(root: Path) -> dict[str, Any]:
|
|
441
|
+
"""End this root's controller and its autostart, for an uninstaller or full shutdown.
|
|
442
|
+
|
|
443
|
+
Idempotent: nothing under ``root``, or nothing running, is a successful stop.
|
|
444
|
+
"""
|
|
445
|
+
result: dict[str, Any] = {
|
|
446
|
+
"schema": STOP_SCHEMA,
|
|
447
|
+
"root": str(root),
|
|
448
|
+
"stopped": False,
|
|
449
|
+
"method": None,
|
|
450
|
+
"autostart": "none",
|
|
451
|
+
}
|
|
452
|
+
if not (root / "control.json").is_file():
|
|
453
|
+
return result
|
|
454
|
+
try:
|
|
455
|
+
_stop_controller(root, result)
|
|
456
|
+
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
|
457
|
+
result.update(ok=False, stopped=False, error=str(error))
|
|
458
|
+
if isinstance(error, ControllerError):
|
|
459
|
+
result["code"] = error.code
|
|
460
|
+
return result
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _stop_controller(root: Path, result: dict[str, Any]) -> None:
|
|
464
|
+
with runtime_io.private_lock(root / "ensure.lock"):
|
|
465
|
+
config = service_control.read_configuration(root)
|
|
466
|
+
config["stopped"] = True
|
|
467
|
+
runtime_io.write_private_json(root / "control.json", config)
|
|
468
|
+
running = not idle(root)
|
|
469
|
+
result["autostart"] = service_autostart.unregister(root)
|
|
470
|
+
if not running and idle(root):
|
|
471
|
+
return
|
|
472
|
+
result["stopped"] = True
|
|
473
|
+
result["method"] = end_controller(root) or "systemd"
|
|
@@ -19,7 +19,7 @@ from localmodels.service_control import controller_available as controller_avail
|
|
|
19
19
|
from localmodels.service_control import read_configuration as read_configuration
|
|
20
20
|
from localmodels.service_jobs import ACTIVE, ROLES, selected_roles
|
|
21
21
|
|
|
22
|
-
STOP_SCHEMA =
|
|
22
|
+
STOP_SCHEMA = service_upgrade.STOP_SCHEMA
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
def stop(root: Path) -> dict[str, Any]:
|
|
@@ -27,35 +27,14 @@ def stop(root: Path) -> dict[str, Any]:
|
|
|
27
27
|
|
|
28
28
|
Idempotent: nothing under ``root``, or nothing running, is a successful stop.
|
|
29
29
|
"""
|
|
30
|
-
|
|
31
|
-
"schema": STOP_SCHEMA,
|
|
32
|
-
"root": str(root),
|
|
33
|
-
"stopped": False,
|
|
34
|
-
"method": None,
|
|
35
|
-
"autostart": "none",
|
|
36
|
-
}
|
|
37
|
-
if not (root / "control.json").is_file():
|
|
38
|
-
return result
|
|
39
|
-
try:
|
|
40
|
-
_stop(root, result)
|
|
41
|
-
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
|
42
|
-
result.update(ok=False, stopped=False, error=str(error))
|
|
43
|
-
if isinstance(error, service_upgrade.ControllerError):
|
|
44
|
-
result["code"] = error.code
|
|
45
|
-
return result
|
|
30
|
+
return service_upgrade.stop_controller(root)
|
|
46
31
|
|
|
47
32
|
|
|
48
|
-
def
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
running = not service_upgrade.idle(root)
|
|
54
|
-
result["autostart"] = service_autostart.unregister(root)
|
|
55
|
-
if not running and service_upgrade.idle(root):
|
|
56
|
-
return
|
|
57
|
-
result["stopped"] = True
|
|
58
|
-
result["method"] = service_upgrade.end_controller(root) or "systemd"
|
|
33
|
+
def _register_controller_root(config: dict[str, Any], root: Path) -> None:
|
|
34
|
+
if isinstance(state_dir := config.get("stateDir"), str) and state_dir:
|
|
35
|
+
from localmodels import service_roots
|
|
36
|
+
|
|
37
|
+
service_roots.register_root(Path(state_dir), root)
|
|
59
38
|
|
|
60
39
|
|
|
61
40
|
def ensure(
|
|
@@ -132,6 +111,7 @@ def ensure(
|
|
|
132
111
|
runtime_io.write_private_json(config_path, config)
|
|
133
112
|
config.pop("stopped", None)
|
|
134
113
|
runtime_io.write_private_json(config_path, config)
|
|
114
|
+
_register_controller_root(config, root)
|
|
135
115
|
runtime_io.private_permissions(key_path)
|
|
136
116
|
key = json.loads(key_path.read_text())
|
|
137
117
|
if os.name != "nt":
|