@simplexai/localmodels-linux-arm64 0.1.0-dev.57 → 0.1.0-dev.59

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 (68) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +66 -64
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +1 -1
  5. package/modules/localmodels/bifrost_admin.py +53 -8
  6. package/modules/localmodels/bifrost_config.py +103 -4
  7. package/modules/localmodels/bifrost_log.py +166 -0
  8. package/modules/localmodels/budget.py +161 -1
  9. package/modules/localmodels/catalog.json +55 -32
  10. package/modules/localmodels/catalog.py +5 -2
  11. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +94 -0
  12. package/modules/localmodels/frontend.py +26 -21
  13. package/modules/localmodels/gateway_bifrost.py +30 -6
  14. package/modules/localmodels/gpu_specs.py +38 -13
  15. package/modules/localmodels/hosts.py +99 -12
  16. package/modules/localmodels/library_cli.py +8 -1
  17. package/modules/localmodels/library_convert.py +34 -0
  18. package/modules/localmodels/library_elastic.py +747 -0
  19. package/modules/localmodels/library_gateway.py +101 -10
  20. package/modules/localmodels/library_jobs.py +16 -7
  21. package/modules/localmodels/library_model.py +101 -4
  22. package/modules/localmodels/library_pricing.py +41 -39
  23. package/modules/localmodels/library_serve.py +322 -58
  24. package/modules/localmodels/library_state.py +35 -1
  25. package/modules/localmodels/library_status.py +113 -6
  26. package/modules/localmodels/llm_rank.py +16 -5
  27. package/modules/localmodels/metal.py +141 -0
  28. package/modules/localmodels/metal_probe.py +167 -0
  29. package/modules/localmodels/plan_envelope.py +4 -1
  30. package/modules/localmodels/probe.py +2 -2
  31. package/modules/localmodels/process_identity_linux.py +39 -0
  32. package/modules/localmodels/recommend.py +6 -1
  33. package/modules/localmodels/remote_ops.py +4 -3
  34. package/modules/localmodels/remote_ops_download.py +37 -24
  35. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  36. package/modules/localmodels/remote_ops_service.py +93 -36
  37. package/modules/localmodels/runtime_auth.py +4 -1
  38. package/modules/localmodels/service_wiring.py +238 -12
  39. package/modules/localmodels/setup_inspection.py +47 -70
  40. package/modules/localmodels/setup_inspection_harness.py +159 -15
  41. package/modules/localmodels/setup_text.py +14 -0
  42. package/modules/localmodels/setup_upgrade.py +1 -1
  43. package/modules/localmodels/source_byok.py +6 -2
  44. package/modules/localmodels/source_byok_probe.py +6 -1
  45. package/modules/localmodels/stack.py +9 -1
  46. package/modules/localmodels/stack_binding.py +3 -35
  47. package/modules/localmodels/stack_cleanup.py +4 -0
  48. package/modules/localmodels/stack_compose.py +24 -3
  49. package/modules/localmodels/stack_hardware.py +3 -1
  50. package/modules/localmodels/stack_lifecycle.py +24 -1
  51. package/modules/localmodels/stack_picks.py +16 -2
  52. package/modules/localmodels/stack_plan.py +6 -2
  53. package/modules/localmodels/stack_ports.py +2 -0
  54. package/modules/localmodels/stack_remove.py +10 -1
  55. package/modules/localmodels/stack_up.py +33 -7
  56. package/modules/localmodels/stack_update.py +3 -1
  57. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.5.txt} +1 -1
  58. package/modules/localmodels/suite.py +43 -27
  59. package/modules/localmodels/transport.py +13 -2
  60. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/METADATA +1 -1
  61. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/RECORD +63 -61
  62. package/package.json +1 -1
  63. package/tool.json +1 -1
  64. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  65. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/WHEEL +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/entry_points.txt +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/NOTICE +0 -0
  68. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -13,8 +13,11 @@ Two short requests measure its decode speed (stack_warm), and the gateway and pi
13
13
  from __future__ import annotations
