@simplexai/localmodels-darwin-x64 0.1.0-dev.59 → 0.1.0-dev.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +79 -73
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +104 -43
  5. package/modules/localmodels/apple_sensors.py +431 -0
  6. package/modules/localmodels/bifrost_admin.py +30 -0
  7. package/modules/localmodels/bifrost_checks.py +2 -2
  8. package/modules/localmodels/bifrost_config.py +132 -9
  9. package/modules/localmodels/bifrost_models.py +1 -1
  10. package/modules/localmodels/catalog.json +146 -54
  11. package/modules/localmodels/catalog.py +20 -3
  12. package/modules/localmodels/catalog_add.py +42 -11
  13. package/modules/localmodels/custom_hub.py +983 -0
  14. package/modules/localmodels/custom_hub_http.py +579 -0
  15. package/modules/localmodels/custom_probe.py +451 -0
  16. package/modules/localmodels/deploy.py +27 -5
  17. package/modules/localmodels/deploy_steps.py +5 -0
  18. package/modules/localmodels/download-mirrors.json +8 -0
  19. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  20. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  21. package/modules/localmodels/engines.py +38 -8
  22. package/modules/localmodels/estimator.py +60 -7
  23. package/modules/localmodels/gateway.py +48 -3
  24. package/modules/localmodels/gateway_app_bifrost.py +4 -4
  25. package/modules/localmodels/gateway_bifrost.py +98 -15
  26. package/modules/localmodels/gguf.py +6 -0
  27. package/modules/localmodels/host_sensors.py +704 -0
  28. package/modules/localmodels/library_cli.py +181 -3
  29. package/modules/localmodels/library_custom.py +831 -0
  30. package/modules/localmodels/library_elastic.py +35 -7
  31. package/modules/localmodels/library_gateway.py +94 -32
  32. package/modules/localmodels/library_jobs.py +76 -11
  33. package/modules/localmodels/library_kept.py +50 -6
  34. package/modules/localmodels/library_model.py +254 -2
  35. package/modules/localmodels/library_pricing.py +83 -4
  36. package/modules/localmodels/library_serve.py +112 -50
  37. package/modules/localmodels/library_smoke.py +315 -0
  38. package/modules/localmodels/library_state.py +77 -1
  39. package/modules/localmodels/library_status.py +126 -4
  40. package/modules/localmodels/nvml_ctypes.py +431 -0
  41. package/modules/localmodels/plan_envelope.py +14 -6
  42. package/modules/localmodels/records.py +1 -0
  43. package/modules/localmodels/remote_ops.py +53 -5
  44. package/modules/localmodels/remote_ops_download.py +168 -29
  45. package/modules/localmodels/remote_ops_ranges.py +2 -5
  46. package/modules/localmodels/remote_ops_service.py +2 -1
  47. package/modules/localmodels/remote_ops_verify.py +22 -5
  48. package/modules/localmodels/runtime-lock.json +19 -19
  49. package/modules/localmodels/service_control.py +32 -1
  50. package/modules/localmodels/service_wiring.py +2 -3
  51. package/modules/localmodels/service_worker.py +6 -2
  52. package/modules/localmodels/services_cli.py +35 -27
  53. package/modules/localmodels/source_byok.py +3 -5
  54. package/modules/localmodels/stack_lifecycle.py +2 -2
  55. package/modules/localmodels/stack_memory.py +1 -0
  56. package/modules/localmodels/stack_view.py +77 -53
  57. package/modules/localmodels/stack_view_demo.py +36 -5
  58. package/modules/localmodels/stack_view_events.py +147 -12
  59. package/modules/localmodels/stack_view_gpu.py +97 -17
  60. package/modules/localmodels/stack_view_llm.py +15 -0
  61. package/modules/localmodels/stack_view_measure.py +4 -1
  62. package/modules/localmodels/stack_view_schema.py +54 -8
  63. package/modules/localmodels/stack_view_serve.py +40 -3
  64. package/modules/localmodels/stack_view_slots.py +89 -10
  65. package/modules/localmodels/stack_view_telemetry.py +163 -0
  66. package/modules/localmodels/stack_view_text.py +5 -2
  67. package/modules/localmodels/stack_view_tick.py +658 -0
  68. package/modules/localmodels/stack_view_words.py +4 -0
  69. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  70. package/modules/localmodels/suite.py +3 -1
  71. package/modules/localmodels/telemetry_math.py +538 -0
  72. package/modules/localmodels/web/view/view.js +1 -1
  73. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/METADATA +1 -1
  74. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/RECORD +76 -70
  75. package/package.json +1 -1
  76. package/tool.json +1 -1
  77. package/modules/localmodels/bifrost_datasheet.py +0 -53
  78. package/modules/localmodels/bifrost_provider.py +0 -88
  79. package/modules/localmodels/bifrost_unit.py +0 -99
  80. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
  81. package/modules/localmodels/gateway_switch.py +0 -51
  82. package/modules/localmodels/library_floor.py +0 -78
  83. package/modules/localmodels/service_stop.py +0 -52
  84. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/WHEEL +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/entry_points.txt +0 -0
  86. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/NOTICE +0 -0
  87. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -13,10 +13,8 @@ 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
