@simplexai/localmodels-linux-x64 0.1.0-dev.35 → 0.1.0-dev.37
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 +124 -102
- package/kit.py +1 -0
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +9 -3
- package/modules/localmodels/bifrost_config.py +188 -0
- package/modules/localmodels/budget.py +15 -2
- package/modules/localmodels/catalog.json +235 -2
- package/modules/localmodels/catalog.py +51 -320
- package/modules/localmodels/catalog_add.py +2 -8
- package/modules/localmodels/catalog_recipes.py +321 -0
- package/modules/localmodels/cli_parser.py +4 -1
- package/modules/localmodels/console.py +5 -4
- package/modules/localmodels/contracts.py +13 -3
- package/modules/localmodels/debug_cli.py +158 -0
- package/modules/localmodels/debug_mode.py +727 -0
- package/modules/localmodels/debug_stub_server.py +192 -0
- package/modules/localmodels/decode_calibration.json +1 -1
- package/modules/localmodels/decode_calibration.py +34 -17
- package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
- package/modules/localmodels/gateway.py +21 -155
- package/modules/localmodels/gateway_accept.py +201 -0
- package/modules/localmodels/gateway_bifrost.py +19 -184
- package/modules/localmodels/gateway_cli.py +11 -4
- package/modules/localmodels/gateway_foundations.py +2 -4
- package/modules/localmodels/gateway_probe.py +0 -1
- package/modules/localmodels/gateway_server.py +2 -3
- package/modules/localmodels/gpu_specs.py +12 -0
- package/modules/localmodels/guard.py +2 -7
- package/modules/localmodels/harness.py +16 -129
- package/modules/localmodels/harness_cleanup.py +135 -0
- package/modules/localmodels/harness_gateway.py +16 -14
- package/modules/localmodels/harness_probe.py +12 -4
- package/modules/localmodels/hosts.py +25 -2
- package/modules/localmodels/http_local.py +59 -0
- package/modules/localmodels/install.py +23 -8
- package/modules/localmodels/library_gateway.py +9 -9
- package/modules/localmodels/library_jobs.py +76 -27
- package/modules/localmodels/library_serve.py +12 -1
- package/modules/localmodels/library_state.py +6 -1
- package/modules/localmodels/llm_rank.py +155 -7
- package/modules/localmodels/metal_probe.py +11 -7
- package/modules/localmodels/probe.py +108 -174
- package/modules/localmodels/process_identity.py +109 -154
- package/modules/localmodels/process_windows.py +86 -0
- package/modules/localmodels/recommend.py +32 -3
- package/modules/localmodels/recommend_cli.py +14 -6
- package/modules/localmodels/remote_ops.py +65 -0
- package/modules/localmodels/remote_ops_download.py +2 -2
- package/modules/localmodels/remote_ops_prepare.py +19 -0
- package/modules/localmodels/remote_ops_service.py +14 -2
- package/modules/localmodels/runtime_args.py +10 -3
- package/modules/localmodels/runtime_auth.py +5 -9
- package/modules/localmodels/runtime_cli.py +128 -129
- package/modules/localmodels/runtime_discovery.py +84 -0
- package/modules/localmodels/runtime_install.py +101 -0
- package/modules/localmodels/runtime_releases.py +302 -0
- package/modules/localmodels/service_stop.py +8 -108
- package/modules/localmodels/service_upgrade.py +394 -63
- package/modules/localmodels/services_cli.py +24 -14
- package/modules/localmodels/setup_inspection.py +97 -9
- package/modules/localmodels/setup_text.py +7 -0
- package/modules/localmodels/sizecalc.py +0 -1
- package/modules/localmodels/stack.py +14 -221
- package/modules/localmodels/stack_arena.py +732 -0
- package/modules/localmodels/stack_args.py +15 -9
- package/modules/localmodels/stack_auto.py +384 -3
- package/modules/localmodels/stack_aux_gpu.py +4 -3
- package/modules/localmodels/stack_capacity.py +138 -0
- package/modules/localmodels/stack_cleanup.py +9 -4
- package/modules/localmodels/stack_cli.py +286 -0
- package/modules/localmodels/stack_compose.py +76 -32
- package/modules/localmodels/stack_console.py +9 -6
- package/modules/localmodels/stack_hardware.py +96 -270
- package/modules/localmodels/stack_hardware_text.py +263 -0
- package/modules/localmodels/stack_journal.py +3 -9
- package/modules/localmodels/stack_ledger.py +48 -18
- package/modules/localmodels/stack_lifecycle.py +33 -312
- package/modules/localmodels/stack_mcp.py +729 -0
- package/modules/localmodels/stack_memory.py +0 -2
- package/modules/localmodels/stack_picks.py +73 -18
- package/modules/localmodels/stack_plan.py +23 -5
- package/modules/localmodels/stack_preflight.py +11 -19
- package/modules/localmodels/stack_remove.py +373 -0
- package/modules/localmodels/stack_route.py +101 -17
- package/modules/localmodels/stack_suite.py +16 -10
- package/modules/localmodels/stack_summary.py +14 -0
- package/modules/localmodels/stack_try.py +238 -24
- package/modules/localmodels/stack_try_client.py +53 -15
- package/modules/localmodels/stack_try_docs.py +2 -2
- package/modules/localmodels/stack_view.py +24 -171
- package/modules/localmodels/stack_view_access.py +114 -1
- package/modules/localmodels/stack_view_agent.py +3 -13
- package/modules/localmodels/stack_view_hub.py +9 -10
- package/modules/localmodels/stack_view_llm.py +1 -1
- package/modules/localmodels/stack_view_sandbox.py +2 -2
- package/modules/localmodels/stack_view_schema.py +183 -0
- package/modules/localmodels/stack_view_serve.py +7 -1
- package/modules/localmodels/stack_view_service.py +1 -2
- package/modules/localmodels/stack_view_text.py +13 -9
- package/modules/localmodels/stack_warm.py +3 -0
- package/modules/localmodels/stack_warm_store.py +517 -0
- package/modules/localmodels/tui.py +28 -4
- package/modules/localmodels/tui_dialogs.py +136 -0
- package/modules/localmodels/tui_modals.py +279 -0
- package/modules/localmodels/tui_screen.py +113 -154
- package/modules/localmodels/tui_views.py +134 -203
- package/modules/localmodels/web/index.html +510 -101
- package/modules/localmodels/web/sizecalc/app.js +363 -10
- package/modules/localmodels/web/sizecalc/page.html +27 -3
- package/modules/localmodels/web/view/fleet.html +11 -2
- package/modules/localmodels/web/view/fleet.js +191 -17
- package/modules/localmodels/web/view/i18n.js +3 -2
- package/modules/localmodels/web/view/index.html +1 -1
- package/modules/localmodels/web/view/nav.js +22 -3
- package/modules/localmodels/web/view/view.css +63 -18
- package/modules/localmodels/web/view/view.js +169 -32
- package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +120 -98
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
- /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -49,8 +49,6 @@ GIB, MIB = 1 << 30, 1 << 20
|
|
|
49
49
|
DEFAULT_CONTEXTS = (65536, 131072, 262144)
|
|
50
50
|
MAX_SLOTS = 64 # the largest concurrency max_slots searches
|
|
51
51
|
MAX_CONTEXT = 1 << 24 # the longest per-slot context max_context searches
|
|
52
|
-
DEVICE_PARTS = ("weights", "kv", "state", "compute", "draft", "process", "vision")
|
|
53
|
-
HOST_PARTS = ("embedding", "process", "checkpoints", "prompt_cache", "vision")
|
|
54
52
|
|
|
55
53
|
|
|
56
54
|
@dataclass(frozen=True)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""The two LLMs ``stack`` offers for one computer: the smartest that fits, and the fastest.
|
|
2
2
|
|
|
3
|
-
Both come from the per-card lists ``stack hardware`` prints (stack_hardware.llm_fits):
|
|
3
|
+
Both come from the per-card lists ``stack hardware`` prints (stack_hardware.llm_fits): eligible
|
|
4
4
|
models that pass the agent gate on a card ``--llm auto`` may take, so nothing here prices or
|
|
5
5
|
probes again. ``smartest`` is what ``--prefer smartest`` (the default) installs. ``fastest`` is
|
|
6
6
|
what ``--prefer fastest`` installs: the highest decode speed that fits, whatever its score. One
|
|
@@ -17,22 +17,26 @@ from collections.abc import Sequence
|
|
|
17
17
|
from typing import TypedDict
|
|
18
18
|
|
|
19
19
|
from localmodels import catalog as cat
|
|
20
|
-
from localmodels import llm_rank
|
|
20
|
+
from localmodels import catalog_recipes, llm_rank
|
|
21
21
|
|
|
22
22
|
# A second choice has to be worth offering: at least this much faster than the smartest.
|
|
23
23
|
WORTH_FASTER = 1.2
|
|
24
24
|
ROLES = ("smartest", "fastest")
|
|
25
25
|
|
|
26
26
|
|
|
27
|
-
class
|
|
28
|
-
|
|
27
|
+
class _FitPolicy(TypedDict, total=False):
|
|
28
|
+
candidate_fallback: bool
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Fit(_FitPolicy):
|
|
32
|
+
"""An automatic LLM fit on one card; candidate_fallback never competes with a primary.
|
|
29
33
|
stack_plan names it LlmFit."""
|
|
30
34
|
|
|
31
35
|
id: str
|
|
32
36
|
quant: str
|
|
33
37
|
quality: int
|
|
34
|
-
decode_tok_s: float # calibrated estimate,
|
|
35
|
-
decode_basis: str # a catalog.DECODE_BASES key
|
|
38
|
+
decode_tok_s: float | None # calibrated estimate, same-device measurement, or None (Strata)
|
|
39
|
+
decode_basis: str # a catalog.DECODE_BASES key, or "unavailable"
|
|
36
40
|
|
|
37
41
|
|
|
38
42
|
class Pick(Fit):
|
|
@@ -57,7 +61,7 @@ def picks(cards: Sequence[CardFits], default: str | None = None) -> list[Pick]:
|
|
|
57
61
|
model counts on the first card that holds it, in the order ``--llm auto`` tries cards (most
|
|
58
62
|
free memory first); ``default`` is the small-Mac default (llm_rank.mac_default). When every
|
|
59
63
|
card that holds a model runs another program's service (a shared Mac's one GPU), the picks
|
|
60
|
-
are what sharing it would install and say so. Empty when nothing
|
|
64
|
+
are what sharing it would install and say so. Empty when nothing eligible fits."""
|
|
61
65
|
free = [c for c in cards if c["auto"] and c["llm"]]
|
|
62
66
|
found: dict[str, Pick] = {}
|
|
63
67
|
for card in sorted(free or cards, key=lambda c: (-c["free_bytes"], c["index"])):
|
|
@@ -65,15 +69,46 @@ def picks(cards: Sequence[CardFits], default: str | None = None) -> list[Pick]:
|
|
|
65
69
|
found.setdefault(
|
|
66
70
|
fit["id"], {**fit, "role": "", "card": card["index"], "shared": not free}
|
|
67
71
|
)
|
|
68
|
-
|
|
72
|
+
strata_ids = {
|
|
73
|
+
c["id"] for c in catalog_recipes.components() if c["runtime"] in ("strata", "strata-poly")
|
|
74
|
+
}
|
|
75
|
+
llama_scores = [
|
|
76
|
+
p["quality"]
|
|
77
|
+
for p in found.values()
|
|
78
|
+
if p["decode_tok_s"] is not None
|
|
79
|
+
and p["id"] not in strata_ids
|
|
80
|
+
and not p.get("candidate_fallback")
|
|
81
|
+
]
|
|
82
|
+
bar = llm_rank.strata_bar(max(llama_scores, default=-1), {})
|
|
83
|
+
eligible = [
|
|
84
|
+
p
|
|
85
|
+
for p in found.values()
|
|
86
|
+
if (p["decode_tok_s"] is not None and p["id"] not in strata_ids) or p["quality"] >= bar
|
|
87
|
+
]
|
|
88
|
+
if not eligible:
|
|
69
89
|
return []
|
|
70
|
-
ranked = [
|
|
71
|
-
|
|
72
|
-
|
|
90
|
+
ranked = [
|
|
91
|
+
(
|
|
92
|
+
(p["quality"], -1.0 if p["decode_tok_s"] is None else p["decode_tok_s"]),
|
|
93
|
+
p["id"],
|
|
94
|
+
p["card"],
|
|
95
|
+
)
|
|
96
|
+
for p in eligible
|
|
97
|
+
]
|
|
98
|
+
fallback_ids = {p["id"] for p in eligible if p.get("candidate_fallback")}
|
|
99
|
+
smartest = found[llm_rank.choose(ranked, "smartest", default, fallback_ids=fallback_ids)[0]]
|
|
100
|
+
llama_ranked = [row for row in ranked if row[1] not in strata_ids]
|
|
101
|
+
fastest = (
|
|
102
|
+
found[llm_rank.choose(llama_ranked, "fastest", fallback_ids=fallback_ids)[0]]
|
|
103
|
+
if llama_ranked
|
|
104
|
+
else smartest
|
|
105
|
+
)
|
|
73
106
|
offered: list[Pick] = [{**smartest, "role": "smartest"}]
|
|
107
|
+
fast_speed, smart_speed = fastest["decode_tok_s"], smartest["decode_tok_s"]
|
|
74
108
|
if (
|
|
75
109
|
fastest["id"] != smartest["id"]
|
|
76
|
-
and
|
|
110
|
+
and fast_speed is not None
|
|
111
|
+
and (smart_speed is None or fast_speed >= smart_speed * WORTH_FASTER)
|
|
77
112
|
):
|
|
78
113
|
offered.append({**fastest, "role": "fastest"})
|
|
79
114
|
return offered
|
|
@@ -89,12 +124,17 @@ def second(offered: list[Pick], chosen: str) -> Pick | None:
|
|
|
89
124
|
return next((p for p in offered if p["role"] == "fastest"), None)
|
|
90
125
|
|
|
91
126
|
|
|
92
|
-
def label(pick:
|
|
127
|
+
def label(pick: Fit) -> str:
|
|
93
128
|
"""One pick in a line: model, score, speed and what the speed rests on."""
|
|
94
129
|
score = f"score {pick['quality']}" if pick["quality"] else "no SimplexAI score"
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
130
|
+
tok_s = pick["decode_tok_s"]
|
|
131
|
+
if tok_s is None:
|
|
132
|
+
speed = "speed unavailable"
|
|
133
|
+
else:
|
|
134
|
+
measured = pick["decode_basis"] == "measured-decode"
|
|
135
|
+
speed = f"{tok_s:.0f} tok/s " + ("measured" if measured else "estimated")
|
|
136
|
+
candidate = " · candidate product fallback" if pick.get("candidate_fallback") else ""
|
|
137
|
+
return f"{pick['id']} {pick['quant']} · {score} · {speed}{candidate}"
|
|
98
138
|
|
|
99
139
|
|
|
100
140
|
def lines(offered: list[Pick], command: str | None) -> list[str]:
|
|
@@ -118,13 +158,28 @@ def lines(offered: list[Pick], command: str | None) -> list[str]:
|
|
|
118
158
|
" the card runs another program's service: once sharing it is "
|
|
119
159
|
"confirmed, add --share-gpu (with --gpu N on an NVIDIA card)"
|
|
120
160
|
)
|
|
121
|
-
if any(p
|
|
122
|
-
|
|
161
|
+
if any(p.get("candidate_fallback") for p in offered):
|
|
162
|
+
out.append(f" {llm_rank.WINDOWS_FALLBACK_WARNING}")
|
|
163
|
+
bases = sorted(
|
|
164
|
+
{
|
|
165
|
+
p["decode_basis"]
|
|
166
|
+
for p in offered
|
|
167
|
+
if p["decode_tok_s"] is not None
|
|
168
|
+
and p["decode_basis"] != "measured-decode"
|
|
169
|
+
and p["decode_basis"] in cat.DECODE_BASES
|
|
170
|
+
}
|
|
171
|
+
)
|
|
172
|
+
if bases:
|
|
123
173
|
out.append(
|
|
124
174
|
" estimated speeds come from "
|
|
125
175
|
+ "; ".join(cat.DECODE_BASES[b] for b in bases)
|
|
126
176
|
+ ", without speculative decoding; stack warm measures the installed one"
|
|
127
177
|
)
|
|
178
|
+
if any(p["decode_tok_s"] is None for p in offered):
|
|
179
|
+
out.append(
|
|
180
|
+
" Strata/PolyStrata decode speed is not estimated; "
|
|
181
|
+
"stack warm measures the installed one"
|
|
182
|
+
)
|
|
128
183
|
return out
|
|
129
184
|
|
|
130
185
|
|
|
@@ -13,6 +13,8 @@ from pathlib import Path
|
|
|
13
13
|
from typing import Literal, TypedDict, cast
|
|
14
14
|
|
|
15
15
|
from localmodels import approval, deploy, gateway, harness, hosts, preparation, reuse, vision
|
|
16
|
+
from localmodels.budget import HARNESS_RAM as HARNESS_RAM
|
|
17
|
+
from localmodels.budget import RAM_FLOOR as RAM_FLOOR
|
|
16
18
|
from localmodels.budget import gib
|
|
17
19
|
from localmodels.gateway_bifrost import FAST_PROVIDER
|
|
18
20
|
from localmodels.plan_envelope import PlanError, resolved_name
|
|
@@ -23,9 +25,8 @@ from localmodels.stack_picks import Fit, Pick
|
|
|
23
25
|
|
|
24
26
|
SCHEMA = "localmodels.stack-plan/v1"
|
|
25
27
|
GIB = 1 << 30
|
|
26
|
-
RAM_FLOOR = 4 * GIB # the baseline's host MemAvailable floor
|
|
27
28
|
# A Mac's floor beside the stack (2026-11-09 user decision, from MLO1's recommendation): the
|
|
28
|
-
# memory "available" there
|
|
29
|
+
# memory "available" there counts free + inactive + speculative pages, and macOS reclaims beyond
|
|
29
30
|
# it, so Linux's 4 GiB floor held back a second margin. A 24 GiB Mac ran Ling 128K and 64K with
|
|
30
31
|
# pi for 20+ minutes from 8.4–8.9 GB available, pressure 1 and no swap growth, where the 4 GiB
|
|
31
32
|
# floor refused it (evidence/2026-11-05-mac-llm-only-tiers/REPORT.md). The live gates stay: a
|
|
@@ -37,7 +38,6 @@ METAL_RAM_FLOOR = 1 * GIB
|
|
|
37
38
|
# so a reply that would think without end (14,000 tokens of thinking, no answer, on local-119
|
|
38
39
|
# 2026-11-05) closes its thinking and answers. `--reasoning-budget` overrides it, 0 removes it.
|
|
39
40
|
REASONING_BUDGET = 8192
|
|
40
|
-
HARNESS_RAM = 1 * GIB # the gateway (Bifrost or Magpie) plus one client session (estimate)
|
|
41
41
|
FRONT_ENV_BYTES = 200 << 20 # a decision front's environment: 110 MB source archive plus wheels
|
|
42
42
|
|
|
43
43
|
|
|
@@ -189,11 +189,29 @@ class DecisionOption(TypedDict):
|
|
|
189
189
|
commercial_use: bool
|
|
190
190
|
|
|
191
191
|
|
|
192
|
-
LlmFit = Fit
|
|
192
|
+
LlmFit = Fit
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class CapacityFit(TypedDict):
|
|
196
|
+
"""GPU-only reference; never permission to install or new validation evidence."""
|
|
197
|
+
|
|
198
|
+
id: str
|
|
199
|
+
quant: str
|
|
200
|
+
status: str
|
|
201
|
+
validated_on: list[str]
|
|
202
|
+
admission: str
|
|
203
|
+
fits_now: bool
|
|
204
|
+
fits_total: bool
|
|
205
|
+
window: int
|
|
206
|
+
slots: int
|
|
207
|
+
vision: str
|
|
208
|
+
kv_types: list[str]
|
|
209
|
+
needed_free_bytes: int
|
|
193
210
|
|
|
194
211
|
|
|
195
212
|
class _CardSince20261028(TypedDict, total=False):
|
|
196
213
|
uuid: str # added after hardware snapshots were introduced
|
|
214
|
+
capacity: list[CapacityFit] # inspection only; absent from saved plan snapshots
|
|
197
215
|
|
|
198
216
|
|
|
199
217
|
class Card(_CardSince20261028):
|
|
@@ -412,7 +430,7 @@ def default_options() -> StackOptions:
|
|
|
412
430
|
"offline": False,
|
|
413
431
|
"slots": 2,
|
|
414
432
|
"tts": False,
|
|
415
|
-
"search":
|
|
433
|
+
"search": False,
|
|
416
434
|
"reasoning_budget": REASONING_BUDGET,
|
|
417
435
|
"gateway": default_gateway(),
|
|
418
436
|
"vision": vision.DEFAULT,
|
|
@@ -631,27 +631,19 @@ def _running(plan: StackPlan) -> list[Finding]:
|
|
|
631
631
|
|
|
632
632
|
|
|
633
633
|
def _apply_lock() -> list[Finding]:
|
|
634
|
-
path = hosts.stacks_dir() / ".apply.lock"
|
|
635
|
-
if not path.exists():
|
|
636
|
-
return [finding("preflight.apply", "pass", "no other stack apply is running")]
|
|
637
634
|
try:
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
with path.open("a") as lock:
|
|
641
|
-
try:
|
|
642
|
-
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
643
|
-
except BlockingIOError:
|
|
644
|
-
return [
|
|
645
|
-
finding(
|
|
646
|
-
"preflight.apply",
|
|
647
|
-
"warn",
|
|
648
|
-
"another stack apply is running; its services and memory are changing",
|
|
649
|
-
"wait for it to finish, then run stack plan again",
|
|
650
|
-
)
|
|
651
|
-
]
|
|
652
|
-
fcntl.flock(lock, fcntl.LOCK_UN)
|
|
653
|
-
except (OSError, ImportError):
|
|
635
|
+
running = hosts.stack_apply_running()
|
|
636
|
+
except OSError:
|
|
654
637
|
return []
|
|
638
|
+
if running:
|
|
639
|
+
return [
|
|
640
|
+
finding(
|
|
641
|
+
"preflight.apply",
|
|
642
|
+
"warn",
|
|
643
|
+
"another stack apply is running; its services and memory are changing",
|
|
644
|
+
"wait for it to finish, then run stack plan again",
|
|
645
|
+
)
|
|
646
|
+
]
|
|
655
647
|
return [finding("preflight.apply", "pass", "no other stack apply is running")]
|
|
656
648
|
|
|
657
649
|
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""Dependency-ordered uninstall, purge confirmation and orphan adoption helpers for stack remove."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from localmodels import (
|
|
11
|
+
deploy,
|
|
12
|
+
gateway,
|
|
13
|
+
gateway_probe,
|
|
14
|
+
harness,
|
|
15
|
+
harness_gateway,
|
|
16
|
+
hosts,
|
|
17
|
+
stack_cleanup,
|
|
18
|
+
)
|
|
19
|
+
from localmodels.budget import gib
|
|
20
|
+
from localmodels.contracts import decode
|
|
21
|
+
from localmodels.records import FinishedRecord, Plan
|
|
22
|
+
from localmodels.remote_ops import RemoveParams, StrataPreparation
|
|
23
|
+
from localmodels.stack_plan import StackError, command, platform_error
|
|
24
|
+
from localmodels.transport import Executor
|
|
25
|
+
|
|
26
|
+
CONFIRM_WORD = "purge"
|
|
27
|
+
UNIT_DIR = harness.UNIT_DIR
|
|
28
|
+
|
|
29
|
+
Out = Callable[[str], None]
|
|
30
|
+
Listing = stack_cleanup.Listing
|
|
31
|
+
Confirm = Callable[[str], bool]
|
|
32
|
+
ActFn = Callable[[Executor, RemoveParams], dict[str, object]]
|
|
33
|
+
RemoveServicesFn = Callable[
|
|
34
|
+
[
|
|
35
|
+
Executor,
|
|
36
|
+
dict[str, hosts.OwnedDeployment],
|
|
37
|
+
dict[str, RemoveParams],
|
|
38
|
+
bool,
|
|
39
|
+
list[gateway.Check],
|
|
40
|
+
],
|
|
41
|
+
list[gateway.Check],
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _params(name: str, kind: str, deploy_dir: str, port: int) -> RemoveParams:
|
|
46
|
+
return {
|
|
47
|
+
"deploy_dir": deploy_dir,
|
|
48
|
+
"service": name,
|
|
49
|
+
"service_kind": kind,
|
|
50
|
+
"port": port,
|
|
51
|
+
"api_key": "",
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def plan_params(plan: Plan) -> RemoveParams:
|
|
56
|
+
svc = plan["service"]
|
|
57
|
+
params = _params(svc["name"], svc["kind"], svc["deploy_dir"], svc["port"])
|
|
58
|
+
params["config_files"] = list(svc.get("config_files") or {})
|
|
59
|
+
if raw := plan["launch"].get("preparation"):
|
|
60
|
+
params["preparation_dir"] = decode(raw, StrataPreparation)["model_dir"]
|
|
61
|
+
return params
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def owned_params(name: str, entry: hosts.OwnedDeployment) -> RemoveParams:
|
|
65
|
+
"""From the manifest; the deployment's record, when there is one, names its config files."""
|
|
66
|
+
params = _params(entry["service"], entry["kind"], entry["deploy_dir"], entry["port"])
|
|
67
|
+
try:
|
|
68
|
+
params = {**plan_params(hosts.record(hosts.LOCAL_ID, name)["plan"]), **params}
|
|
69
|
+
except KeyError:
|
|
70
|
+
pass
|
|
71
|
+
if entry.get("preparation_dir"):
|
|
72
|
+
params["preparation_dir"] = entry["preparation_dir"]
|
|
73
|
+
return params
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def plan_purge(params: RemoveParams, files: list[str], keep: set[str]) -> None:
|
|
77
|
+
"""List removable model files; shared inputs also keep their preparation workspace."""
|
|
78
|
+
expanded = [os.path.expanduser(f) for f in files]
|
|
79
|
+
if any(f in keep for f in expanded):
|
|
80
|
+
params.pop("preparation_dir", None)
|
|
81
|
+
kept = (".sha256", ".part", ".part.ranges") # .part.ranges: a parallel download's record
|
|
82
|
+
params["purge_files"] = [
|
|
83
|
+
p for f in expanded if f not in keep for p in (f, *(f + k for k in kept))
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def in_use(records: list[FinishedRecord], skip: set[str]) -> set[str]:
|
|
88
|
+
return {
|
|
89
|
+
os.path.expanduser(f["dest"])
|
|
90
|
+
for r in records
|
|
91
|
+
if r["plan"]["name"] not in skip
|
|
92
|
+
for f in r["plan"]["files"]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def listing(event: dict[str, object]) -> Listing:
|
|
97
|
+
if event.get("event") != "result":
|
|
98
|
+
raise OSError(str(event.get("message") or "cannot list the files to delete"))
|
|
99
|
+
rows = decode(event.get("files", []), list[list[object]])
|
|
100
|
+
return [(str(r[0]), int(str(r[1])), int(str(r[2]))) for r in rows]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def ask(prompt: str) -> bool:
|
|
104
|
+
if not sys.stdin.isatty():
|
|
105
|
+
return False
|
|
106
|
+
return input(prompt).strip() == CONFIRM_WORD
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def approve(found: Listing, yes: bool, out: Out, confirm: Confirm) -> bool:
|
|
110
|
+
"""Show every file a purge deletes and its total; go on only with --yes or the word."""
|
|
111
|
+
total = sum(size for _, size, _ in found)
|
|
112
|
+
out(f"--purge will delete these {len(found)} files, {gib(total)} ({total} bytes):")
|
|
113
|
+
for path, size, links in found:
|
|
114
|
+
shared = ", hard link, deleting it frees no space" if links > 1 else ""
|
|
115
|
+
out(f" {path} ({size} bytes{shared})")
|
|
116
|
+
if yes or confirm(f"Type {CONFIRM_WORD} to delete (anything else cancels): "):
|
|
117
|
+
return True
|
|
118
|
+
out(f"Nothing deleted: type {CONFIRM_WORD} to confirm, or add --yes when not interactive")
|
|
119
|
+
return False
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def drop_slices(doc: hosts.Owned) -> list[gateway.Check]:
|
|
123
|
+
"""A suite slice file goes once no unit runs in it (remote_ops does the same per unit)."""
|
|
124
|
+
units = Path(os.path.expanduser(UNIT_DIR))
|
|
125
|
+
texts = [p.read_text(encoding="utf-8") for p in units.glob("*.service")]
|
|
126
|
+
checks: list[gateway.Check] = []
|
|
127
|
+
for name in doc["slices"]:
|
|
128
|
+
path = units / name
|
|
129
|
+
if any(f"Slice={name}\n" in t for t in texts):
|
|
130
|
+
checks.append({"check": f"slice {name}", "ok": False, "detail": "in use, kept"})
|
|
131
|
+
continue
|
|
132
|
+
if path.is_file() and "Description=localmodels suite" in path.read_text(encoding="utf-8"):
|
|
133
|
+
path.unlink()
|
|
134
|
+
harness.run_tool(["systemctl", "--user", "daemon-reload"], timeout=30)
|
|
135
|
+
checks.append({"check": f"slice {name}", "ok": True, "detail": "deleted"})
|
|
136
|
+
|
|
137
|
+
def drop(d: hosts.Owned, name: str = name) -> None:
|
|
138
|
+
d["slices"] = [s for s in d["slices"] if s != name]
|
|
139
|
+
|
|
140
|
+
hosts.update_owned(drop)
|
|
141
|
+
return checks
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def list_files(
|
|
145
|
+
executor: Executor,
|
|
146
|
+
entries: dict[str, hosts.OwnedDeployment],
|
|
147
|
+
plans: dict[str, RemoveParams],
|
|
148
|
+
keep: set[str],
|
|
149
|
+
weights: bool,
|
|
150
|
+
*,
|
|
151
|
+
act: ActFn,
|
|
152
|
+
) -> Listing:
|
|
153
|
+
"""Each deployment's dry run fills in the files its removal deletes: everything in its
|
|
154
|
+
directory, and with ``weights`` its model files that nothing else uses."""
|
|
155
|
+
found_all: Listing = []
|
|
156
|
+
for name, entry in entries.items():
|
|
157
|
+
plan_purge(plans[name], entry["files"] if weights else [], keep)
|
|
158
|
+
found = listing(act(executor, {**plans[name], "dry_run": True}))
|
|
159
|
+
plans[name]["purge"] = [path for path, _, _ in found]
|
|
160
|
+
found_all += found
|
|
161
|
+
return found_all
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def remove_services(
|
|
165
|
+
executor: Executor,
|
|
166
|
+
entries: dict[str, hosts.OwnedDeployment],
|
|
167
|
+
plans: dict[str, RemoveParams],
|
|
168
|
+
weights: bool,
|
|
169
|
+
unwire_checks: list[gateway.Check],
|
|
170
|
+
*,
|
|
171
|
+
act: ActFn,
|
|
172
|
+
) -> list[gateway.Check]:
|
|
173
|
+
"""Stop and remove each service with its directory. A deployment whose model files stay
|
|
174
|
+
remains in the manifest as removed, so a later ``--purge`` finds them."""
|
|
175
|
+
if not all(check["ok"] for check in unwire_checks):
|
|
176
|
+
return []
|
|
177
|
+
checks: list[gateway.Check] = []
|
|
178
|
+
for name, entry in entries.items():
|
|
179
|
+
result = act(executor, plans[name])
|
|
180
|
+
ok = result.get("event") == "result"
|
|
181
|
+
kept = (
|
|
182
|
+
[] if weights else [f for f in entry["files"] if os.path.lexists(os.path.expanduser(f))]
|
|
183
|
+
)
|
|
184
|
+
done = f"removed with its directory ({result.get('purged', 0)} files)"
|
|
185
|
+
done += f", {len(kept)} model file(s) kept" if kept else ""
|
|
186
|
+
checks.append(
|
|
187
|
+
{"check": name, "ok": ok, "detail": done if ok else str(result.get("message"))}
|
|
188
|
+
)
|
|
189
|
+
if ok:
|
|
190
|
+
hosts.delete_record(hosts.LOCAL_ID, name, purged=not kept)
|
|
191
|
+
return checks
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def remove_tools(
|
|
195
|
+
doc: hosts.Owned, magpie: str | None, plan: harness.ToolPlan | None = None
|
|
196
|
+
) -> tuple[list[gateway.Check], list[str]]:
|
|
197
|
+
"""The gateway this tool started goes before the Magpie it runs, then the tools and the
|
|
198
|
+
archives they were installed from. A Magpie that changed since install (it updates itself)
|
|
199
|
+
keeps its gateway: other providers may use it. Every tool leaves the manifest, deleted or
|
|
200
|
+
kept with the reason printed."""
|
|
201
|
+
checks: list[gateway.Check] = []
|
|
202
|
+
notes: list[str] = []
|
|
203
|
+
started = doc["gateway"]["started"]
|
|
204
|
+
ours = next((t for t in doc["tools"] if Path(t["path"]).name == "magpie"), None)
|
|
205
|
+
drift = harness.changed(ours) if ours and os.path.lexists(ours["path"]) else None
|
|
206
|
+
if started and magpie and ours and drift:
|
|
207
|
+
hosts.own_gateway(hosts.TOOLS_DIR, "started", None)
|
|
208
|
+
notes.append(
|
|
209
|
+
f"- gateway ({started}) kept: {ours['path']} {drift}; it may serve other providers"
|
|
210
|
+
)
|
|
211
|
+
elif started and magpie:
|
|
212
|
+
gateway_check = gateway.stop_gateway(magpie, started, plan=plan)
|
|
213
|
+
checks.append(gateway_check)
|
|
214
|
+
if not gateway_check["ok"]:
|
|
215
|
+
notes.append("- tools kept: stopping the gateway failed; fix it and rerun stack remove")
|
|
216
|
+
return checks, notes
|
|
217
|
+
gone, kept = harness.remove_tools(doc, True)
|
|
218
|
+
tools = {t["path"] for t in doc["tools"]}
|
|
219
|
+
archives = set(doc["archives"])
|
|
220
|
+
|
|
221
|
+
def forget(d: hosts.Owned) -> None:
|
|
222
|
+
d["tools"] = [t for t in d["tools"] if t["path"] not in tools]
|
|
223
|
+
d["archives"] = [a for a in d["archives"] if a not in archives]
|
|
224
|
+
|
|
225
|
+
hosts.update_owned(forget)
|
|
226
|
+
notes += [f"- kept {path}: {reason}" for path, reason in kept.items()]
|
|
227
|
+
if gone:
|
|
228
|
+
checks.append({"check": "tools", "ok": True, "detail": "deleted " + ", ".join(gone)})
|
|
229
|
+
return checks, notes
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def outside(members: set[str], doc: hosts.Owned) -> dict[str, bool]:
|
|
233
|
+
"""Deployments this computer has that no stack apply deployed, and whether each still has
|
|
234
|
+
a record (``service local NAME remove`` needs one)."""
|
|
235
|
+
found = {r["plan"]["name"]: True for r in hosts.records(hosts.LOCAL_ID)}
|
|
236
|
+
found |= {n: found.get(n, False) for n in doc["deployments"]}
|
|
237
|
+
return {n: has for n, has in sorted(found.items()) if n not in members}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def chosen(members: set[str], doc: hosts.Owned, everything: bool, out: Out) -> set[str]:
|
|
241
|
+
"""The deployments this uninstall takes: the stack's; those an earlier remove left only
|
|
242
|
+
model files of; one whose directory is gone (cleared from the manifest); and with
|
|
243
|
+
``everything`` the rest. A deployment of another kind, or one recorded under another state
|
|
244
|
+
directory, is named and left alone: it may be serving."""
|
|
245
|
+
selected = set(members)
|
|
246
|
+
for name, has_record in outside(members, doc).items():
|
|
247
|
+
entry = doc["deployments"].get(name)
|
|
248
|
+
live = entry is not None and not entry["removed"]
|
|
249
|
+
here = live and os.path.isdir(os.path.expanduser(doc["deployments"][name]["deploy_dir"]))
|
|
250
|
+
if everything or (entry is not None and not has_record and not here):
|
|
251
|
+
if live and not here:
|
|
252
|
+
out(f"- {name}: its directory is gone; cleared from the manifest")
|
|
253
|
+
selected.add(name)
|
|
254
|
+
continue
|
|
255
|
+
how = (
|
|
256
|
+
f"use service local {name} remove"
|
|
257
|
+
if has_record
|
|
258
|
+
else "it has no deployment record here (another state directory may manage it)"
|
|
259
|
+
)
|
|
260
|
+
out(f"- {name}: not part of this stack, left unchanged; {how}, or stack remove --all")
|
|
261
|
+
return selected
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def teardown(
|
|
265
|
+
doc: hosts.Owned,
|
|
266
|
+
entries: dict[str, hosts.OwnedDeployment],
|
|
267
|
+
plans: dict[str, RemoveParams],
|
|
268
|
+
executor: Executor,
|
|
269
|
+
target: harness.ToolPlan | None,
|
|
270
|
+
weights: bool,
|
|
271
|
+
serve_log: str,
|
|
272
|
+
*,
|
|
273
|
+
remove_services_fn: RemoveServicesFn,
|
|
274
|
+
) -> tuple[list[gateway.Check], list[str]]:
|
|
275
|
+
"""Clients, services, then gateway and tools, each only when the step before succeeded."""
|
|
276
|
+
magpie = gateway_probe.magpie_binary(doc)
|
|
277
|
+
magpie_plan = harness_gateway.magpie_target(hosts.TOOLS_DIR) # past a verified Bifrost move
|
|
278
|
+
checks = gateway.unwire(magpie, plan=target, magpie_plan=magpie_plan)
|
|
279
|
+
checks += remove_services_fn(executor, entries, plans, weights, checks)
|
|
280
|
+
if all(check["ok"] for check in checks):
|
|
281
|
+
tool_checks, notes = remove_tools(doc, magpie, magpie_plan or target)
|
|
282
|
+
else:
|
|
283
|
+
tool_checks, notes = [], ["- tools kept: earlier step failed; fix and rerun stack remove"]
|
|
284
|
+
checks += tool_checks
|
|
285
|
+
if all(check["ok"] for check in checks):
|
|
286
|
+
harness_gateway.purge_gateway_profile(target, notes)
|
|
287
|
+
if os.path.isfile(serve_log):
|
|
288
|
+
os.remove(serve_log)
|
|
289
|
+
return checks + drop_slices(hosts.load_owned()), notes
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def run_remove(
|
|
293
|
+
purge: bool,
|
|
294
|
+
yes: bool,
|
|
295
|
+
out: Out = print,
|
|
296
|
+
confirm: Confirm = ask,
|
|
297
|
+
*,
|
|
298
|
+
everything: bool = False,
|
|
299
|
+
dry_run: bool = False,
|
|
300
|
+
act: ActFn,
|
|
301
|
+
remove_services_fn: RemoveServicesFn,
|
|
302
|
+
members_fn: Callable[[], set[str]],
|
|
303
|
+
owned_params_fn: Callable[[str, hosts.OwnedDeployment], RemoveParams] = owned_params,
|
|
304
|
+
) -> int:
|
|
305
|
+
if sys.platform != "darwin" and (error := platform_error(sys.platform)):
|
|
306
|
+
raise StackError(error)
|
|
307
|
+
members = members_fn()
|
|
308
|
+
doc = stack_cleanup.adopted(members, dry_run, out)
|
|
309
|
+
target = harness_gateway.accepted_plan(hosts.TOOLS_DIR)
|
|
310
|
+
profile = harness_gateway.gateway_profile(target)
|
|
311
|
+
selected = chosen(members, doc, everything, out)
|
|
312
|
+
if any(t["sha256"] is None for t in doc["tools"]):
|
|
313
|
+
out(
|
|
314
|
+
f"- {hosts.owned_path()} lists tools by path only (manifest format before v1), "
|
|
315
|
+
"treated as legacy, unverified; neither remove nor --purge deletes them"
|
|
316
|
+
)
|
|
317
|
+
entries = {n: d for n, d in doc["deployments"].items() if n in selected}
|
|
318
|
+
doc = stack_cleanup.without_others_archives(doc, selected, out)
|
|
319
|
+
engines = stack_cleanup.engines_in_use() # before anything goes: what the stack ran
|
|
320
|
+
bases = {Path(os.path.expanduser(d["deploy_dir"])).parent.parent for d in entries.values()}
|
|
321
|
+
bases.add(Path(os.path.expanduser(deploy.DEFAULT_BASE_DIR)))
|
|
322
|
+
last = not set(outside(selected, doc)) # no deployment of another kind is left to read state
|
|
323
|
+
# A plain uninstall keeps the verified downloads beside the model files; a purge takes them.
|
|
324
|
+
downloads = [] if purge else stack_cleanup.kept_downloads(doc, engines, selected, last)
|
|
325
|
+
doc = {**doc, "archives": [a for a in doc["archives"] if a not in downloads]}
|
|
326
|
+
if hosts.owns_nothing({**doc, "deployments": entries}) and not (profile and profile.exists()):
|
|
327
|
+
return stack_cleanup.finish(engines, selected, bases, last, dry_run, out, downloads=purge)
|
|
328
|
+
executor = hosts.executor(hosts.get_device(hosts.LOCAL_ID))
|
|
329
|
+
plans = {n: owned_params_fn(n, d) for n, d in entries.items()}
|
|
330
|
+
serve_log = str(hosts.owned_path().parent / "magpie-serve.log")
|
|
331
|
+
keep = in_use(hosts.records(hosts.LOCAL_ID), selected)
|
|
332
|
+
keep |= {f for n, d in doc["deployments"].items() if n not in selected for f in d["files"]}
|
|
333
|
+
found = list_files(executor, entries, plans, keep, purge, act=act)
|
|
334
|
+
found += stack_cleanup.local_listing(
|
|
335
|
+
[*doc["archives"], serve_log, *([str(profile)] if profile else [])]
|
|
336
|
+
)
|
|
337
|
+
kept_weights = stack_cleanup.kept_weights(entries, found)
|
|
338
|
+
if dry_run:
|
|
339
|
+
swept = stack_cleanup.sweep(engines, selected, state=last, downloads=purge, dry_run=True)
|
|
340
|
+
kept = stack_cleanup.local_listing(downloads)
|
|
341
|
+
stack_cleanup.preview(found, kept_weights, swept, doc, out, kept)
|
|
342
|
+
return 0
|
|
343
|
+
if purge and not approve(found, yes, out, confirm):
|
|
344
|
+
return 1
|
|
345
|
+
checks, notes = teardown(
|
|
346
|
+
doc,
|
|
347
|
+
entries,
|
|
348
|
+
plans,
|
|
349
|
+
executor,
|
|
350
|
+
target,
|
|
351
|
+
purge,
|
|
352
|
+
serve_log,
|
|
353
|
+
remove_services_fn=remove_services_fn,
|
|
354
|
+
)
|
|
355
|
+
for check in checks:
|
|
356
|
+
out(f"{'✓' if check['ok'] else '✗'} {check['check']}: {check['detail']}")
|
|
357
|
+
for note in notes:
|
|
358
|
+
out(note)
|
|
359
|
+
if not all(c["ok"] for c in checks):
|
|
360
|
+
out(f"Not all removed; still recorded in {hosts.owned_path()}; fix and rerun stack remove")
|
|
361
|
+
return 1
|
|
362
|
+
stack_cleanup.finish(engines, selected, bases, last, False, out, quiet=True, downloads=purge)
|
|
363
|
+
stack_cleanup.record_downloads(downloads)
|
|
364
|
+
kept = stack_cleanup.local_listing(downloads)
|
|
365
|
+
weight = sum(size for _, size, _ in [*kept_weights, *kept])
|
|
366
|
+
out(
|
|
367
|
+
f"Removed. Kept {len(kept_weights)} model files and {len(kept)} downloaded archives, "
|
|
368
|
+
f"{gib(weight)}: the next install reuses them; {command()} stack remove --purge "
|
|
369
|
+
"deletes them"
|
|
370
|
+
if kept_weights or kept
|
|
371
|
+
else "Removed. Nothing this tool installed is left but the manifest's empty lock file"
|
|
372
|
+
)
|
|
373
|
+
return 0
|