14
14
 
15
15
  import contextlib
16
+ import contextvars
16
17
  import os
17
18
  import shutil
19
+ from collections.abc import Iterator
20
+ from dataclasses import dataclass
18
21
  from pathlib import Path
19
22
 
20
23
  from localmodels import (
@@ -24,27 +27,74 @@ from localmodels import (
24
27
  frontend,
25
28
  harness,
26
29
  hosts,
30
+ library_elastic,
27
31
  library_gateway,
28
32
  library_jobs,
29
33
  library_kept,
30
34
  library_pricing,
31
35
  library_state,
32
36
  library_status,
37
+ metal,
33
38
  plan_envelope,
39
+ source_byok,
34
40
  stack_lifecycle,
35
41
  stack_ports,
36
42
  stack_verify,
37
43
  stack_warm,
38
44
  )
39
- from localmodels.library_model import LibraryError, LoadStep, Row, progress
45
+ from localmodels.library_elastic import ElasticPlan, ElasticRoomError
46
+ from localmodels.library_model import LibraryError, LoadStep, Row, problem_from_error, progress
40
47
  from localmodels.library_pricing import Model
41
- from localmodels.library_state import Job, JobHandle, Record
48
+ from localmodels.library_state import Job, JobHandle, LoadPosture, PostureSnapshot, Record
42
49
  from localmodels.probe import HostFacts
43
50
  from localmodels.records import FinishedRecord, Plan
44
51
  from localmodels.transport import Executor
45
52
 
46
53
  LOAD_STEPS = deploy.STEPS
47
- OOM = ("out of memory", "cudamalloc failed", "failed to allocate", "unable to allocate")
54
+ MAX_OOM_RETRIES = 2
55
+ OOM = (
56
+ "out of memory",
57
+ "cudamalloc failed",
58
+ "failed to allocate",
59
+ "unable to allocate",
60
+ "ggml_metal_buffer_init",
61
+ "metal_buffer_init",
62
+ "newbufferwithlength",
63
+ "failed to create metal",
64
+ "metal allocation failed",
65
+ "ggml_backend_metal_buffer",
66
+ "kioreturnnomemory",
67
+ "not enough memory",
68
+ "insufficient memory",
69
+ "std::bad_alloc",
70
+ "bad_alloc",
71
+ )
72
+
73
+
74
+ @dataclass
75
+ class _ElasticLoadContext:
76
+ """Active load parameters for runtime OOM self-healing retries inside ``_start``."""
77
+
78
+ elastic: ElasticPlan
79
+ base: str
80
+ pool: str
81
+ port: int
82
+ force: bool
83
+
84
+
85
+ _FORCE_LOAD: contextvars.ContextVar[bool] = contextvars.ContextVar("_FORCE_LOAD", default=False)
86
+ _ELASTIC_CTX: contextvars.ContextVar[_ElasticLoadContext | None] = contextvars.ContextVar(
87
+ "_ELASTIC_CTX", default=None
88
+ )
89
+
90
+
91
+ @contextlib.contextmanager
92
+ def _force_scope(force: bool) -> Iterator[None]:
93
+ token = _FORCE_LOAD.set(force)
94
+ try:
95
+ yield
96
+ finally:
97
+ _FORCE_LOAD.reset(token)
48
98
 
49
99
 
50
100
  def _deploy_load_step(step: str) -> LoadStep:
@@ -71,27 +121,113 @@ def _reserved(skip: str) -> dict[str, int]:
71
121
  return found
72
122
 
73
123
 
74
- def _room(facts: HostFacts, model: Model, record: Record, freed: dict[str, int]) -> None:
75
- """LOAD_NO_ROOM unless the model fits its pool now, after ``freed`` is given back."""
124
+ def _pressure_name(level: int | None) -> str | None:
125
+ if level is None:
126
+ return None
127
+ if level == metal.PRESSURE_NORMAL:
128
+ return "normal"
129
+ if level == metal.PRESSURE_WARN:
130
+ return "warn"
131
+ return "critical"
132
+
133
+
134
+ def _no_room_error(
135
+ model: Model,
136
+ exc: deploy.AgentMemoryError,
137
+ default_pool: str,
138
+ *,
139
+ failed: bool = False,
140
+ ) -> LibraryError:
141
+ refused_pool = "system" if exc.memory == "system memory" else default_pool
142
+ fields: dict[str, str | int | bool] = {
143
+ "pool": refused_pool,
144
+ "need_bytes": exc.needed_bytes,
145
+ "free_bytes": exc.available_bytes,
146
+ }
147
+ if isinstance(exc, ElasticRoomError):
148
+ refused_pool = exc.pool
149
+ fields["pool"] = refused_pool
150
+ fields["min_need_bytes"] = exc.min_need_bytes
151
+ fields["shortfall_bytes"] = exc.shortfall_bytes
152
+ fields["can_force"] = exc.can_force
153
+ if exc.wired_headroom_bytes is not None:
154
+ fields["wired_headroom_bytes"] = exc.wired_headroom_bytes
155
+ if exc.soft_available_bytes is not None:
156
+ fields["soft_available_bytes"] = exc.soft_available_bytes
157
+ if (label := _pressure_name(exc.pressure_level)) is not None:
158
+ fields["memory_pressure"] = label
159
+ else:
160
+ fields["min_need_bytes"] = exc.needed_bytes
161
+ fields["shortfall_bytes"] = max(0, exc.needed_bytes - exc.available_bytes)
162
+ fields["can_force"] = False
163
+ return LibraryError(
164
+ "LOAD_NO_ROOM",
165
+ f"{model.id} does not fit {refused_pool} now",
166
+ failed=failed,
167
+ **fields,
168
+ )
169
+
170
+
171
+ def _posture_snapshot(spec: library_elastic.PostureSpec) -> PostureSnapshot:
172
+ summary = spec.to_summary()
173
+ snap: PostureSnapshot = {
174
+ "context_tokens": summary["context_tokens"],
175
+ "slots": summary["slots"],
176
+ }
177
+ if "kv_cache_quant" in summary:
178
+ snap["kv_cache_quant"] = summary["kv_cache_quant"]
179
+ return snap
180
+
181
+
182
+ def _load_posture_record(
183
+ elastic: ElasticPlan, *, oom_retries: int = 0, degradation_reason: str | None = None
184
+ ) -> LoadPosture:
185
+ reason = degradation_reason if degradation_reason is not None else elastic.degradation_reason
186
+ degraded = elastic.degraded or oom_retries > 0
187
+ doc: LoadPosture = {
188
+ "requested_posture": _posture_snapshot(elastic.requested_posture),
189
+ "effective_posture": _posture_snapshot(elastic.effective_posture),
190
+ "degraded": degraded,
191
+ }
192
+ if elastic.memory_pressure_warning is not None:
193
+ warn = elastic.memory_pressure_warning
194
+ doc["memory_pressure_warning"] = {
195
+ "level": warn["level"],
196
+ "pool": warn["pool"],
197
+ "free_bytes": warn["free_bytes"],
198
+ "budget_bytes": warn["budget_bytes"],
199
+ }
200
+ if degraded and reason:
201
+ doc["degradation_reason"] = reason
202
+ if oom_retries > 0:
203
+ doc["oom_retries"] = oom_retries
204
+ if elastic.forced:
205
+ doc["forced"] = True
206
+ return doc
207
+
208
+
209
+ def _room(
210
+ facts: HostFacts,
211
+ model: Model,
212
+ record: Record,
213
+ freed: dict[str, int],
214
+ *,
215
+ force: bool = False,
216
+ ) -> ElasticPlan:
217
+ """LOAD_NO_ROOM unless the model fits its pool under dual-tier admission after ``freed``."""
76
218
  now = library_pricing.live(facts, _reserved(model.id), freed)
77
219
  try:
78
- library_pricing.price(
220
+ return library_elastic.price_elastic(
79
221
  now,
80
222
  model,
81
223
  record["pool"],
82
224
  base_of(record),
83
225
  library_pricing.entries(),
84
- require_live=True,
226
+ allow_overcommit=True,
227
+ force=force,
85
228
  )
86
229
  except deploy.AgentMemoryError as exc:
87
- refused_pool = "system" if exc.memory == "system memory" else record["pool"]
88
- raise LibraryError(
89
- "LOAD_NO_ROOM",
90
- f"{model.id} does not fit {refused_pool} now",
91
- pool=refused_pool,
92
- need_bytes=exc.needed_bytes,
93
- free_bytes=exc.available_bytes,
94
- ) from None
230
+ raise _no_room_error(model, exc, record["pool"]) from None
95
231
  except engines.CudaDriverError as exc:
96
232
  raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc)) from None