17
16
  import os
18
17
  import shutil
19
- from collections.abc import Iterator
20
18
  from dataclasses import dataclass
21
19
  from pathlib import Path
22
20
 
@@ -68,33 +66,58 @@ OOM = (
68
66
  "insufficient memory",
69
67
  "std::bad_alloc",
70
68
  "bad_alloc",
69
+ "vk::outofdevicememoryerror",
70
+ "failed to allocate kv cache",
71
+ )
72
+ UNSUPPORTED_ARCH = (
73
+ "unknown model architecture",
74
+ "unknown tensor type",
75
+ "unsupported gguf",
76
+ "gguf version",
77
+ "not supported by this build",
78
+ "unknown ftype",
79
+ "invalid tensor type",
80
+ "unknown architecture",
81
+ )
82
+ CORRUPT_WEIGHTS = (
83
+ "failed to load model from file",
84
+ "invalid magic",
85
+ "not a gguf",
86
+ "unexpected eof",
87
+ "corrupt",
88
+ "truncated",
89
+ "missing tensor",
90
+ "split file",
91
+ "sha256 mismatch",
92
+ "failed to read",
93
+ "invalid gguf",
71
94
  )
72
95
 
73
96
 
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
-
97
+ def classify_failure_text(text: str) -> tuple[str, str]:
98
+ """Classify server/load error text into ``(kind, error_code)``."""
99
+ lower = text.lower()
100
+ if any(word in lower for word in OOM):
101
+ return "oom", "OUT_OF_MEMORY"
102
+ if any(word in lower for word in UNSUPPORTED_ARCH):
103
+ return "unsupported_arch", "UNSUPPORTED_ARCHITECTURE"
104
+ if any(word in lower for word in CORRUPT_WEIGHTS):
105
+ return "corrupt", "CORRUPT_WEIGHTS"
106
+ return "unknown", "ENGINE_START_FAILED"
84
107
 
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
108
 
109
+ @dataclass
110
+ class LoadContext:
111
+ """Explicit load options and active elastic-retry state passed through the load call chain."""
90
112
 
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)
113
+ force: bool = False
114
+ ctx_override: int | None = None
115
+ use_jinja: bool = True
116
+ autostart: bool = True
117
+ elastic: ElasticPlan | None = None
118
+ base: str = ""
119
+ pool: str = ""
120
+ port: int = 0
98
121
 
99
122
 
100
123
  def _deploy_load_step(step: str) -> LoadStep:
