@simplexai/localmodels-linux-arm64 0.1.0-dev.104 → 0.1.0-dev.106

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 (85) hide show
  1. package/README.md +1 -1
  2. package/bootstrap.identity +1 -1
  3. package/bootstrap.sha256 +84 -82
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +204 -86
  6. package/modules/localmodels/apple_sensors.py +23 -0
  7. package/modules/localmodels/approval.py +25 -2
  8. package/modules/localmodels/catalog.json +454 -31
  9. package/modules/localmodels/catalog.py +11 -0
  10. package/modules/localmodels/catalog_recipes.py +61 -3
  11. package/modules/localmodels/cli_help.py +10 -0
  12. package/modules/localmodels/cli_parser.py +313 -230
  13. package/modules/localmodels/component.py +20 -2
  14. package/modules/localmodels/custom_probe.py +4 -2
  15. package/modules/localmodels/deploy.py +11 -1
  16. package/modules/localmodels/engine_adapters/suite_plan.py +21 -21
  17. package/modules/localmodels/host_sensors.py +25 -2
  18. package/modules/localmodels/hosts.py +26 -5
  19. package/modules/localmodels/library_cli.py +34 -16
  20. package/modules/localmodels/library_custom.py +9 -1
  21. package/modules/localmodels/library_direct.py +41 -1
  22. package/modules/localmodels/library_jobs.py +23 -4
  23. package/modules/localmodels/library_model.py +146 -1
  24. package/modules/localmodels/library_order.py +175 -69
  25. package/modules/localmodels/library_poly.py +42 -11
  26. package/modules/localmodels/library_presentation.py +485 -0
  27. package/modules/localmodels/library_pricing.py +3 -1
  28. package/modules/localmodels/library_serve.py +208 -3
  29. package/modules/localmodels/library_state.py +47 -10
  30. package/modules/localmodels/library_status.py +29 -16
  31. package/modules/localmodels/llm_rank.py +9 -3
  32. package/modules/localmodels/plan_envelope.py +11 -2
  33. package/modules/localmodels/probe.py +34 -7
  34. package/modules/localmodels/quant_formats.py +9 -2
  35. package/modules/localmodels/records.py +19 -2
  36. package/modules/localmodels/remote_ops_verify.py +91 -24
  37. package/modules/localmodels/runtime_index.py +303 -0
  38. package/modules/localmodels/setup_inspection.py +22 -3
  39. package/modules/localmodels/sidecar_http.py +6 -2
  40. package/modules/localmodels/speech_cli.py +23 -17
  41. package/modules/localmodels/speech_jobs.py +4 -0
  42. package/modules/localmodels/speech_model.py +1 -1
  43. package/modules/localmodels/speech_serve.py +9 -2
  44. package/modules/localmodels/speech_server.py +3 -0
  45. package/modules/localmodels/stack_args.py +270 -139
  46. package/modules/localmodels/stack_auto.py +90 -5
  47. package/modules/localmodels/stack_cli.py +117 -116
  48. package/modules/localmodels/stack_compose.py +5 -1
  49. package/modules/localmodels/stack_debug.py +14 -4
  50. package/modules/localmodels/stack_down.py +2 -0
  51. package/modules/localmodels/stack_hardware.py +14 -12
  52. package/modules/localmodels/stack_mlx.py +8 -1
  53. package/modules/localmodels/stack_picks.py +19 -20
  54. package/modules/localmodels/stack_plan.py +3 -2
  55. package/modules/localmodels/stack_review.py +28 -7
  56. package/modules/localmodels/stack_suite.py +11 -9
  57. package/modules/localmodels/stack_up.py +2 -0
  58. package/modules/localmodels/stack_view.py +180 -35
  59. package/modules/localmodels/stack_view_demo.py +2 -0
  60. package/modules/localmodels/stack_view_gpu.py +36 -2
  61. package/modules/localmodels/stack_view_schema.py +26 -3
  62. package/modules/localmodels/stack_view_slots.py +3 -1
  63. package/modules/localmodels/stack_view_telemetry.py +90 -4
  64. package/modules/localmodels/stack_view_tick.py +246 -40
  65. package/modules/localmodels/stack_view_words.py +7 -0
  66. package/modules/localmodels/stack_whatif_html.py +9 -12
  67. package/modules/localmodels/suite.py +129 -2
  68. package/modules/localmodels/telemetry_math.py +458 -18
  69. package/modules/localmodels/transport.py +8 -1
  70. package/modules/localmodels/tts_cli.py +29 -25
  71. package/modules/localmodels/tts_jobs.py +5 -0
  72. package/modules/localmodels/tts_serve.py +9 -2
  73. package/modules/localmodels/tts_sidecar.py +3 -0
  74. package/modules/localmodels/web/whatif/app.js +1 -1
  75. package/modules/localmodels/web/whatif/sim.js +8 -14
  76. package/modules/localmodels/win_probe.py +89 -16
  77. package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev106.dist-info}/METADATA +1 -1
  78. package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev106.dist-info}/RECORD +80 -78
  79. package/package.json +1 -1
  80. package/tool.json +1 -1
  81. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev106.dist-info}/WHEEL +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev106.dist-info}/entry_points.txt +0 -0
  83. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev106.dist-info}/licenses/LICENSE +0 -0
  84. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev106.dist-info}/licenses/NOTICE +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev106.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -13,6 +13,7 @@ loopback endpoint registration. Unload removes the service; the weights stay.