97
233
  except engines.EngineUnavailableError as exc:
@@ -140,7 +276,7 @@ def _remove_service(plan: Plan, run: Executor) -> None:
140
276
  raise LibraryError(
141
277
  "ENGINE_START_FAILED", f"stopping {plan['name']}: {outcome.get('message')}"
142
278
  )
143
- hosts.delete_record(hosts.LOCAL_ID, plan["name"])
279
+ hosts.delete_record(hosts.LOCAL_ID, plan["name"], deploy_dir=plan["service"]["deploy_dir"])
144
280
 
145
281
 
146
282
  def _forget_deployment(plan: Plan) -> None:
@@ -149,7 +285,9 @@ def _forget_deployment(plan: Plan) -> None:
149
285
  deploy_dir = Path(os.path.expanduser(plan["service"]["deploy_dir"]))
150
286
  if deploy_dir.parent.name == "deployments" and deploy_dir.is_dir():
151
287
  shutil.rmtree(deploy_dir, ignore_errors=True)
152
- hosts.delete_record(hosts.LOCAL_ID, plan["name"], purged=True)
288
+ hosts.delete_record(
289
+ hosts.LOCAL_ID, plan["name"], purged=True, deploy_dir=plan["service"]["deploy_dir"]
290
+ )
153
291
 