@@ -206,6 +229,16 @@ def _load_posture_record(
206
229
  return doc
207
230
 
208
231
 
232
+ def _custom_flags(record: Record) -> tuple[bool, bool]:
233
+ """Return ``(use_jinja, autostart)`` derived from a record's optional custom metadata."""
234
+ custom = record.get("custom")
235
+ if custom is None:
236
+ return True, True
237
+ use_jinja = bool(custom.get("has_chat_template", True))
238
+ autostart = not bool(custom.get("standby_on_restart", True))
239
+ return use_jinja, autostart
240
+
241
+
209
242
  def _room(
210
243
  facts: HostFacts,
211
244
  model: Model,
@@ -213,9 +246,11 @@ def _room(
213
246
  freed: dict[str, int],
214
247
  *,
215
248
  force: bool = False,
249
+ ctx: int | None = None,
216
250
  ) -> ElasticPlan:
217
251
  """LOAD_NO_ROOM unless the model fits its pool under dual-tier admission after ``freed``."""
218
252
  now = library_pricing.live(facts, _reserved(model.id), freed)
253
+ use_jinja, _ = _custom_flags(record)
219
254
  try:
220
255
  return library_elastic.price_elastic(
221
256
  now,
@@ -225,6 +260,8 @@ def _room(
225
260
  library_pricing.entries(),
226
261
  allow_overcommit=True,
227
262
  force=force,
263
+ ctx_override=ctx,
264
+ use_jinja=use_jinja,
228
265
  )
229
266
  except deploy.AgentMemoryError as exc:
230
267
  raise _no_room_error(model, exc, record["pool"]) from None
@@ -258,11 +295,10 @@ def _port(facts: HostFacts) -> int:
258
295
 
259
296
  def _start_code(finished: FinishedRecord) -> str:
260
297
  failed = next((s for s in finished["steps"] if not s["ok"]), None)
261
- text = " ".join(
262
- str(x) for x in (finished.get("error"), failed and failed.get("stderr")) if x
263
- ).lower()
264
- if any(word in text for word in OOM):
265
- return "OUT_OF_MEMORY"
298
+ text = " ".join(str(x) for x in (finished.get("error"), failed and failed.get("stderr")) if x)
299
+ kind, code = classify_failure_text(text)
300
+ if kind != "unknown":
301
+ return code
266
302
  if failed is not None and failed["step"] == "verify":
267
303
  return "HEALTH_CHECK_FAILED"
268
304
  if failed is not None and failed["step"] in ("engine", "download"):
@@ -346,11 +382,11 @@ def _serve(
346
382
  run: Executor,
347
383
  port: int,
348
384
  handle: JobHandle,
349
- *,
350
- force: bool = False,
385
+ ctx: LoadContext,
351
386
  ) -> Record:
352
387
  base = base_of(record)
353
388
  now = library_pricing.live(facts, _reserved(model.id))
389
+ use_jinja, autostart = _custom_flags(record)
354
390
  try:
355
391
  elastic = library_elastic.price_elastic(
356
392
  now,
@@ -360,7 +396,9 @@ def _serve(
360
396
  library_pricing.entries(),
361
397
  port=port,
362
398
  allow_overcommit=True,
363
- force=force,
399
+ force=ctx.force,
400
+ ctx_override=ctx.ctx_override,
401
+ use_jinja=use_jinja,
364
402
  )
365
403
  except deploy.AgentMemoryError as exc: # after --unload: no longer a refusal
366
404
  raise _fail(record, _no_room_error(model, exc, record["pool"], failed=True)) from None
@@ -385,12 +423,21 @@ def _serve(
385
423
  ),
386
424
  ) from None
387
425
  plan = elastic.plan
426
+ if not autostart:
427
+ plan["service"]["autostart"] = False
388
428
  if missing := library_jobs.files_missing(plan):
389
429
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing), failed=True)
390
430
  steps = [str(step) for step in LOAD_STEPS]
391
431
  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)
432
+ start_ctx = LoadContext(
433
+ force=ctx.force,
434
+ ctx_override=ctx.ctx_override,
435
+ use_jinja=use_jinja,
436
+ autostart=autostart,
437
+ elastic=elastic,
438
+ base=base,
439
+ pool=record["pool"],
440
+ port=port,
394
441
  )
395
442
  if record.get("baseline_plan") is None:
396
443
  record["baseline_plan"] = record["plan"]