13
13
  from __future__ import annotations
14
14
 
15
15
  import contextlib
16
+ import math
16
17
  import os
17
18
  import shutil
18
19
  import time
@@ -35,6 +36,7 @@ from localmodels import (
35
36
  library_status,
36
37
  metal,
37
38
  plan_envelope,
39
+ runtime_index,
38
40
  sidecar_state,
39
41
  speech_admission,
40
42
  speech_state,
@@ -44,7 +46,14 @@ from localmodels import (
44
46
  tts_state,
45
47
  )
46
48
  from localmodels.library_elastic import ElasticPlan, ElasticRoomError
47
- from localmodels.library_model import LibraryError, LoadStep, Row, problem_from_error, progress
49
+ from localmodels.library_model import (
50
+ LibraryError,
51
+ LoadBreakdownMs,
52
+ LoadStep,
53
+ Row,
54
+ problem_from_error,
55
+ progress,
56
+ )
48
57
  from localmodels.library_pricing import Model
49
58
  from localmodels.library_state import Job, JobHandle, LoadPosture, PostureSnapshot, Record
50
59
  from localmodels.planning import memory_pools
@@ -56,6 +65,29 @@ LOAD_STEPS = deploy.STEPS
56
65
  MAX_OOM_RETRIES = 2
57
66
  _METAL_UNLOAD_SETTLE_POLLS = 6
58
67
  _METAL_UNLOAD_SETTLE_S = 0.5
68
+ _ENGINE_LOG_TAIL_BYTES = 65536
69
+ _LOAD_TIMING_KEYS = (
70
+ "loaded_at",
71
+ "load_duration_ms",
72
+ "load_breakdown_ms",
73
+ "cold_load",
74
+ "warm_first_s",
75
+ "warm_second_s",
76
+ )
77
+ _COLD_LOG_MARKERS = (
78
+ "cold_load=true",
79
+ "cold start",
80
+ "cold load",
81
+ "cache cold",
82
+ "page cache miss",
83
+ )
84
+ _WARM_LOG_MARKERS = (
85
+ "cold_load=false",
86
+ "warm start",
87
+ "warm load",
88
+ "cache warm",
89
+ "page cache hit",
90
+ )
59
91
  OOM = (
60
92
  "out of memory",
61
93
  "cudamalloc failed",
@@ -349,10 +381,116 @@ def _forget_deployment(plan: Plan) -> None:
349
381
  )
350
382
 
351
383
 
384
+ def _clear_load_timing(record: Record) -> None:
385
+ """Drop per-load lifecycle timing fields without forgetting ``ever_loaded``."""
386
+ for key in _LOAD_TIMING_KEYS:
387
+ record.pop(key, None) # type: ignore[misc]
388
+
389
+
390
+ def _finite_nonneg_float(value: object) -> float | None:
391
+ if isinstance(value, bool) or not isinstance(value, int | float):
392
+ return None
393
+ f = float(value)
394
+ return f if math.isfinite(f) and f >= 0 else None
395
+
396
+
397
+ def _read_engine_log_tail(plan: Plan) -> str:
398
+ """Read a bounded tail of the deployment's server.log for cold/warm markers."""
399
+ log_path = Path(os.path.expanduser(plan["service"]["deploy_dir"])) / "server.log"
400
+ try:
401
+ with log_path.open("rb") as fh:
402
+ fh.seek(0, os.SEEK_END)
403
+ size = fh.tell()
404
+ fh.seek(max(0, size - _ENGINE_LOG_TAIL_BYTES))
405
+ return fh.read().decode("utf-8", errors="replace")
406
+ except OSError:
407
+ return ""
408
+
409
+
410
+ def detect_cold_load(
411
+ *,
412
+ log_text: str = "",
413
+ first_load: bool = False,
414
+ warm_first_s: float | None = None,
415
+ warm_second_s: float | None = None,
416
+ ) -> bool | None:
417
+ """Return True/False when cold vs warm load is reliably determinable, else None."""
418
+ if log_text:
419
+ for line in reversed(log_text.splitlines()):
420
+ low = line.lower()
421
+ if any(marker in low for marker in _COLD_LOG_MARKERS):
422
+ return True
423
+ if any(marker in low for marker in _WARM_LOG_MARKERS):
424
+ return False
425
+ if first_load:
426
+ return True
427
+ if warm_first_s is not None and warm_second_s is not None and warm_second_s > 0:
428
+ if warm_first_s >= warm_second_s * 2.0 and (warm_first_s - warm_second_s) >= 0.5:
429
+ return True
430
+ if warm_first_s <= warm_second_s * 1.25 and (warm_first_s - warm_second_s) <= 0.25:
431
+ return False
432
+ return None
433
+
434
+
435
+ def _build_load_breakdown(
436
+ finished: FinishedRecord,
437
+ *,
438
+ pre_deploy_ms: int,
439
+ warm_ms: int,
440
+ register_ms: int,
441
+ ) -> LoadBreakdownMs:
442
+ breakdown: LoadBreakdownMs = {}
443
+ step_prepare_ms = sum(
444
+ int(s["duration_ms"])
445
+ for s in finished["steps"]
446
+ if s["step"] in ("engine", "download", "install", "start")
447
+ and isinstance(s.get("duration_ms"), int)
448
+ and not isinstance(s.get("duration_ms"), bool)
449
+ and int(s["duration_ms"]) >= 0
450
+ )
451
+ breakdown["prepare_ms"] = max(0, pre_deploy_ms + step_prepare_ms)
452
+
453
+ verify_step = next((s for s in finished["steps"] if s["step"] == "verify"), None)
454
+ verify_res = verify_step.get("result") if verify_step is not None else None
455
+ verify_step_ms = (
456
+ int(verify_step["duration_ms"])
457
+ if verify_step is not None
458
+ and isinstance(verify_step.get("duration_ms"), int)
459
+ and not isinstance(verify_step.get("duration_ms"), bool)
460
+ and int(verify_step["duration_ms"]) >= 0
461
+ else None
462
+ )
463
+ engine_load_ms: int | None = None
464
+ touch_verify_ms: int | None = None
465
+ if isinstance(verify_res, dict):
466
+ raw_hw = verify_res.get("health_wait_ms")
467
+ if isinstance(raw_hw, int) and not isinstance(raw_hw, bool) and raw_hw >= 0:
468
+ engine_load_ms = raw_hw
469
+ raw_touch = verify_res.get("touch_ms")
470
+ if isinstance(raw_touch, int) and not isinstance(raw_touch, bool) and raw_touch >= 0:
471
+ touch_verify_ms = raw_touch
472
+ else:
473
+ raw_sec = verify_res.get("seconds")
474
+ if isinstance(raw_sec, int | float) and not isinstance(raw_sec, bool) and raw_sec >= 0:
475
+ touch_verify_ms = max(0, round(float(raw_sec) * 1000))
476
+ if engine_load_ms is None and verify_step_ms is not None and touch_verify_ms is not None:
477
+ engine_load_ms = max(0, verify_step_ms - touch_verify_ms)
478
+ if engine_load_ms is not None:
479
+ breakdown["engine_load_ms"] = engine_load_ms
480
+ if touch_verify_ms is not None:
481
+ breakdown["touch_verify_ms"] = touch_verify_ms
482
+
483
+ breakdown["warm_ms"] = max(0, warm_ms)
484
+ breakdown["register_ms"] = max(0, register_ms)
485
+ return breakdown
486
+
487
+
352
488
  def _fail(record: Record, error: LibraryError) -> LibraryError:
353
489
  record["state"] = "failed"
354
490
  record["error"] = problem_from_error(error)
491
+ _clear_load_timing(record)
355
492
  library_state.save(record)
493
+ runtime_index.refresh()
356
494
  return error
357
495
 
358
496
 
@@ -375,15 +513,18 @@ def stop(record: Record, run: Executor) -> None:
375
513
  elif had_registration:
376
514
  library_state.save(record)
377
515
  record.pop("load_posture", None)
516
+ _clear_load_timing(record)
378
517
  if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
379
518
  _remove_service(record["plan"], run)
380
519
  record["state"] = "idle"
381
520
  for key in ("registration", "error", "note"):
382
521
  record.pop(key, None) # type: ignore[misc]
522
+ _clear_load_timing(record)
383
523
  library_state.save(record)
384
524
  if (baseline := record.pop("baseline_plan", None)) is not None:
385
525
  record["plan"] = baseline
386
526
  library_state.save(record)
527
+ runtime_index.refresh()
387
528
 
388
529
 
389
530
  def demote_speech_if_holding_pool(state_dir: Path | None, pool_id: str) -> bool:
@@ -477,6 +618,8 @@ def _serve(
477
618
  handle: JobHandle,
478
619
  ctx: LoadContext,
479
620
  ) -> Record:
621
+ load_started = time.monotonic()
622
+ first_load = not bool(record.get("ever_loaded") or record.get("tokens_per_second") is not None)
480
623
  base = base_of(record)
481
624
  use_jinja, autostart = _custom_flags(record)
482
625
  facts, elastic = _serve_elastic_plan(model, record, facts, base, port, ctx, use_jinja=use_jinja)
@@ -501,20 +644,34 @@ def _serve(
501
644
  record["baseline_plan"] = record["plan"]
502
645
  record["plan"], record["state"] = plan, "starting"
503
646
  record.pop("error", None)
647
+ _clear_load_timing(record)
504
648
  library_state.save(record) # the server about to start is recorded before it exists
505
649
  handle.update("load", 0, len(steps), load_step="prepare")
506
650
  progress(model.id, "load", 0, len(steps), load_step="prepare")
507
651
  try:
508
- _start(model, record, plan, facts, run, steps, handle, start_ctx)
652
+ _start(
653
+ model,
654
+ record,
655
+ plan,
656
+ facts,
657
+ run,
658
+ steps,
659
+ handle,
660
+ start_ctx,
661
+ load_started=load_started,
662
+ first_load=first_load,
663
+ )
509
664
  except LibraryError:
510
665
  raise
511
666
  except BaseException: # interrupted (cancel, Ctrl-C) or crashed once the server may run
512
667
  _abandon(record, run)
513
668
  raise
514
669
  record["state"] = "loaded"
670
+ record["ever_loaded"] = True
515
671
  record.pop("error", None)
516
672
  record.pop("note", None)
517
673
  library_state.save(record)
674
+ runtime_index.refresh()
518
675
  return record
519
676
 
520
677
 
@@ -555,7 +712,12 @@ def _start(
555
712
  steps: list[str],
556
713
  handle: JobHandle,
557
714
  ctx: LoadContext,
715
+ *,
716
+ load_started: float | None = None,
717
+ first_load: bool = False,
558
718
  ) -> None:
719
+ started_at = time.monotonic() if load_started is None else load_started
720
+
559
721
  def seen(step: str, _event: object) -> None:
560
722
  done = steps.index(step)
561
723
  load_step = _deploy_load_step(step)
@@ -570,6 +732,7 @@ def _start(
570
732
  _restore_baseline_plan(record)
571
733
  raise _fail(record, LibraryError("ENGINE_START_FAILED", str(exc))) from None
572
734
 
735
+ pre_deploy_ms = max(0, round((time.monotonic() - started_at) * 1000))
573
736
  oom_retries = 0
574
737
  while True:
575
738
  finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
@@ -609,20 +772,58 @@ def _start(
609
772
  progress(model.id, "load", len(steps), len(steps), load_step="load")
610
773
  handle.update("warm", 0, 2, load_step="warm")
611
774
  progress(model.id, "warm", 0, 2, load_step="warm")
612
- speed = stack_warm.warm_llm(plan)["decode_tok_s"]
775
+ warm_started = time.monotonic()
776
+ warm_res = stack_warm.warm_llm(plan)
777
+ speed = warm_res.get("decode_tok_s")
778
+ first_s = _finite_nonneg_float(warm_res.get("first_s"))
779
+ second_s = _finite_nonneg_float(warm_res.get("second_s"))
613
780
  prefill = stack_warm.prompt_speed(plan) # one more request; warm still counts two steps
781
+ warm_wall_ms = max(0, round((time.monotonic() - warm_started) * 1000))
782
+ reported_warm_ms = (
783
+ max(0, round((first_s + second_s) * 1000))
784
+ if first_s is not None and second_s is not None
785
+ else 0
786
+ )
787
+ warm_ms = max(warm_wall_ms, reported_warm_ms)
614
788
  handle.update("warm", 2, 2, load_step="warm")
615
789
  progress(model.id, "warm", 2, 2, load_step="warm")
616
790
  if speed is not None:
617
791
  record["tokens_per_second"] = float(speed)
792
+ if first_s is not None:
793
+ record["warm_first_s"] = round(first_s, 4)
794
+ else:
795
+ record.pop("warm_first_s", None)
796
+ if second_s is not None:
797
+ record["warm_second_s"] = round(second_s, 4)
798
+ else:
799
+ record.pop("warm_second_s", None)
618
800
  if prefill is not None:
619
801
  record["prompt_tokens_per_second"] = prefill
620
802
  else: # the last load's measurement, or none
621
803
  record.pop("prompt_tokens_per_second", None)
804
+ reg_started = time.monotonic()
622
805
  reg = library_direct.registration(model.id, plan)
623
806
  record["registration"] = reg
624
807
  if pi_selector := reg.get("pi_model"):
625
808
  record["pi_model"] = pi_selector
809
+ register_ms = max(0, round((time.monotonic() - reg_started) * 1000))
810
+ breakdown = _build_load_breakdown(
811
+ finished,
812
+ pre_deploy_ms=pre_deploy_ms,
813
+ warm_ms=warm_ms,
814
+ register_ms=register_ms,
815
+ )
816
+ total_wall_ms = max(0, round((time.monotonic() - started_at) * 1000))
817
+ breakdown_sum = sum(v for v in breakdown.values() if isinstance(v, int))
818
+ record["loaded_at"] = plan_envelope.utc_now().replace("+00:00", "Z")
819
+ record["load_breakdown_ms"] = breakdown
820
+ record["load_duration_ms"] = max(total_wall_ms, breakdown_sum)
821
+ record["cold_load"] = detect_cold_load(
822
+ log_text=_read_engine_log_tail(plan),
823
+ first_load=first_load,
824
+ warm_first_s=first_s,
825
+ warm_second_s=second_s,
826
+ )
626
827
  library_state.save(record)
627
828
 
628
829
 
@@ -799,6 +1000,7 @@ def load(
799
1000
  load_ctx = LoadContext(force=force, ctx_override=ctx)
800
1001
  attempt = _admit_and_claim(model, others, base_dir, load_ctx)
801
1002
  if attempt.already_loaded is not None:
1003
+ runtime_index.refresh()
802
1004
  return attempt.already_loaded
803
1005
  assert attempt.claimed is not None
804
1006
  record, targets, facts, port, claims = attempt.claimed
@@ -842,6 +1044,8 @@ def unload(model_id: str, base_dir: str) -> Row:
842
1044
  with library_state.held([job]):
843
1045
  if record["state"] != "idle":
844
1046
  stop(record, library_jobs.executor())
1047
+ else:
1048
+ runtime_index.refresh()
845
1049
  return _row(model, base_dir)
846
1050
 
847
1051
 
@@ -860,4 +1064,5 @@ def remove(model_id: str, base_dir: str) -> Row:
860
1064
  if active_plan["name"] != record["plan"]["name"]:
861
1065
  _forget_deployment(active_plan)
862
1066
  library_state.forget(model.id)
1067
+ runtime_index.refresh()
863
1068
  return _row(model, base_dir)
@@ -15,6 +15,7 @@ import contextlib
15
15
  import json
16
16
  import os
17
17
  import re
18
+ import threading
18
19
  import uuid
19
20
  from collections.abc import Iterator
20
21
  from contextlib import contextmanager
@@ -23,7 +24,7 @@ from typing import Literal, TypedDict
23
24
 
24
25
  from localmodels import hosts, process_identity
25
26
  from localmodels.contracts import decode
26
- from localmodels.library_model import LibraryError, Note, Problem
27
+ from localmodels.library_model import LibraryError, LoadBreakdownMs, Note, Problem
27
28
  from localmodels.plan_envelope import utc_now
28
29
  from localmodels.records import Plan
29
30
 
@@ -144,6 +145,13 @@ class Record(_RecordRequired, total=False):
144
145
  custom: CustomMeta # custom hub model metadata (absent for curated models)
145
146
  verification: VerificationRecord # smoke-test verification state (custom models)
146
147
  catalog_entry: dict[str, object] # schema-3 entry snapshot for custom models
148
+ loaded_at: str | None # RFC3339 UTC timestamp when the active load became ready
149
+ load_duration_ms: int | None # total load duration in ms for the active load
150
+ load_breakdown_ms: LoadBreakdownMs | None # per-phase timing breakdown in ms
151
+ cold_load: bool | None # whether the active load was cold (None when indeterminate)
152
+ warm_first_s: float | None # wall seconds of warm_llm() first request
153
+ warm_second_s: float | None # wall seconds of warm_llm() second request
154
+ ever_loaded: bool # True once the model has completed at least one load on this host
147
155
 
148
156
 
149
157
  class _JobSince20261113(TypedDict, total=False):
@@ -178,8 +186,19 @@ class Job(_JobSince20261113):
178
186
  updated_at: str
179
187
 
180
188
 
181
- def root() -> Path:
182
- return hosts.state_dir() / "library"
189
+ _HELD_LOCKS = threading.local()
190
+
191
+
192
+ def _held_locks() -> set[str]:
193
+ held: set[str] | None = getattr(_HELD_LOCKS, "keys", None)
194
+ if held is None:
195
+ held = set()
196
+ _HELD_LOCKS.keys = held
197
+ return held
198
+
199
+
200
+ def root(state_dir: Path | None = None) -> Path:
201
+ return (hosts.state_dir() if state_dir is None else state_dir) / "library"
183
202
 
184
203
 
185
204
  def _file(model: str) -> str:
@@ -200,10 +219,19 @@ def pid_path(model: str) -> Path:
200
219
 
201
220
  @contextmanager
202
221
  def locked(state_dir: Path | None = None) -> Iterator[None]:
203
- """The one lock every state transition holds, briefly."""
204
- lock_root = root() if state_dir is None else state_dir / "library"
205
- with hosts.file_lock(lock_root / ".lock"):
222
+ """The one lock every state transition holds, briefly (re-entrant per thread)."""
223
+ lock_file = root(state_dir) / ".lock"
224
+ resolved = os.path.realpath(lock_file)
225
+ held = _held_locks()
226
+ if resolved in held:
206
227
  yield
228
+ return
229
+ with hosts.file_lock(lock_file):
230
+ held.add(resolved)
231
+ try:
232
+ yield
233
+ finally:
234
+ held.discard(resolved)
207
235
 
208
236
 
209
237
  def load(model: str) -> Record | None:
@@ -214,9 +242,9 @@ def load(model: str) -> Record | None:
214
242
  return None
215
243
 
216
244
 
217
- def records() -> list[Record]:
245
+ def records(state_dir: Path | None = None) -> list[Record]:
218
246
  found = []
219
- for path in sorted((root() / "models").glob("*.json")):
247
+ for path in sorted((root(state_dir) / "models").glob("*.json")):
220
248
  try:
221
249
  found.append(decode(json.loads(path.read_text(encoding="utf-8")), Record))
222
250
  except (OSError, ValueError):
@@ -336,6 +364,14 @@ def fail_job(job: Job, error: Problem) -> None:
336
364
  path.unlink(missing_ok=True)
337
365
 
338
366
 
367
+ def _may_persist_job(job: Job) -> bool:
368
+ """Under ``locked()``: True only while ``job`` still owns its model slot and is active."""
369
+ found = read_job(job["model"])
370
+ if found is None or found.get("id") != job.get("id"):
371
+ return False
372
+ return not found.get("error") and not cancelled(job)
373
+
374
+
339
375
  class JobHandle:
340
376
  """This process's job: progress written for ``status``, at most once a second."""
341
377
 
@@ -416,8 +452,9 @@ class JobHandle:
416
452
  if changed or now - self._written >= JOB_WRITE_EVERY_S or done >= total:
417
453
  self._written = now
418
454
  self.job["updated_at"] = utc_now()
419
- with contextlib.suppress(OSError):
420
- hosts.save_private(job_path(self.job["model"]), self.job)
455
+ with contextlib.suppress(OSError), locked():
456
+ if _may_persist_job(self.job):
457
+ hosts.save_private(job_path(self.job["model"]), self.job)
421
458
 
422
459
 
423
460
  def refuse_busy(model: str, kind: str) -> None:
@@ -20,6 +20,7 @@ from localmodels import (
20
20
  library_direct,
21
21
  library_elastic,
22
22
  library_order,
23
+ library_presentation,
23
24
  library_pricing,
24
25
  library_state,
25
26
  metal,
@@ -64,6 +65,7 @@ from localmodels.library_model import (
64
65
  VerificationFailureKind,
65
66
  VerificationMeta,
66
67
  VerificationStatus,
68
+ apply_load_lifecycle,
67
69
  disambiguate_row_names,
68
70
  sanitize_problem,
69
71
  )
@@ -381,8 +383,11 @@ def card(model: Model, vision_on: bool) -> Row:
381
383
  }
382
384
  if HUB_REPO.fullmatch(entry.repo):
383
385
  found["source_url"] = f"https://huggingface.co/{entry.repo}"
384
- if vision_on:
385
- found["capabilities"] = ["vision"]
386
+ caps = [c for c in entry.capabilities if c != "vision" or vision_on]
387
+ if vision_on and "vision" not in caps:
388
+ caps = ["vision", *caps]
389
+ if caps:
390
+ found["capabilities"] = caps
386
391
  return cast(Row, {k: v for k, v in found.items() if v})
387
392
 
388
393
 
@@ -484,15 +489,14 @@ def _apply_engine_meta(lib: Library, found: Row, model: Model, plan: Plan | None
484
489
  )
485
490
  raw_slots = plan["launch"].get("slots") if plan is not None else None
486
491
  parsed_slots = int(str(raw_slots)) if raw_slots is not None else 0
487
- found["concurrency"] = (
488
- parsed_slots
489
- if parsed_slots >= 1
490
- else (
491
- 2
492
- if engine == "polystrata"
493
- else (1 if engine == "strata" else library_pricing.posture().slots)
494
- )
495
- )
492
+ if parsed_slots >= 1:
493
+ concurrency = parsed_slots
494
+ elif engine == "polystrata":
495
+ recipe = next((r for r in suite.recipes("llm") if r["id"] == model.entry.id), None)
496
+ concurrency = suite.effective_parallel(recipe, ()) if recipe is not None else 1
497
+ else:
498
+ concurrency = 1 if engine == "strata" else library_pricing.posture().slots
499
+ found["concurrency"] = concurrency
496
500
  if (
497
501
  plan is not None
498
502
  and engine in ("polystrata", "strata")
@@ -574,6 +578,8 @@ def _apply_record_meta(
574
578
  record: Record | None,
575
579
  state: str,
576
580
  problem: Problem | None,
581
+ *,
582
+ now_utc: dt.datetime,
577
583
  ) -> None:
578
584
  if state != "absent":
579
585
  if (selector := pi_model_of(model, record)) is not None:
@@ -581,6 +587,7 @@ def _apply_record_meta(
581
587
  if record is not None:
582
588
  if state == "loaded":
583
589
  _apply_loaded_endpoint(found, model, record)
590
+ apply_load_lifecycle(found, record, now_utc=now_utc)
584
591
  if (speed := record.get("tokens_per_second")) is not None:
585
592
  found["tokens_per_second"] = round(speed, 1)
586
593
  if (prefill := record.get("prompt_tokens_per_second")) is not None:
@@ -914,7 +921,8 @@ def _apply_storage(
914
921
  found["storage"] = storage
915
922
 
916
923
 
917
- def row(lib: Library, model: Model) -> Row:
924
+ def row(lib: Library, model: Model, *, now_utc: dt.datetime | None = None) -> Row:
925
+ observed_now = dt.datetime.now(dt.timezone.utc) if now_utc is None else now_utc
918
926
  record = lib.records.get(model.id)
919
927
  priced = lib.judge(model)
920
928
  state, problem = _state(lib, model.id, record)
@@ -975,7 +983,8 @@ def row(lib: Library, model: Model) -> Row:
975
983
  found["load"] = _loading(job)
976
984
  found.update(card(model, found["vision"]))
977
985
  _apply_engine_meta(lib, found, model, plan)
978
- _apply_record_meta(found, model, record, state, problem)
986
+ library_presentation.apply_row_meta(lib.facts, found, model, plan)
987
+ _apply_record_meta(found, model, record, state, problem, now_utc=observed_now)
979
988
  _apply_custom_meta(found, record, job, alive)
980
989
  _apply_storage(lib, found, model, record, job, plan, state)
981
990
  return found
@@ -1151,8 +1160,9 @@ def host(lib: Library) -> Host:
1151
1160
 
1152
1161
 
1153
1162
  def build(lib: Library) -> Status:
1163
+ observed_now = dt.datetime.now(dt.timezone.utc)
1154
1164
  models = lib.models()
1155
- rows = [row(lib, m) for m in models]
1165
+ rows = [row(lib, m, now_utc=observed_now) for m in models]
1156
1166
  disambiguate_row_names(rows)
1157
1167
  now = memory_pools.live(lib.facts, lib.reserved())
1158
1168
  candidates = [
@@ -1163,14 +1173,17 @@ def build(lib: Library) -> Status:
1163
1173
  and r.get("fits_now") is True
1164
1174
  and r.get("origin") != "custom"
1165
1175
  ]
1166
- chosen = library_pricing.recommend(now, candidates, lib.base_dir)
1176
+ best_pick = library_pricing.smartest(now, lib.base_dir)
1177
+ best_id = f"{best_pick[0]}:{best_pick[1]}" if best_pick is not None else None
1178
+ chosen = next((m.id for m in candidates if m.id == best_id), None) if best_id else None
1167
1179
  for r in rows:
1168
1180
  r["recommended"] = r["id"] == chosen
1169
1181
  rows = library_order.order_rows(lib.facts, models, rows)
1182
+ library_presentation.enrich_status_rows(lib.facts, rows, best_id)
1170
1183
  status_doc: Status = {
1171
1184
  "schema": STATUS_SCHEMA,
1172
1185
  "tool_version": __version__,
1173
- "observed_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
1186
+ "observed_at": observed_now.isoformat(timespec="seconds"),
1174
1187
  "host": host(lib),
1175
1188
  "pools": pools(lib, rows),
1176
1189
  "models": rows,
@@ -71,14 +71,20 @@ def strata_bar(llama_score: int, options: Mapping[str, object]) -> int:
71
71
 
72
72
 
73
73
  def strata_recipe_bar(
74
- llama_score: int, options: Mapping[str, object], *, prefer_over_llama: bool = False
74
+ llama_score: int,
75
+ options: Mapping[str, object],
76
+ *,
77
+ prefer_over_llama: bool = False,
78
+ allow_poly_fastest: bool = False,
75
79
  ) -> int:
76
80
  """The installed score one Strata/PolyStrata recipe must reach to replace the llama.cpp pick:
77
81
  a recipe marked ``prefer_over_llama`` (such as PolyStrata Inkling 2 Mini on CUDA 13+, which
78
82
  offers higher-precision quants and faster decode/prefill on NVIDIA cards) wins within
79
- ``COIN_FLIP`` against llama.cpp under ``smartest``, while keeping ``--prefer fastest`` on
80
- llama.cpp when one fits."""
83
+ ``COIN_FLIP`` against llama.cpp under ``smartest`` and ``concurrent``, and may compete under
84
+ ``--prefer fastest`` when ``allow_poly_fastest`` is set (full-VRAM resident, >= 2 slots)."""
81
85
  if options.get("prefer") == "fastest" and llama_score >= 0:
86
+ if allow_poly_fastest and prefer_over_llama:
87
+ return 0
82
88
  return 1 << 30
83
89
  if prefer_over_llama:
84
90
  return max(0, llama_score - COIN_FLIP)
@@ -34,6 +34,7 @@ from localmodels.records import (
34
34
  ModelSpec,
35
35
  PinnedFile,
36
36
  Plan,
37
+ PlanEndpoint,
37
38
  ReleaseEngine,
38
39
  ReusableFile,
39
40
  ServicePlan,
@@ -457,7 +458,7 @@ def plan_envelope(
457
458
  placement: dict[str, object],
458
459
  launch: dict[str, object],
459
460
  service: Launch,
460
- endpoint: dict[str, str],
461
+ endpoint: PlanEndpoint,
461
462
  warnings: list[str],
462
463
  ) -> Plan:
463
464
  """The deployment-plan/v1 document every planner writes; each prices its own parts."""
@@ -476,6 +477,14 @@ def plan_envelope(
476
477
  svc[key] = service[key]
477
478
  if "autostart" in service:
478
479
  svc["autostart"] = service["autostart"]
480
+ full_endpoint: PlanEndpoint = {
481
+ "base_url": f"http://{host}:{where.port}/v1",
482
+ "health_path": "/health",
483
+ "slots_path": None,
484
+ "metrics_path": None,
485
+ "metrics_requires_auth": False,
486
+ **endpoint,
487
+ }
479
488
  return {
480
489
  "schema": PLAN_SCHEMA,
481
490
  "name": where.name,
@@ -492,6 +501,6 @@ def plan_envelope(
492
501
  "placement": placement,
493
502
  "launch": launch,
494
503
  "service": svc,
495
- "endpoint": {"base_url": f"http://{host}:{where.port}/v1", **endpoint},
504
+ "endpoint": full_endpoint,
496
505
  "warnings": warnings,
497
506
  }