154
292
 
155
293
  def stack_member(record: Record) -> str | None:
@@ -161,33 +299,44 @@ def stack_member(record: Record) -> str | None:
161
299
 
162
300
  def _fail(record: Record, error: LibraryError) -> LibraryError:
163
301
  record["state"] = "failed"
164
- record["error"] = {"code": error.code, "detail": error.detail}
302
+ record["error"] = problem_from_error(error)
165
303
  library_state.save(record) # a registration it could not take out stays for unload
166
304
  return error
167
305
 
168
306
 
307
+ def _restore_baseline_plan(record: Record) -> None:
308
+ """Restore the pristine capacity plan once the active server is stopped."""
309
+ if (baseline := record.pop("baseline_plan", None)) is not None:
310
+ record["plan"] = baseline
311
+
312
+
169
313
  def stop(record: Record, run: Executor) -> None:
170
- """Unregister, then stop and remove the model's server; its weights stay. Either failing
171
- raises, so the next unload or remove tries again. Once unregistered the record says so
172
- before the server stops: a process killed in between leaves a failed model with no
173
- registration, which status shows and the next load registers again, never a loaded one
174
- the gateway and pi no longer route to."""
314
+ """Demote a loaded record, unregister it, then stop and remove the model's server; its
315
+ weights stay. Either failing raises, so the next unload or remove tries again. A loaded
316
+ record is marked failed on disk before unregistering so a failed, interrupted, or killed
317
+ stop never leaves status or load treating an unroutable model as loaded; once unregistered
318
+ the registration receipt is removed before the server stops."""
175
319
  if registration := record.get("registration"):
176
- library_gateway.unregister(registration)
177
- record.pop("registration")
178
320
  if record["state"] == "loaded":
179
321
  record["state"] = "failed"
180
322
  record["error"] = {
181
323
  "code": "ENGINE_START_FAILED",
182
324
  "detail": "stopping the model server did not finish; unload or load it again",
183
325
  }