@@ -400,14 +447,12 @@ def _serve(
400
447
  handle.update("load", 0, len(steps), load_step="prepare")
401
448
  progress(model.id, "load", 0, len(steps), load_step="prepare")
402
449
  try:
403
- _start(model, record, plan, facts, run, steps, handle)
450
+ _start(model, record, plan, facts, run, steps, handle, start_ctx)
404
451
  except LibraryError:
405
452
  raise
406
453
  except BaseException: # interrupted (cancel, Ctrl-C) or crashed once the server may run
407
454
  _abandon(record, run)
408
455
  raise
409
- finally:
410
- _ELASTIC_CTX.reset(ctx_token)
411
456
  record["state"] = "loaded"
412
457
  record.pop("error", None)
413
458
  record.pop("note", None)
@@ -416,14 +461,14 @@ def _serve(
416
461
 
417
462
 
418
463
  def _next_oom_rung(
419
- model: Model, facts: HostFacts, ctx: _ElasticLoadContext, next_index: int
464
+ model: Model, facts: HostFacts, ctx: LoadContext, next_index: int
420
465
  ) -> ElasticPlan | None:
421
466
  """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):
467
+ if ctx.elastic is None or not ctx.elastic.ladder or next_index >= len(ctx.elastic.ladder):
423
468
  return None
424
469
  now = library_pricing.live(facts, _reserved(model.id))
425
470
  try:
426
- return library_elastic.price_elastic(
471
+ next_elastic = library_elastic.price_elastic(
427
472
  now,
428
473
  model,
429
474
  ctx.pool,
@@ -433,7 +478,12 @@ def _next_oom_rung(
433
478
  allow_overcommit=True,
434
479
  force=ctx.force,
435
480
  min_rung_index=next_index,
481
+ ctx_override=ctx.ctx_override,
482
+ use_jinja=ctx.use_jinja,
436
483
  )
484
+ if not ctx.autostart:
485
+ next_elastic.plan["service"]["autostart"] = False
486
+ return next_elastic
437
487
  except plan_envelope.PlanError:
438
488
  return None
439
489
 
@@ -470,6 +520,7 @@ def _start(
470
520
  run: Executor,
471
521
  steps: list[str],
472
522
  handle: JobHandle,
523
+ ctx: LoadContext,
473
524
  ) -> None:
474
525
  def seen(step: str, _event: object) -> None:
475
526
  done = steps.index(step)
@@ -485,7 +536,6 @@ def _start(
485
536
  _restore_baseline_plan(record)
486
537
  raise _fail(record, LibraryError("ENGINE_START_FAILED", str(exc))) from None
487
538
 
488
- ctx = _ELASTIC_CTX.get()
489
539
  oom_retries = 0
490
540
  while True:
491
541
  finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
@@ -502,7 +552,7 @@ def _start(
502
552
  raise _fail(
503
553
  record, LibraryError(code, detail, failed=error.failed, **error.fields)
504
554
  ) from None
505
- if code == "OUT_OF_MEMORY" and ctx is not None and oom_retries < MAX_OOM_RETRIES:
555
+ if code == "OUT_OF_MEMORY" and ctx.elastic is not None and oom_retries < MAX_OOM_RETRIES:
506
556
  next_elastic = _next_oom_rung(model, facts, ctx, ctx.elastic.rung_index + 1)
507
557
  if next_elastic is not None:
508
558
  oom_retries += 1
@@ -559,7 +609,9 @@ def _abandon(record: Record, run: Executor) -> None:
559
609
  library_state.save(record)
560
610
 
561
611
 
562
- def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts) -> None:
612
+ def _admit(
613
+ model: Model, record: Record, targets: list[Record], facts: HostFacts, ctx: LoadContext
614
+ ) -> None:
563
615
  """Under ``locked()``: LOAD_NO_ROOM unless the model fits its pool in ``facts`` (probed
564
616
  under the same lock), less every live load's reservation, plus what ``targets`` and a
565
617
  stale server of the model itself give back. The caller commits its own reservation before
@@ -578,7 +630,7 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
578
630
  freed["system"] = freed.get("system", 0) + library_pricing.host_ram_bytes(
579
631
  target["plan"], catalog
580
632
  )
581
- _room(facts, model, record, freed, force=_FORCE_LOAD.get())
633
+ _room(facts, model, record, freed, force=ctx.force, ctx=ctx.ctx_override)
582
634
 
583
635
 
584
636
  def _row(model: Model, base_dir: str) -> Row:
@@ -587,9 +639,18 @@ def _row(model: Model, base_dir: str) -> Row:
587
639
  return library_status.row(library_status.Library.read(library_jobs.probe(), base_dir), model)
588
640
 
589
641
 
590
- def load(model_id: str, base_dir: str, unload: list[str], *, force: bool = False) -> Row:
642
+ def load(
643
+ model_id: str,
644
+ base_dir: str,
645
+ unload: list[str],
646
+ *,
647
+ force: bool = False,
648
+ ctx: int | None = None,
649
+ ) -> Row:
591
650
  from localmodels import library_convert
592
651
 
652
+ if ctx is not None and (isinstance(ctx, bool) or ctx <= 0):
653
+ raise LibraryError("INVALID_STATE", "--ctx must be a positive integer")
593
654
  library_convert.convert_once()
594
655
  model = library_pricing.find(model_id, library_pricing.entries())
595
656
  # One entry per model, whatever spelling or repetition named it: each allocation is
@@ -597,8 +658,9 @@ def load(model_id: str, base_dir: str, unload: list[str], *, force: bool = False
597
658
  others = list(
598
659
  dict.fromkeys(library_pricing.find(m, library_pricing.entries()).id for m in unload)
599
660
  )
661
+ load_ctx = LoadContext(force=force, ctx_override=ctx)
600
662
  targets: list[Record] = []
601
- with library_state.locked(), _force_scope(force): # validate, admit and claim as one step
663
+ with library_state.locked(): # validate, admit and claim as one step
602
664
  library_state.refuse_busy(model.id, "load")
603
665
  record = library_state.load(model.id)
604
666
  if record is None:
@@ -619,7 +681,7 @@ def load(model_id: str, base_dir: str, unload: list[str], *, force: bool = False
619
681
  found = library_state.load(other)
620
682
  if other != model.id and found is not None and found["state"] != "idle":
621
683
  targets.append(found)
622
- _admit(model, record, targets, facts)
684
+ _admit(model, record, targets, facts, load_ctx)
623
685
  memory = record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"])
624
686
  port = _port(facts) # reserved with the claim: no concurrent load takes it too
625
687
  claims = [library_state.acquire("load", model.id, record["pool"], memory, [], port=port)]
@@ -644,7 +706,7 @@ def load(model_id: str, base_dir: str, unload: list[str], *, force: bool = False
644
706
  executor,
645
707
  port,
646
708
  handle,
647
- force=force,
709
+ load_ctx,
648
710
  )
649
711
  return _row(model, base_dir)
650
712
 
@@ -695,9 +757,9 @@ def remove(model_id: str, base_dir: str) -> Row:
695
757
  if record["state"] != "idle":
696
758
  stop(record, library_jobs.executor())
697
759
  with library_state.locked():
698
- library_jobs.delete_weights(
699
- library_jobs.dests(record["plan"]), library_jobs.in_use(model.id)
700
- )
760
+ weight_dests = library_jobs.dests(record["plan"])
761
+ library_jobs.delete_weights(weight_dests, library_jobs.in_use(model.id))
762
+ library_jobs.prune_empty_custom_dirs(weight_dests, base_of(record))
701
763
  _forget_deployment(record["plan"])
702
764
  if active_plan["name"] != record["plan"]["name"]:
703
765
  _forget_deployment(active_plan)
@@ -0,0 +1,315 @@
1
+ """Isolated conservative smoke-test for custom (or downloaded) library models.
2
+
3
+ Runs an ephemeral loopback ``llama-server`` at ``--ctx <4096|2048>`` and ``slots=1``, verifies a
4
+ minimal completion (``"Reply with OK."``, ``max_tokens: 16``), auto-retries once without
5
+ ``--jinja`` on chat-template errors, and ALWAYS shuts down and deletes the ephemeral deployment
6
+ before returning. Never touches active curated models, Bifrost, Pi ``models.json``, or
7
+ ``model-source.json``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import copy
14
+ import os
15
+ import shutil
16
+ import socket
17
+ import uuid
18
+ from pathlib import Path
19
+
20
+ from localmodels import (
21
+ app,
22
+ custom_hub,
23
+ hosts,
24
+ library_jobs,
25
+ library_pricing,
26
+ library_serve,
27
+ library_state,
28
+ library_status,
29
+ plan_envelope,
30
+ remote_ops,
31
+ stack_lifecycle,
32
+ )
33
+ from localmodels.library_model import LibraryError, Row, progress
34
+ from localmodels.library_state import Record, VerificationFailureRecord, VerificationRecord
35
+ from localmodels.probe import HostFacts
36
+ from localmodels.records import FinishedRecord, Plan
37
+
38
+ DIAGNOSTIC_LOG_LIMIT = 4000
39
+ _TEMPLATE_ERROR_PATTERNS = (
40
+ "chat template",
41
+ "chat_template",
42
+ "minja",
43
+ "jinja",
44
+ "template error",
45
+ "failed to parse template",
46
+ )
47
+
48
+
49
+ def _free_ephemeral_port(taken: set[int]) -> int:
50
+ for _ in range(16):
51
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
52
+ sock.bind(("127.0.0.1", 0))
53
+ port = int(sock.getsockname()[1])
54
+ if port not in taken:
55
+ return port
56
+ raise LibraryError("ENGINE_START_FAILED", "could not allocate an ephemeral loopback port")
57
+
58
+
59
+ def _replace_flag(argv: list[str], names: tuple[str, ...], flag: str, value: str) -> list[str]:
60
+ out: list[str] = []
61
+ i = 0
62
+ replaced = False
63
+ while i < len(argv):
64
+ if argv[i] in names:
65
+ if not replaced:
66
+ out.extend([flag, value])
67
+ replaced = True
68
+ i += 2
69
+ continue
70
+ out.append(argv[i])
71
+ i += 1
72
+ if not replaced:
73
+ out.extend([flag, value])
74
+ return out
75
+
76
+
77
+ def _strip_flags(argv: list[str], names: set[str], valued: set[str]) -> list[str]:
78
+ out: list[str] = []
79
+ i = 0
80
+ while i < len(argv):
81
+ tok = argv[i]
82
+ if tok in names:
83
+ i += 1
84
+ continue
85
+ if tok in valued:
86
+ i += 2
87
+ continue
88
+ out.append(tok)
89
+ i += 1
90
+ return out
91
+
92
+
93
+ def _build_smoke_plan(
94
+ record: Record,
95
+ facts: HostFacts,
96
+ base_dir: str,
97
+ port: int,
98
+ ctx: int,
99
+ *,
100
+ use_jinja: bool,
101
+ ) -> Plan:
102
+ """Build an ephemeral loopback smoke-test plan derived from ``record['plan']``."""
103
+ plan = copy.deepcopy(record["plan"])
104
+ token_id = uuid.uuid4().hex[:10]
105
+ smoke_name = f"smoke-{token_id}"
106
+ base = base_dir.rstrip("/")
107
+ deploy_dir = f"{base}/deployments/{smoke_name}"
108
+ api_key_file = f"{deploy_dir}/api-key"
109
+
110
+ argv = list(plan["service"]["argv"])
111
+ argv = _strip_flags(
112
+ argv,
113
+ names={"--jinja", "--no-warmup", "--mmproj-offload"},
114
+ valued={"--mmproj", "--chat-template-file", "--reasoning-budget"},
115
+ )
116
+ argv = _replace_flag(argv, ("-c", "--ctx-size"), "-c", str(ctx))
117
+ argv = _replace_flag(argv, ("-np", "--parallel"), "-np", "1")
118
+ argv = _replace_flag(argv, ("--host",), "--host", "127.0.0.1")
119
+ argv = _replace_flag(argv, ("--port",), "--port", str(port))
120
+ argv = _replace_flag(argv, ("--api-key-file",), "--api-key-file", api_key_file)
121
+ argv = _replace_flag(argv, ("--cache-ram",), "--cache-ram", "256")
122
+ if use_jinja:
123
+ argv.append("--jinja")
124
+ for flag in ("--metrics", "--slots", "--no-ui"):
125
+ if flag not in argv:
126
+ argv.append(flag)
127
+
128
+ service_kind = facts["service_manager"]["kind"]
129
+ plan["name"] = smoke_name
130
+ plan["service"] = {
131
+ "name": plan_envelope.service_name(base, smoke_name),
132
+ "kind": service_kind,
133
+ "deploy_dir": deploy_dir,
134
+ "port": port,
135
+ "bind": "127.0.0.1",
136
+ "argv": argv,
137
+ "env": dict(plan["service"].get("env") or {}),
138
+ "autostart": False,
139
+ }
140
+ plan["endpoint"] = {
141
+ **plan["endpoint"],
142
+ "base_url": f"http://127.0.0.1:{port}/v1",
143
+ }
144
+ plan["launch"] = {
145
+ **plan["launch"],
146
+ "window": ctx,
147
+ "slots": 1,
148
+ "smoke": True,
149
+ "vision": False,
150
+ }
151
+ return plan
152
+
153
+
154
+ def _read_server_log(deploy_dir: str) -> str:
155
+ log_path = Path(os.path.expanduser(deploy_dir)) / "server.log"
156
+ try:
157
+ raw = log_path.read_bytes()
158
+ except OSError:
159
+ return ""
160
+ return raw[-16384:].decode("utf-8", errors="replace")
161
+
162
+
163
+ def _cleanup_smoke_plan(plan: Plan) -> None:
164
+ run = library_jobs.executor()
165
+ with contextlib.suppress(Exception):
166
+ run.run_action("remove", stack_lifecycle.plan_params(plan), timeout=120)
167
+ with contextlib.suppress(Exception):
168
+ hosts.delete_record(
169
+ hosts.LOCAL_ID, plan["name"], purged=True, deploy_dir=plan["service"]["deploy_dir"]
170
+ )
171
+ deploy_dir = Path(os.path.expanduser(plan["service"]["deploy_dir"]))
172
+ if deploy_dir.parent.name == "deployments" and deploy_dir.is_dir():
173
+ shutil.rmtree(deploy_dir, ignore_errors=True)
174
+
175
+
176
+ def _is_template_error(text: str) -> bool:
177
+ lower = text.lower()
178
+ return any(pattern in lower for pattern in _TEMPLATE_ERROR_PATTERNS)
179
+
180
+
181
+ def _diagnostic_text(finished: FinishedRecord, server_log: str) -> str:
182
+ failed = next((s for s in finished["steps"] if not s["ok"]), None)
183
+ parts = [
184
+ str(finished.get("error") or ""),
185
+ str(failed.get("stderr") or "") if failed is not None else "",
186
+ server_log,
187
+ ]
188
+ combined = "\n".join(part.strip() for part in parts if part and part.strip())
189
+ redacted = custom_hub.redact_secrets(remote_ops.redact_text(combined))
190
+ return redacted[-DIAGNOSTIC_LOG_LIMIT:]
191
+
192
+
193
+ def _run_attempt(
194
+ model_id: str,
195
+ smoke_plan: Plan,
196
+ ) -> tuple[FinishedRecord, str]:
197
+ def on_event(step: str, _event: object) -> None:
198
+ done = 2 if step == "verify" else 1
199
+ progress(model_id, "smoke_test", done, 3)
200
+
201
+ server_log = ""
202
+ try:
203
+ finished = app.run_deploy(hosts.LOCAL_ID, smoke_plan, on_event=on_event)
204
+ if not finished["ok"]:
205
+ server_log = _read_server_log(smoke_plan["service"]["deploy_dir"])
206
+ return finished, server_log
207
+ finally:
208
+ _cleanup_smoke_plan(smoke_plan)
209
+
210
+
211
+ def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
212
+ """Run an isolated ephemeral smoke-test at ``ctx`` tokens and persist ``verification``."""
213
+ if isinstance(ctx, bool) or ctx <= 0:
214
+ raise LibraryError("INVALID_STATE", "--ctx must be a positive integer")
215
+ model = library_pricing.find(model_id, library_pricing.entries())
216
+ with library_state.locked():
217
+ library_state.refuse_busy(model.id, "smoke_test")
218
+ record = library_state.load(model.id)
219
+ if record is None:
220
+ raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
221
+ if missing := library_jobs.files_missing(record["plan"]):
222
+ raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing))
223
+ facts = library_jobs.probe()
224
+ taken = {
225
+ r["plan"]["service"]["port"] for r in library_state.records() if r["state"] != "idle"
226
+ }
227
+ taken.update(
228
+ int(j.get("port", 0))
229
+ for j, alive in library_state.jobs().values()
230
+ if alive and j.get("port")
231
+ )
232
+ port = _free_ephemeral_port(taken)
233
+ prior_verification = record.get("verification")
234
+ record["verification"] = {"status": "running", "context_tokens": ctx}
235
+ library_state.save(record)
236
+ job = library_state.acquire("smoke_test", model.id, record["pool"], 0, [], port=port)
237
+
238
+ record_base = record.get("base_dir") or base_dir
239
+ custom_meta = record.get("custom")
240
+ use_jinja = (
241
+ bool(custom_meta.get("has_chat_template", True)) if custom_meta is not None else True
242
+ )
243
+ progress(model.id, "smoke_test", 0, 3)
244
+ with library_state.held([job]):
245
+ try:
246
+ smoke_plan = _build_smoke_plan(
247
+ record, facts, record_base, port, ctx, use_jinja=use_jinja
248
+ )
249
+ finished, server_log = _run_attempt(model.id, smoke_plan)
250
+ jinja_fallback = False
251
+ if not finished["ok"] and use_jinja:
252
+ diag = _diagnostic_text(finished, server_log)
253
+ if _is_template_error(diag):
254
+ jinja_fallback = True
255
+ retry_plan = _build_smoke_plan(
256
+ record, facts, record_base, port, ctx, use_jinja=False
257
+ )
258
+ finished, server_log = _run_attempt(model.id, retry_plan)
259
+ except BaseException:
260
+ with library_state.locked():
261
+ current = library_state.load(model.id)
262
+ if current is not None:
263
+ if prior_verification is not None:
264
+ current["verification"] = prior_verification
265
+ else:
266
+ current["verification"] = {"status": "untested"}
267
+ library_state.save(current)
268
+ raise
269
+
270
+ now_iso = plan_envelope.utc_now()
271
+ if finished["ok"]:
272
+ progress(model.id, "smoke_test", 3, 3)
273
+ verified: VerificationRecord = {
274
+ "status": "verified",
275
+ "context_tokens": ctx,
276
+ "tested_at": now_iso,
277
+ }
278
+ with library_state.locked():
279
+ current = library_state.load(model.id)
280
+ if current is not None:
281
+ current["verification"] = verified
282
+ if jinja_fallback and isinstance(current.get("custom"), dict):
283
+ current["custom"]["has_chat_template"] = False
284
+ library_state.save(current)
285
+ else:
286
+ diag_log = _diagnostic_text(finished, server_log)
287
+ kind, code = library_serve.classify_failure_text(diag_log)
288
+ failure: VerificationFailureRecord = {
289
+ "kind": kind,
290
+ "code": code,
291
+ "context_tokens": ctx,
292
+ "can_retry_lower_ctx": kind == "oom" and ctx > 2048,
293
+ "can_redownload": kind == "corrupt",
294
+ }
295
+ if diag_log:
296
+ failure["diagnostic_log"] = diag_log
297
+ failed_ver: VerificationRecord = {
298
+ "status": "failed",
299
+ "context_tokens": ctx,
300
+ "tested_at": now_iso,
301
+ "failure": failure,
302
+ }
303
+ with library_state.locked():
304
+ current = library_state.load(model.id)
305
+ if current is not None:
306
+ current["verification"] = failed_ver
307
+ library_state.save(current)
308
+ summary = custom_hub.redact_secrets(
309
+ remote_ops.redact_text(str(finished.get("error") or "smoke test failed"))
310
+ )
311
+ raise LibraryError(code, summary, failed=True)
312
+
313
+ return library_status.model_row(
314
+ library_status.Library.read(library_jobs.probe(), base_dir), model.id
315
+ )