326
+ library_state.save(record)
327
+ library_gateway.unregister(registration)
328
+ record.pop("registration")
184
329
  library_state.save(record)
330
+ record.pop("load_posture", None)
185
331
  if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
186
332
  _remove_service(record["plan"], run)
187
333
  record["state"] = "idle"
188
334
  for key in ("registration", "error", "note"):
189
335
  record.pop(key, None) # type: ignore[misc]
190
336
  library_state.save(record)
337
+ if (baseline := record.pop("baseline_plan", None)) is not None:
338
+ record["plan"] = baseline
339
+ library_state.save(record)
191
340
 
192
341
 
193
342
  def _serve(
@@ -197,46 +346,54 @@ def _serve(
197
346
  run: Executor,
198
347
  port: int,
199
348
  handle: JobHandle,
349
+ *,
350
+ force: bool = False,
200
351
  ) -> Record:
201
352
  base = base_of(record)
202
353
  now = library_pricing.live(facts, _reserved(model.id))
203
354
  try:
204
- plan = library_pricing.price(
355
+ elastic = library_elastic.price_elastic(
205
356
  now,
206
357
  model,
207
358
  record["pool"],
208
359
  base,
209
360
  library_pricing.entries(),
210
361
  port=port,
211
- require_live=True,
362
+ allow_overcommit=True,
363
+ force=force,
212
364
  )
213
365
  except deploy.AgentMemoryError as exc: # after --unload: no longer a refusal
214
- refused_pool = "system" if exc.memory == "system memory" else record["pool"]
215
- raise LibraryError(
216
- "LOAD_NO_ROOM",
217
- f"{model.id} does not fit {refused_pool} now",
218
- failed=True,
219
- pool=refused_pool,
220
- need_bytes=exc.needed_bytes,
221
- free_bytes=exc.available_bytes,
222
- ) from None
366
+ raise _fail(record, _no_room_error(model, exc, record["pool"], failed=True)) from None
223
367
  except engines.CudaDriverError as exc:
224
368
  raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc), failed=True) from None
225
369
  except engines.EngineUnavailableError as exc:
226
370
  raise LibraryError("RUNTIME_DEPENDENCY_MISSING", str(exc), failed=True) from None
227
371
  except library_pricing.LiveMemoryUnavailable as exc:
228
- raise LibraryError(
229
- "LOAD_NO_ROOM",
230
- str(exc),
231
- failed=True,
232
- pool=record["pool"],
233
- need_bytes=record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"]),
234
- free_bytes=0,
372
+ need = record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"])
373
+ raise _fail(
374
+ record,
375
+ LibraryError(
376
+ "LOAD_NO_ROOM",
377
+ str(exc),
378
+ failed=True,
379
+ pool=record["pool"],
380
+ need_bytes=need,
381
+ free_bytes=0,
382
+ min_need_bytes=need,
383
+ shortfall_bytes=need,
384
+ can_force=False,
385
+ ),
235
386
  ) from None
387
+ plan = elastic.plan
236
388
  if missing := library_jobs.files_missing(plan):
237
389
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing), failed=True)
238
390
  steps = [str(step) for step in LOAD_STEPS]
239
-
391
+ record["load_posture"] = _load_posture_record(elastic)
392
+ ctx_token = _ELASTIC_CTX.set(
393
+ _ElasticLoadContext(elastic=elastic, base=base, pool=record["pool"], port=port, force=force)
394
+ )
395
+ if record.get("baseline_plan") is None:
396
+ record["baseline_plan"] = record["plan"]
240
397
  record["plan"], record["state"] = plan, "starting"
241
398
  record.pop("error", None)
242
399
  library_state.save(record) # the server about to start is recorded before it exists
@@ -249,6 +406,8 @@ def _serve(
249
406
  except BaseException: # interrupted (cancel, Ctrl-C) or crashed once the server may run
250
407
  _abandon(record, run)
251
408
  raise
409
+ finally:
410
+ _ELASTIC_CTX.reset(ctx_token)
252
411
  record["state"] = "loaded"
253
412
  record.pop("error", None)
254
413
  record.pop("note", None)
@@ -256,6 +415,53 @@ def _serve(
256
415
  return record
257
416
 
258
417
 
418
+ def _next_oom_rung(
419
+ model: Model, facts: HostFacts, ctx: _ElasticLoadContext, next_index: int
420
+ ) -> ElasticPlan | None:
421
+ """Build the plan for posture rung ``next_index`` after an OOM failure on rung ``k``."""
422
+ if not ctx.elastic.ladder or next_index >= len(ctx.elastic.ladder):
423
+ return None
424
+ now = library_pricing.live(facts, _reserved(model.id))
425
+ try:
426
+ return library_elastic.price_elastic(
427
+ now,
428
+ model,
429
+ ctx.pool,
430
+ ctx.base,
431
+ library_pricing.entries(),
432
+ port=ctx.port,
433
+ allow_overcommit=True,
434
+ force=ctx.force,
435
+ min_rung_index=next_index,
436
+ )
437
+ except plan_envelope.PlanError:
438
+ return None
439
+
440
+
441
+ def _rollback_registration(
442
+ record: Record, plan: Plan, run: Executor, exc: LibraryError
443
+ ) -> LibraryError:
444
+ """Undo gateway registration and stop the server after a failed ``register()``, surfacing any
445
+ incomplete cleanup in the error detail while keeping uncleaned receipts/plans for ``unload``."""
446
+ notes: list[str] = []
447
+ try: # kept for unload when this fails too
448
+ library_gateway.unregister(record["registration"])
449
+ record.pop("registration")
450
+ except LibraryError as unreg_err:
451
+ notes.append(f"unregister failed ({unreg_err.detail})")
452
+ try:
453
+ _remove_service(plan, run)
454
+ except LibraryError as stop_err:
455
+ notes.append(f"failed to stop server ({stop_err.detail})")
456
+ else:
457
+ record.pop("load_posture", None)
458
+ _restore_baseline_plan(record)
459
+ if notes:
460
+ detail = f"{exc.detail}; rollback incomplete: {'; '.join(notes)}"
461
+ exc = LibraryError(exc.code, detail, failed=exc.failed, **exc.fields)
462
+ return _fail(record, exc)
463
+
464
+
259
465
  def _start(
260
466
  model: Model,
261
467
  record: Record,
@@ -275,13 +481,45 @@ def _start(
275
481
  try:
276
482
  frontend.install(str(plan["launch"]["frontend_base_dir"]), str(reqs))
277
483
  except frontend.FrontendError as exc:
484
+ record.pop("load_posture", None)
485
+ _restore_baseline_plan(record)
278
486
  raise _fail(record, LibraryError("ENGINE_START_FAILED", str(exc))) from None
279
487
 
280
- finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
281
- if not finished["ok"]:
282
- error = LibraryError(_start_code(finished), str(finished.get("error") or "start failed"))
283
- with contextlib.suppress(LibraryError): # the record keeps the plan to stop it later
488
+ ctx = _ELASTIC_CTX.get()
489
+ oom_retries = 0
490
+ while True:
491
+ finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
492
+ if finished["ok"]:
493
+ break
494
+ code = _start_code(finished)
495
+ error = LibraryError(code, str(finished.get("error") or "start failed"))
496
+ try:
284
497
  _remove_service(plan, run)
498
+ except LibraryError as cleanup_err:
499
+ # Keep record["plan"] on the unstopped deployment so unload/remove can stop it;
500
+ # never retry or launch a second server while the failed one may still hold GPU/RAM.
501
+ detail = f"{error.detail}; cleanup failed ({cleanup_err.detail})"
502
+ raise _fail(
503
+ record, LibraryError(code, detail, failed=error.failed, **error.fields)
504
+ ) from None
505
+ if code == "OUT_OF_MEMORY" and ctx is not None and oom_retries < MAX_OOM_RETRIES:
506
+ next_elastic = _next_oom_rung(model, facts, ctx, ctx.elastic.rung_index + 1)
507
+ if next_elastic is not None:
508
+ oom_retries += 1
509
+ ctx.elastic = next_elastic
510
+ plan = next_elastic.plan
511
+ record["plan"] = plan
512
+ record["load_posture"] = _load_posture_record(
513
+ next_elastic,
514
+ oom_retries=oom_retries,
515
+ degradation_reason="oom_retry",
516
+ )
517
+ library_state.save(record)
518
+ handle.update("load", 0, len(steps), load_step="prepare")
519
+ progress(model.id, "load", 0, len(steps), load_step="prepare")
520
+ continue
521
+ record.pop("load_posture", None)
522
+ _restore_baseline_plan(record)
285
523
  raise _fail(record, error)
286
524
  handle.update("load", len(steps), len(steps), load_step="load")
287
525
  progress(model.id, "load", len(steps), len(steps), load_step="load")
@@ -306,12 +544,7 @@ def _start(
306
544
  model.id, model.entry, plan, key, facts, stack_provider=member
307
545
  )
308
546
  except LibraryError as exc:
309
- with contextlib.suppress(LibraryError): # kept for unload when this fails too
310
- library_gateway.unregister(record["registration"])
311
- record.pop("registration")
312
- with contextlib.suppress(LibraryError):
313
- _remove_service(plan, run)
314
- raise _fail(record, exc) from None
547
+ raise _rollback_registration(record, plan, run, exc) from None
315
548
 
316
549
 
317
550
  def _abandon(record: Record, run: Executor) -> None:
@@ -345,7 +578,7 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
345
578
  freed["system"] = freed.get("system", 0) + library_pricing.host_ram_bytes(
346
579
  target["plan"], catalog
347
580
  )
348
- _room(facts, model, record, freed)
581
+ _room(facts, model, record, freed, force=_FORCE_LOAD.get())
349
582
 
350
583
 
351
584
  def _row(model: Model, base_dir: str) -> Row:
@@ -354,7 +587,7 @@ def _row(model: Model, base_dir: str) -> Row:
354
587
  return library_status.row(library_status.Library.read(library_jobs.probe(), base_dir), model)
355
588
 
356
589
 
357
- def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
590
+ def load(model_id: str, base_dir: str, unload: list[str], *, force: bool = False) -> Row:
358
591
  from localmodels import library_convert
359
592
 
360
593
  library_convert.convert_once()
@@ -365,7 +598,7 @@ def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
365
598
  dict.fromkeys(library_pricing.find(m, library_pricing.entries()).id for m in unload)
366
599
  )
367
600
  targets: list[Record] = []
368
- with library_state.locked(): # validate, admit and claim as one step
601
+ with library_state.locked(), _force_scope(force): # validate, admit and claim as one step
369
602
  library_state.refuse_busy(model.id, "load")
370
603
  record = library_state.load(model.id)
371
604
  if record is None:
@@ -404,7 +637,15 @@ def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
404
637
  # A stop that fails ends the load: a server that may still run keeps its record
405
638
  # and its memory, and nothing is started beside it.
406
639
  stop(record, executor)
407
- _serve(model, record, library_jobs.probe() if refresh else facts, executor, port, handle)
640
+ _serve(
641
+ model,
642
+ record,
643
+ library_jobs.probe() if refresh else facts,
644
+ executor,
645
+ port,
646
+ handle,
647
+ force=force,
648
+ )
408
649
  return _row(model, base_dir)
409
650
 
410
651
 
@@ -430,13 +671,27 @@ def unload(model_id: str, base_dir: str) -> Row:
430
671
  return _row(model, base_dir)
431
672
 
432
673
 
674
+ def _clear_removed_source(pi_model: str | None) -> None:
675
+ """Clear a stale local ``runtime_model`` in ``model-source.json`` when its model is removed."""
676
+ if not pi_model:
677
+ return
678
+ with contextlib.suppress(OSError, ValueError, source_byok.ByokError):
679
+ state = source_byok.load_source_state()
680
+ if state is not None and state["mode"] == "local" and state["runtime_model"] == pi_model:
681
+ source_byok.save_source_state({**state, "runtime_model": ""})
682
+
683
+
433
684
  def remove(model_id: str, base_dir: str) -> Row:
434
685
  from localmodels import library_convert
435
686
 
436
687
  library_convert.convert_once()
437
688
  model = library_pricing.find(model_id, library_pricing.entries())
438
689
  record, job = _claim(model, "remove")
690
+ reg = record.get("registration")
691
+ removed_pi_model = record.get("pi_model") or (reg.get("pi_model") if reg is not None else None)
692
+ still_served = False
439
693
  with library_state.held([job]):
694
+ active_plan = record["plan"]
440
695
  if record["state"] != "idle":
441
696
  stop(record, library_jobs.executor())
442
697
  with library_state.locked():
@@ -444,5 +699,14 @@ def remove(model_id: str, base_dir: str) -> Row:
444
699
  library_jobs.dests(record["plan"]), library_jobs.in_use(model.id)
445
700
  )
446
701
  _forget_deployment(record["plan"])
702
+ if active_plan["name"] != record["plan"]["name"]:
703
+ _forget_deployment(active_plan)
447
704
  library_state.forget(model.id)
705
+ if removed_pi_model:
706
+ still_served = any(
707
+ r.get("state") == "loaded" and r.get("pi_model") == removed_pi_model
708
+ for r in library_state.records()
709
+ )
710
+ if not still_served:
711
+ _clear_removed_source(removed_pi_model)
448
712
  return _row(model, base_dir)
@@ -56,6 +56,36 @@ class _RecordRequired(TypedDict):
56
56
  updated_at: str
57
57
 
58
58
 
59
+ class _PostureSnapshotRequired(TypedDict):
60
+ context_tokens: int
61
+ slots: int
62
+
63
+
64
+ class PostureSnapshot(_PostureSnapshotRequired, total=False):
65
+ kv_cache_quant: str
66
+ kv_types: list[str]
67
+
68
+
69
+ class PressureWarningSnapshot(TypedDict):
70
+ level: str
71
+ pool: str
72
+ free_bytes: int
73
+ budget_bytes: int
74
+
75
+
76
+ class _LoadPostureRequired(TypedDict):
77
+ requested_posture: PostureSnapshot
78
+ effective_posture: PostureSnapshot
79
+ degraded: bool
80
+
81
+
82
+ class LoadPosture(_LoadPostureRequired, total=False):
83
+ degradation_reason: str
84
+ memory_pressure_warning: PressureWarningSnapshot
85
+ oom_retries: int
86
+ forced: bool
87
+
88
+
59
89
  class Record(_RecordRequired, total=False):
60
90
  base_dir: str # where it was downloaded: its weights, engine and deployments live there
61
91
  memory_bytes: int # the footprint priced at download (on the pool's whole capacity)
@@ -67,6 +97,8 @@ class Record(_RecordRequired, total=False):
67
97
  converted: bool # adopted from a Quick Install stack
68
98
  stack_provider: str # converted: its own stack provider, the main or the fastest LLM
69
99
  pi_model: str # what pi offers once it is loaded; fixed when the record is made
100
+ load_posture: LoadPosture # elastic posture & warning metadata recorded on load
101
+ baseline_plan: Plan # pristine capacity plan preserved while a degraded/active load runs
70
102
 
71
103
 
72
104
  class _JobSince20261113(TypedDict, total=False):
@@ -225,8 +257,10 @@ def cancelled(job: Job) -> bool:
225
257
 
226
258
 
227
259
  def clear_job(model: str) -> None:
260
+ job = job_path(model)
228
261
  for path in (
229
- job_path(model),
262
+ job,
263
+ job.with_name(job.name + ".tmp"),
230
264
  cancel_path(model),
231
265
  pid_path(model),
232
266
  Path(str(pid_path(model)) + ".identity.json"),