@simplexai/localmodels-darwin-x64 0.1.0-dev.65 → 0.1.0-dev.68
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 +62 -61
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/auth_proxy.py +34 -2
- package/modules/localmodels/bifrost_config.py +11 -6
- package/modules/localmodels/catalog.json +500 -16
- package/modules/localmodels/custom_hub.py +54 -6
- package/modules/localmodels/custom_probe.py +28 -0
- package/modules/localmodels/debug_stub_server.py +34 -1
- package/modules/localmodels/deploy.py +33 -349
- package/modules/localmodels/download-mirrors.json +43 -3
- package/modules/localmodels/draft_spec.py +1 -1
- package/modules/localmodels/engine_adapters/__init__.py +4 -2
- package/modules/localmodels/engine_adapters/auxiliary.py +4 -1
- package/modules/localmodels/engine_adapters/llama_cpp.py +539 -0
- package/modules/localmodels/engines-b11583.json +9 -5
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +85 -1
- package/modules/localmodels/engines.json +9 -5
- package/modules/localmodels/gateway_bifrost.py +2 -1
- package/modules/localmodels/harness_gateway.py +14 -3
- package/modules/localmodels/harness_probe.py +64 -3
- package/modules/localmodels/library_custom.py +9 -7
- package/modules/localmodels/library_elastic.py +5 -4
- package/modules/localmodels/library_jobs.py +138 -25
- package/modules/localmodels/library_model.py +22 -2
- package/modules/localmodels/library_order.py +1 -1
- package/modules/localmodels/library_serve.py +49 -11
- package/modules/localmodels/library_state.py +12 -0
- package/modules/localmodels/library_status.py +10 -0
- package/modules/localmodels/pi_profile.py +1 -1
- package/modules/localmodels/planning/budget.py +8 -3
- package/modules/localmodels/process_identity.py +73 -10
- package/modules/localmodels/remote_ops_mirrors.py +55 -19
- package/modules/localmodels/runtime_io.py +1 -0
- package/modules/localmodels/runtime_windows_acl.py +47 -17
- package/modules/localmodels/service_deployment.py +3 -3
- package/modules/localmodels/setup_inspection.py +28 -1
- package/modules/localmodels/setup_inspection_harness.py +4 -1
- package/modules/localmodels/setup_text.py +6 -0
- package/modules/localmodels/slot_cache.py +1 -3
- package/modules/localmodels/speech_admission.py +16 -4
- package/modules/localmodels/speech_catalog.py +5 -1
- package/modules/localmodels/speech_cli.py +5 -5
- package/modules/localmodels/speech_jobs.py +101 -19
- package/modules/localmodels/speech_server.py +2 -0
- package/modules/localmodels/speech_worker_sensevoice.py +194 -6
- package/modules/localmodels/speech_workers.py +74 -6
- package/modules/localmodels/stack.py +13 -1
- package/modules/localmodels/stack_auto.py +6 -0
- package/modules/localmodels/stack_capacity.py +3 -3
- package/modules/localmodels/stack_cli.py +3 -0
- package/modules/localmodels/stack_compose.py +7 -3
- package/modules/localmodels/stack_ports.py +58 -27
- package/modules/localmodels/stack_suite.py +7 -1
- package/modules/localmodels/suite.py +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/RECORD +59 -58
- package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/licenses/NOTICE +3 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -26,6 +26,7 @@ from localmodels import (
|
|
|
26
26
|
engines,
|
|
27
27
|
frontend,
|
|
28
28
|
harness,
|
|
29
|
+
harness_probe,
|
|
29
30
|
hosts,
|
|
30
31
|
library_convert,
|
|
31
32
|
library_elastic,
|
|
@@ -281,6 +282,14 @@ def _room(
|
|
|
281
282
|
) from None
|
|
282
283
|
|
|
283
284
|
|
|
285
|
+
def _port_busy(port: int) -> bool:
|
|
286
|
+
"""A listener holds ``port``, or bind() refuses it (an outgoing connection's local port where
|
|
287
|
+
the ephemeral range covers the service ports): the server's wrapper could not serve it."""
|
|
288
|
+
# Bind first: connect() to a bound, non-listening port is refused on Linux but answers EAGAIN
|
|
289
|
+
# on macOS, which loopback_listening reports as "cannot confirm".
|
|
290
|
+
return not harness_probe.loopback_bindable(port) or stack_ports.loopback_listening(port)
|
|
291
|
+
|
|
292
|
+
|
|
284
293
|
def _port(facts: HostFacts) -> int:
|
|
285
294
|
"""Under ``locked()``: a free port that no recorded server and no live load holds; the
|
|
286
295
|
caller reserves it in its load job before releasing the lock."""
|
|
@@ -293,10 +302,8 @@ def _port(facts: HostFacts) -> int:
|
|
|
293
302
|
if alive and job.get("port")
|
|
294
303
|
]
|
|
295
304
|
try:
|
|
296
|
-
return stack_ports.default_port(
|
|
297
|
-
|
|
298
|
-
)
|
|
299
|
-
except (plan_envelope.PlanError, OSError) as exc:
|
|
305
|
+
return stack_ports.default_port(facts, stack_ports.AUTO_PORTS, _port_busy, reserved=taken)
|
|
306
|
+
except (plan_envelope.PlanError, stack_ports.PortProbeError, OSError) as exc:
|
|
300
307
|
raise LibraryError("ENGINE_START_FAILED", str(exc)) from None
|
|
301
308
|
|
|
302
309
|
|
|
@@ -355,12 +362,37 @@ def _restore_baseline_plan(record: Record) -> None:
|
|
|
355
362
|
record["plan"] = baseline
|
|
356
363
|
|
|
357
364
|
|
|
365
|
+
def _stop_after_unregister_error(
|
|
366
|
+
record: Record, run: Executor, unreg_err: LibraryError
|
|
367
|
+
) -> LibraryError:
|
|
368
|
+
"""Stop the server even when gateway unregister failed so its memory is freed, while
|
|
369
|
+
keeping the failed record and registration receipt for a subsequent unload or remove."""
|
|
370
|
+
stop_err: LibraryError | None = None
|
|
371
|
+
if record["state"] != "idle":
|
|
372
|
+
try:
|
|
373
|
+
_remove_service(record["plan"], run)
|
|
374
|
+
except LibraryError as exc:
|
|
375
|
+
stop_err = exc
|
|
376
|
+
else:
|
|
377
|
+
record.pop("load_posture", None)
|
|
378
|
+
_restore_baseline_plan(record)
|
|
379
|
+
detail = (
|
|
380
|
+
f"{unreg_err.detail}; failed to stop server ({stop_err.detail})"
|
|
381
|
+
if stop_err is not None
|
|
382
|
+
else unreg_err.detail
|
|
383
|
+
)
|
|
384
|
+
err = LibraryError(unreg_err.code, detail, failed=unreg_err.failed, **unreg_err.fields)
|
|
385
|
+
return _fail(record, err)
|
|
386
|
+
|
|
387
|
+
|
|
358
388
|
def stop(record: Record, run: Executor) -> None:
|
|
359
389
|
"""Demote a loaded record, unregister it, then stop and remove the model's server; its
|
|
360
|
-
weights stay.
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
the
|
|
390
|
+
weights stay. A loaded record is marked failed on disk before unregistering so a failed,
|
|
391
|
+
interrupted, or killed stop never leaves status or load treating an unroutable model as
|
|
392
|
+
loaded; once unregistered the registration receipt is removed before the server stops. If
|
|
393
|
+
unregistering fails with ``LibraryError``, the server is still stopped to free its memory
|
|
394
|
+
while the record stays ``failed`` with its registration receipt for the next unload."""
|
|
395
|
+
unreg_err: LibraryError | None = None
|
|
364
396
|
if registration := record.get("registration"):
|
|
365
397
|
if record["state"] == "loaded":
|
|
366
398
|
record["state"] = "failed"
|
|
@@ -369,9 +401,15 @@ def stop(record: Record, run: Executor) -> None:
|
|
|
369
401
|
"detail": "stopping the model server did not finish; unload or load it again",
|
|
370
402
|
}
|
|
371
403
|
library_state.save(record)
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
404
|
+
try:
|
|
405
|
+
library_gateway.unregister(registration)
|
|
406
|
+
except LibraryError as exc:
|
|
407
|
+
unreg_err = exc
|
|
408
|
+
else:
|
|
409
|
+
record.pop("registration")
|
|
410
|
+
library_state.save(record)
|
|
411
|
+
if unreg_err is not None:
|
|
412
|
+
raise _stop_after_unregister_error(record, run, unreg_err) from None
|
|
375
413
|
record.pop("load_posture", None)
|
|
376
414
|
if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
|
|
377
415
|
_remove_service(record["plan"], run)
|
|
@@ -152,6 +152,8 @@ class _JobSince20261113(TypedDict, total=False):
|
|
|
152
152
|
connections: int # active parallel download connections
|
|
153
153
|
shard_index: int # 1-based active shard index for multi-shard downloads
|
|
154
154
|
shard_count: int # total shard count for multi-shard downloads
|
|
155
|
+
engine_done: int # engine archive bytes inside done while the engine downloads too
|
|
156
|
+
engine_total: int # engine archive bytes inside total (first install only)
|
|
155
157
|
load_step: str # load sub-step: prepare | start | load | warm
|
|
156
158
|
error: Problem # a download that stopped cleanly: status shows why; cancel discards it
|
|
157
159
|
custom: CustomMeta # custom hub metadata while download is in progress
|
|
@@ -350,6 +352,8 @@ class JobHandle:
|
|
|
350
352
|
load_step: str | None = None,
|
|
351
353
|
shard_index: int | None = None,
|
|
352
354
|
shard_count: int | None = None,
|
|
355
|
+
engine_done: int | None = None,
|
|
356
|
+
engine_total: int | None = None,
|
|
353
357
|
) -> None:
|
|
354
358
|
import time
|
|
355
359
|
|
|
@@ -360,6 +364,7 @@ class JobHandle:
|
|
|
360
364
|
self.job.get("total"),
|
|
361
365
|
self.job.get("shard_index"),
|
|
362
366
|
self.job.get("shard_count"),
|
|
367
|
+
self.job.get("done", 0) > 0, # the first bytes moving: status leaves 0 at once
|
|
363
368
|
)
|
|
364
369
|
self.job["phase"], self.job["done"], self.job["total"] = phase, done, total
|
|
365
370
|
self.job["bytes_per_second"] = bytes_per_second
|
|
@@ -385,6 +390,12 @@ class JobHandle:
|
|
|
385
390
|
self.job.pop("connections", None)
|
|
386
391
|
self.job.pop("shard_index", None)
|
|
387
392
|
self.job.pop("shard_count", None)
|
|
393
|
+
if phase in ("download", "verify") and engine_total is not None and engine_total > 0:
|
|
394
|
+
self.job["engine_total"] = engine_total
|
|
395
|
+
self.job["engine_done"] = max(0, min(engine_done or 0, engine_total))
|
|
396
|
+
else:
|
|
397
|
+
self.job.pop("engine_total", None)
|
|
398
|
+
self.job.pop("engine_done", None)
|
|
388
399
|
if phase in ("load", "warm") and load_step is not None:
|
|
389
400
|
self.job["load_step"] = load_step
|
|
390
401
|
else:
|
|
@@ -396,6 +407,7 @@ class JobHandle:
|
|
|
396
407
|
self.job.get("total"),
|
|
397
408
|
self.job.get("shard_index"),
|
|
398
409
|
self.job.get("shard_count"),
|
|
410
|
+
self.job.get("done", 0) > 0,
|
|
399
411
|
) != prev
|
|
400
412
|
now = time.monotonic()
|
|
401
413
|
if changed or now - self._written >= JOB_WRITE_EVERY_S or done >= total:
|
|
@@ -432,6 +432,16 @@ def _downloading(job: Job) -> Download:
|
|
|
432
432
|
s_cnt = job.get("shard_count")
|
|
433
433
|
if isinstance(s_cnt, int) and not isinstance(s_cnt, bool) and s_cnt >= 1:
|
|
434
434
|
dl["shard_count"] = s_cnt
|
|
435
|
+
e_total, e_done = job.get("engine_total"), job.get("engine_done")
|
|
436
|
+
if (
|
|
437
|
+
isinstance(e_total, int)
|
|
438
|
+
and not isinstance(e_total, bool)
|
|
439
|
+
and e_total > 0
|
|
440
|
+
and isinstance(e_done, int)
|
|
441
|
+
and not isinstance(e_done, bool)
|
|
442
|
+
):
|
|
443
|
+
dl["engine_total_bytes"] = min(e_total, dl["total_bytes"])
|
|
444
|
+
dl["engine_done_bytes"] = max(0, min(e_done, dl["engine_total_bytes"]))
|
|
435
445
|
return dl
|
|
436
446
|
|
|
437
447
|
|
|
@@ -107,7 +107,7 @@ def write_json(path: Path, value: dict[str, Any]) -> None:
|
|
|
107
107
|
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
108
108
|
handle.write(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
|
109
109
|
os.chmod(tmp, mode)
|
|
110
|
-
|
|
110
|
+
runtime_io.rename_with_retry(Path(tmp), path, replace=True)
|
|
111
111
|
except BaseException:
|
|
112
112
|
with contextlib.suppress(OSError):
|
|
113
113
|
os.unlink(tmp)
|
|
@@ -22,6 +22,7 @@ from __future__ import annotations
|
|
|
22
22
|
|
|
23
23
|
import re
|
|
24
24
|
from dataclasses import dataclass, replace
|
|
25
|
+
from typing import Literal
|
|
25
26
|
|
|
26
27
|
from localmodels import gpu_specs, metal
|
|
27
28
|
from localmodels.context_policy import RUNTIME_OVERHEAD_BYTES
|
|
@@ -61,6 +62,10 @@ _SERVING_PROCESS_RE = re.compile(
|
|
|
61
62
|
)
|
|
62
63
|
|
|
63
64
|
|
|
65
|
+
# The device a placement runs on; engine_adapters.llama_cpp.backend_for keys its hooks on it.
|
|
66
|
+
Backend = Literal["cuda", "metal", "cpu"]
|
|
67
|
+
|
|
68
|
+
|
|
64
69
|
@dataclass(frozen=True)
|
|
65
70
|
class Placement:
|
|
66
71
|
"""Where one model would run: one card, every card split by layer, or the host's unified pool."""
|
|
@@ -69,7 +74,7 @@ class Placement:
|
|
|
69
74
|
label: str
|
|
70
75
|
gpu_indices: tuple[int, ...]
|
|
71
76
|
budget: HardwareBudget
|
|
72
|
-
backend:
|
|
77
|
+
backend: Backend
|
|
73
78
|
pooled: bool = False # multi-card split: our extension, not calibrated
|
|
74
79
|
busy: bool = False # another process already holds part of a selected card
|
|
75
80
|
conflicts: tuple[str, ...] = () # foreign serving work on the selected cards (gpu_conflicts)
|
|
@@ -391,7 +396,7 @@ def placements(facts: HostFacts, *, planning: bool = True) -> list[Placement]:
|
|
|
391
396
|
# Metal, integrated or unknown GPUs, CPU: RAM as unified memory. AMD/Intel discrete cards
|
|
392
397
|
# need the engine's device probe, which runs only after an engine is installed.
|
|
393
398
|
cls = facts.get("gpu_vendor_class", "unknown")
|
|
394
|
-
backend = "metal" if facts.get("platform") == "darwin" else "cpu"
|
|
399
|
+
backend: Backend = "metal" if facts.get("platform") == "darwin" else "cpu"
|
|
395
400
|
metal_info = metal.reading(facts) if backend == "metal" else None
|
|
396
401
|
metal_name = str(metal_info.get("name") or "") if metal_info else ""
|
|
397
402
|
budget = _uma(
|
|
@@ -562,7 +567,7 @@ class AdmissionBudget:
|
|
|
562
567
|
"""
|
|
563
568
|
|
|
564
569
|
pool: str
|
|
565
|
-
backend:
|
|
570
|
+
backend: Backend
|
|
566
571
|
soft_budget_bytes: int
|
|
567
572
|
hard_ceiling_bytes: int
|
|
568
573
|
reserve_bytes: int
|
|
@@ -45,6 +45,8 @@ def current_uid() -> int:
|
|
|
45
45
|
|
|
46
46
|
_STILL_ACTIVE = 259
|
|
47
47
|
_QUERY_LIMITED = 0x1000 # PROCESS_QUERY_LIMITED_INFORMATION
|
|
48
|
+
_SYNCHRONIZE = 0x00100000
|
|
49
|
+
_WAIT_OBJECT_0 = 0x00000000
|
|
48
50
|
|
|
49
51
|
|
|
50
52
|
_API: list[tuple[Any, Any]] = []
|
|
@@ -64,6 +66,7 @@ def _api() -> tuple[Any, Any]:
|
|
|
64
66
|
(kernel.OpenProcess, (d, b, d), h),
|
|
65
67
|
(kernel.GetCurrentProcess, (), h),
|
|
66
68
|
(kernel.CloseHandle, (h,), b),
|
|
69
|
+
(kernel.WaitForSingleObject, (h, d), d),
|
|
67
70
|
(kernel.LocalFree, (p,), p),
|
|
68
71
|
(kernel.GetExitCodeProcess, (h, ptr(d)), b),
|
|
69
72
|
(kernel.GetProcessTimes, (h, *[ptr(wintypes.FILETIME)] * 4), b),
|
|
@@ -322,21 +325,81 @@ def stop_children(pid: int) -> int:
|
|
|
322
325
|
return len(children)
|
|
323
326
|
|
|
324
327
|
|
|
325
|
-
def
|
|
326
|
-
"""
|
|
328
|
+
def _windows_handle_identity(kernel: Any, handle: Any, pid: int) -> Identity | None:
|
|
329
|
+
"""Identity of an already-open Windows process handle, even while terminating."""
|
|
330
|
+
from ctypes import wintypes
|
|
331
|
+
|
|
332
|
+
times = [wintypes.FILETIME() for _ in range(4)]
|
|
333
|
+
if not kernel.GetProcessTimes(handle, *(ctypes.byref(t) for t in times)):
|
|
334
|
+
return None
|
|
335
|
+
created = (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime
|
|
336
|
+
sid = _token_sid(handle)
|
|
337
|
+
own = _own_sid()
|
|
338
|
+
uid = 0 if sid is not None and own is not None and sid == own else -1
|
|
339
|
+
return {"pid": pid, "uid": uid, "pgid": pid, "started": str(created)}
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _open_verified_windows_handle(pid: int, saved: Identity) -> Any | None:
|
|
343
|
+
"""Open a SYNCHRONIZE handle to ``pid`` matching ``saved``; caller must CloseHandle."""
|
|
344
|
+
if not _windows():
|
|
345
|
+
return None
|
|
346
|
+
kernel, _ = _api()
|
|
347
|
+
handle = kernel.OpenProcess(_SYNCHRONIZE | _QUERY_LIMITED, False, pid)
|
|
348
|
+
if not handle:
|
|
349
|
+
return None
|
|
350
|
+
matched = False
|
|
351
|
+
try:
|
|
352
|
+
matched = _windows_handle_identity(kernel, handle, pid) == saved
|
|
353
|
+
except OSError:
|
|
354
|
+
matched = False
|
|
355
|
+
finally:
|
|
356
|
+
if not matched:
|
|
357
|
+
kernel.CloseHandle(handle)
|
|
358
|
+
return handle if matched else None
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _wait_windows_handle(handle: Any, timeout_s: float) -> bool:
|
|
362
|
+
"""Wait up to ``timeout_s`` for a Windows process handle to become signaled."""
|
|
363
|
+
kernel, _ = _api()
|
|
364
|
+
timeout_ms = 0 if timeout_s <= 0 else min(max(1, int(timeout_s * 1000)), 0xFFFFFFFE)
|
|
365
|
+
return bool(kernel.WaitForSingleObject(handle, timeout_ms) == _WAIT_OBJECT_0)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _windows_exited(pid: int, saved: Identity, handle: Any | None) -> bool:
|
|
369
|
+
if handle is not None:
|
|
370
|
+
return _wait_windows_handle(handle, 0.0)
|
|
371
|
+
return _windows_inspect(pid) != saved
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _wait_windows_exit(pid: int, saved: Identity, handle: Any | None, timeout_s: float) -> bool:
|
|
327
375
|
import time
|
|
328
376
|
|
|
329
|
-
|
|
377
|
+
if handle is not None:
|
|
378
|
+
return _wait_windows_handle(handle, timeout_s)
|
|
379
|
+
deadline = time.monotonic() + timeout_s
|
|
380
|
+
while time.monotonic() < deadline:
|
|
330
381
|
if _windows_inspect(pid) != saved:
|
|
331
382
|
return True
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
383
|
+
time.sleep(0.2)
|
|
384
|
+
return False
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def windows_stop_tree(pid: int, saved: Identity, grace: float) -> bool:
|
|
388
|
+
"""Stop PID and descendants via polite ``taskkill /T`` (capped at 2 s) then ``/F``."""
|
|
389
|
+
handle = _open_verified_windows_handle(pid, saved)
|
|
390
|
+
try:
|
|
391
|
+
for force in (False, True):
|
|
392
|
+
if _windows_exited(pid, saved, handle):
|
|
337
393
|
return True
|
|
338
|
-
|
|
339
|
-
|
|
394
|
+
if not _taskkill(pid, force) and not force:
|
|
395
|
+
continue
|
|
396
|
+
wait_s = min(grace, 2.0) if not force else 15.0
|
|
397
|
+
if _wait_windows_exit(pid, saved, handle, wait_s):
|
|
398
|
+
return True
|
|
399
|
+
return _windows_exited(pid, saved, handle)
|
|
400
|
+
finally:
|
|
401
|
+
if handle is not None:
|
|
402
|
+
_api()[0].CloseHandle(handle)
|
|
340
403
|
|
|
341
404
|
|
|
342
405
|
# Scheduled tasks start child services below normal (priority/memory/I/O), allowing Windows to
|
|
@@ -208,6 +208,35 @@ discard = remote_ops_common.discard
|
|
|
208
208
|
clear_link = remote_ops_common.clear_link
|
|
209
209
|
|
|
210
210
|
|
|
211
|
+
def _lock_once(lock: object, *, block: bool = False) -> bool:
|
|
212
|
+
"""Take the engines-root lock on an open lock file: one attempt, or (POSIX ``block``) wait
|
|
213
|
+
for it. Windows has no blocking form; its callers poll."""
|
|
214
|
+
try:
|
|
215
|
+
if os.name == "nt":
|
|
216
|
+
import msvcrt
|
|
217
|
+
|
|
218
|
+
lock.seek(0) # type: ignore[attr-defined]
|
|
219
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
|
|
220
|
+
else:
|
|
221
|
+
import fcntl
|
|
222
|
+
|
|
223
|
+
flags = fcntl.LOCK_EX if block else fcntl.LOCK_EX | fcntl.LOCK_NB
|
|
224
|
+
fcntl.flock(lock, flags) # type: ignore[arg-type]
|
|
225
|
+
except OSError:
|
|
226
|
+
return False
|
|
227
|
+
return True
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _unlock(lock: object) -> None:
|
|
231
|
+
if os.name == "nt":
|
|
232
|
+
import msvcrt
|
|
233
|
+
|
|
234
|
+
with contextlib.suppress(OSError):
|
|
235
|
+
lock.seek(0) # type: ignore[attr-defined]
|
|
236
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
|
|
237
|
+
# POSIX: closing the file releases the flock.
|
|
238
|
+
|
|
239
|
+
|
|
211
240
|
@contextlib.contextmanager
|
|
212
241
|
def engine_lock(directory: str) -> Iterator[None]:
|
|
213
242
|
"""Serialize concurrent engine fetches and unpacks under the same engines root so parallel
|
|
@@ -216,27 +245,34 @@ def engine_lock(directory: str) -> Iterator[None]:
|
|
|
216
245
|
os.makedirs(parent, exist_ok=True)
|
|
217
246
|
lock_path = os.path.join(parent, ".engine.lock")
|
|
218
247
|
with open(lock_path, "a+") as lock:
|
|
219
|
-
|
|
220
|
-
|
|
248
|
+
while not _lock_once(lock, block=True):
|
|
249
|
+
time.sleep(0.1)
|
|
250
|
+
try:
|
|
251
|
+
yield
|
|
252
|
+
finally:
|
|
253
|
+
_unlock(lock)
|
|
221
254
|
|
|
222
|
-
lock.seek(0)
|
|
223
|
-
while True:
|
|
224
|
-
try:
|
|
225
|
-
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
|
|
226
|
-
break
|
|
227
|
-
except OSError:
|
|
228
|
-
time.sleep(0.1)
|
|
229
|
-
try:
|
|
230
|
-
yield
|
|
231
|
-
finally:
|
|
232
|
-
with contextlib.suppress(OSError):
|
|
233
|
-
lock.seek(0)
|
|
234
|
-
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
|
|
235
|
-
else:
|
|
236
|
-
import fcntl
|
|
237
255
|
|
|
238
|
-
|
|
239
|
-
|
|
256
|
+
@contextlib.contextmanager
|
|
257
|
+
def try_engine_lock(directory: str, wait_s: float = 0.0) -> Iterator[bool]:
|
|
258
|
+
"""``engine_lock`` that gives up after ``wait_s``: yields whether it holds the lock. A
|
|
259
|
+
cleanup that must not touch another download's ``.archives/*.part`` uses it."""
|
|
260
|
+
parent = os.path.dirname(directory) or "."
|
|
261
|
+
if not os.path.isdir(parent):
|
|
262
|
+
yield False
|
|
263
|
+
return
|
|
264
|
+
lock_path = os.path.join(parent, ".engine.lock")
|
|
265
|
+
with open(lock_path, "a+") as lock:
|
|
266
|
+
deadline = time.monotonic() + max(0.0, wait_s)
|
|
267
|
+
held = _lock_once(lock)
|
|
268
|
+
while not held and time.monotonic() < deadline:
|
|
269
|
+
time.sleep(0.1)
|
|
270
|
+
held = _lock_once(lock)
|
|
271
|
+
try:
|
|
272
|
+
yield held
|
|
273
|
+
finally:
|
|
274
|
+
if held:
|
|
275
|
+
_unlock(lock)
|
|
240
276
|
|
|
241
277
|
|
|
242
278
|
def npm_transfer(
|
|
@@ -132,6 +132,7 @@ _windows_private = runtime_windows_acl.private_permissions
|
|
|
132
132
|
_private_dacl_entries = runtime_windows_acl.private_dacl_entries
|
|
133
133
|
_windows_sid_text = runtime_windows_acl.sid_text
|
|
134
134
|
rename_with_retry = runtime_windows_acl.rename_with_retry
|
|
135
|
+
unlink_with_retry = runtime_windows_acl.unlink_with_retry
|
|
135
136
|
|
|
136
137
|
|
|
137
138
|
def _safe_member(name: str) -> Path:
|
|
@@ -9,7 +9,7 @@ import sys
|
|
|
9
9
|
import time
|
|
10
10
|
from collections.abc import Callable, Sequence
|
|
11
11
|
from pathlib import Path
|
|
12
|
-
from typing import Any
|
|
12
|
+
from typing import Any, TypeVar
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
@functools.lru_cache(maxsize=1)
|
|
@@ -300,36 +300,66 @@ def protect(advapi: Any, kernel: Any, path: Path, user_sid: str) -> None:
|
|
|
300
300
|
kernel.LocalFree(security)
|
|
301
301
|
|
|
302
302
|
|
|
303
|
-
|
|
304
|
-
|
|
303
|
+
_T = TypeVar("_T")
|
|
304
|
+
_WINDOWS_LOCK_RETRY_WINERRORS = frozenset({5, 32})
|
|
305
|
+
_WINDOWS_LOCK_RETRY_DELAYS_S = (0.05, 0.1, 0.2, 0.4, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5)
|
|
305
306
|
|
|
306
307
|
|
|
307
|
-
def
|
|
308
|
-
"""True for transient Windows
|
|
308
|
+
def _retryable_windows_lock_error(exc: OSError) -> bool:
|
|
309
|
+
"""True for transient Windows AV / indexer / exiting-process handle locks."""
|
|
309
310
|
if sys.platform != "win32" or not isinstance(exc, PermissionError):
|
|
310
311
|
return False
|
|
311
312
|
winerror = getattr(exc, "winerror", None)
|
|
312
313
|
if winerror is not None:
|
|
313
|
-
return winerror in
|
|
314
|
+
return winerror in _WINDOWS_LOCK_RETRY_WINERRORS
|
|
314
315
|
return exc.errno in (None, errno.EACCES)
|
|
315
316
|
|
|
316
317
|
|
|
317
|
-
def
|
|
318
|
-
|
|
319
|
-
target: Path,
|
|
318
|
+
def _retry_windows_lock(
|
|
319
|
+
op: Callable[[], _T],
|
|
320
320
|
*,
|
|
321
|
-
|
|
322
|
-
delays: Sequence[float] = _WINDOWS_RENAME_RETRY_DELAYS_S,
|
|
321
|
+
delays: Sequence[float] = _WINDOWS_LOCK_RETRY_DELAYS_S,
|
|
323
322
|
pause: Callable[[float], None] | None = None,
|
|
324
|
-
) ->
|
|
325
|
-
"""Rename or replace ``source`` into ``target``, retrying transient Windows AV locks
|
|
326
|
-
(WinError 5 Access Denied / WinError 32 Sharing Violation) with bounded backoff."""
|
|
323
|
+
) -> _T:
|
|
327
324
|
sleep = time.sleep if pause is None else pause
|
|
328
325
|
for delay in delays:
|
|
329
326
|
try:
|
|
330
|
-
return
|
|
327
|
+
return op()
|
|
331
328
|
except OSError as exc:
|
|
332
|
-
if not
|
|
329
|
+
if not _retryable_windows_lock_error(exc):
|
|
333
330
|
raise
|
|
334
331
|
sleep(delay)
|
|
335
|
-
return
|
|
332
|
+
return op()
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def rename_with_retry(
|
|
336
|
+
source: Path,
|
|
337
|
+
target: Path,
|
|
338
|
+
*,
|
|
339
|
+
replace: bool = False,
|
|
340
|
+
delays: Sequence[float] = _WINDOWS_LOCK_RETRY_DELAYS_S,
|
|
341
|
+
pause: Callable[[float], None] | None = None,
|
|
342
|
+
) -> Path:
|
|
343
|
+
"""Rename or replace ``source`` into ``target``, retrying transient Windows file locks
|
|
344
|
+
(WinError 5 Access Denied / WinError 32 Sharing Violation) with bounded backoff."""
|
|
345
|
+
return _retry_windows_lock(
|
|
346
|
+
lambda: source.replace(target) if replace else source.rename(target),
|
|
347
|
+
delays=delays,
|
|
348
|
+
pause=pause,
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def unlink_with_retry(
|
|
353
|
+
path: Path,
|
|
354
|
+
*,
|
|
355
|
+
missing_ok: bool = False,
|
|
356
|
+
delays: Sequence[float] = _WINDOWS_LOCK_RETRY_DELAYS_S,
|
|
357
|
+
pause: Callable[[float], None] | None = None,
|
|
358
|
+
) -> None:
|
|
359
|
+
"""Unlink ``path``, retrying transient Windows file locks
|
|
360
|
+
(WinError 5 Access Denied / WinError 32 Sharing Violation) with bounded backoff."""
|
|
361
|
+
_retry_windows_lock(
|
|
362
|
+
lambda: path.unlink(missing_ok=missing_ok),
|
|
363
|
+
delays=delays,
|
|
364
|
+
pause=pause,
|
|
365
|
+
)
|
|
@@ -75,7 +75,7 @@ def plan_component(
|
|
|
75
75
|
options = {**stack.default_options(), "base_dir": str(root)}
|
|
76
76
|
try:
|
|
77
77
|
return decision.gpu_plans(facts, options, choice, card)
|
|
78
|
-
except stack_ports.PortUnavailableError as exc:
|
|
78
|
+
except (stack_ports.PortUnavailableError, stack_ports.PortProbeError) as exc:
|
|
79
79
|
raise WaitingForResourcesError("port") from exc
|
|
80
80
|
raise WaitingForResourcesError("gpu")
|
|
81
81
|
if role not in ("embedding", "reranker"):
|
|
@@ -85,7 +85,7 @@ def plan_component(
|
|
|
85
85
|
port = stack_ports.default_port(
|
|
86
86
|
facts, stack_ports.AUXILIARY_PORTS[role], stack_ports.loopback_listening
|
|
87
87
|
)
|
|
88
|
-
except PlanError as exc:
|
|
88
|
+
except (PlanError, stack_ports.PortProbeError) as exc:
|
|
89
89
|
raise WaitingForResourcesError("port") from exc
|
|
90
90
|
built = suite_plan.build_plan(
|
|
91
91
|
"local",
|
|
@@ -394,7 +394,7 @@ class Deployment:
|
|
|
394
394
|
offset=component.FRONT_OFFSET if template_front is not None else 0,
|
|
395
395
|
reserved=(main["llm"]["service"]["port"],),
|
|
396
396
|
)
|
|
397
|
-
except PlanError as exc:
|
|
397
|
+
except (PlanError, stack_ports.PortProbeError) as exc:
|
|
398
398
|
raise WaitingForResourcesError("port") from exc
|
|
399
399
|
built, front = _decision_endpoint(template, template_front, port)
|
|
400
400
|
else:
|
|
@@ -23,6 +23,7 @@ from localmodels import (
|
|
|
23
23
|
stack,
|
|
24
24
|
stack_binding,
|
|
25
25
|
stack_hardware,
|
|
26
|
+
stack_ports,
|
|
26
27
|
stack_review,
|
|
27
28
|
)
|
|
28
29
|
from localmodels.contracts import decode
|
|
@@ -237,12 +238,35 @@ def _harness_availability(
|
|
|
237
238
|
}
|
|
238
239
|
|
|
239
240
|
|
|
241
|
+
def _port_check_availability(
|
|
242
|
+
options: StackOptions, facts: HostFacts, exc: StackError, lang: Lang
|
|
243
|
+
) -> StackAvailability:
|
|
244
|
+
"""No port of a range could be confirmed free (stack_ports.PortProbeError): blocked now and
|
|
245
|
+
retryable, never a reason to recommend another runtime when the hardware fits."""
|
|
246
|
+
capable = setup_inspection_harness.hardware_capable_without_harness(options, facts)
|
|
247
|
+
return {
|
|
248
|
+
"available": False,
|
|
249
|
+
"reasons": [
|
|
250
|
+
{
|
|
251
|
+
"code": "port-check-failed",
|
|
252
|
+
"message": text("port-check-failed", lang, detail=str(exc))
|
|
253
|
+
if capable
|
|
254
|
+
else str(exc),
|
|
255
|
+
}
|
|
256
|
+
],
|
|
257
|
+
"plan": None,
|
|
258
|
+
"hardwareCapable": capable,
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
|
|
240
262
|
def _plan_stack(
|
|
241
263
|
options: StackOptions, facts: HostFacts, share_gpu: bool, lang: Lang
|
|
242
264
|
) -> StackAvailability:
|
|
243
265
|
try:
|
|
244
266
|
try:
|
|
245
267
|
plan = stack.build(options, facts=facts)
|
|
268
|
+
except stack_ports.PortProbeError as exc:
|
|
269
|
+
return _port_check_availability(options, facts, exc, lang)
|
|
246
270
|
except (PlanError, stack.StackError) as exc:
|
|
247
271
|
last_error: PlanError | StackError | None = exc
|
|
248
272
|
last_options = options
|
|
@@ -518,7 +542,7 @@ INSPECT = (
|
|
|
518
542
|
INSPECT_REASONS = (
|
|
519
543
|
"unsupported-platform · facts-unavailable · plan-unavailable · gpu-sharing-required\n"
|
|
520
544
|
"cuda-driver-update-required · cuda-driver-version-unknown · gateway-port-in-use · "
|
|
521
|
-
"harness-unavailable\n"
|
|
545
|
+
"harness-unavailable · port-check-failed\n"
|
|
522
546
|
"(gpu-sharing-required: a plan fits only beside other GPU work, its owner known or not; ask, "
|
|
523
547
|
"then rerun with --share-gpu, which plans by the free VRAM)\n"
|
|
524
548
|
"cuda-driver-update-required / cuda-driver-version-unknown (stack.state is blocked-now, "
|
|
@@ -528,6 +552,9 @@ INSPECT_REASONS = (
|
|
|
528
552
|
"gateway-port-in-use / harness-unavailable (stack.state is blocked-now with "
|
|
529
553
|
"hardwareCapable true when the hardware fits, but the gateway port is held or tool checks "
|
|
530
554
|
"failed; free the port or fix the tool issue and check again)\n"
|
|
555
|
+
"port-check-failed (stack.state is blocked-now with hardwareCapable true when the hardware "
|
|
556
|
+
"fits: no port of a range the stack needs could be confirmed free right now, because the "
|
|
557
|
+
"loopback check could not tell; check again)\n"
|
|
531
558
|
"gpu-memory-required (stack.state is blocked-now, stack.basis is capacity: other programs "
|
|
532
559
|
"or another inference app/GPU workload use the GPU memory the plan needs; close them and "
|
|
533
560
|
"check again; gpuIndex, freeBytes and requiredBytes give the card and its free and needed "
|
|
@@ -45,7 +45,10 @@ class Reason(_ReasonOptional):
|
|
|
45
45
|
message: str
|
|
46
46
|
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
# Blocked-now reasons about the gateway, its tools or loopback ports, not the hardware.
|
|
49
|
+
# port-check-failed: the loopback probe could not tell whether any port of a range is free
|
|
50
|
+
# (stack_ports.PortProbeError, or the Magpie address); checking again may pass.
|
|
51
|
+
HARNESS_CODES = frozenset({"gateway-port-in-use", "harness-unavailable", "port-check-failed"})
|
|
49
52
|
_PORT_CONFLICT_HINTS = (
|
|
50
53
|
"is held by",
|
|
51
54
|
"ports 3425..3456 are all in use",
|
|
@@ -106,6 +106,12 @@ MESSAGES: dict[str, tuple[str, str]] = {
|
|
|
106
106
|
"This computer's hardware can run local models, but the gateway port is currently in use "
|
|
107
107
|
"({detail}). Stop that program or set another gateway address, then check again.",
|
|
108
108
|
),
|
|
109
|
+
"port-check-failed": (
|
|
110
|
+
"这台电脑的硬件可以运行本地模型,但暂时无法确认本地端口是否空闲({detail})。"
|
|
111
|
+
"请稍后重新检查。",
|
|
112
|
+
"This computer's hardware can run local models, but whether a local port is free could "
|
|
113
|
+
"not be confirmed right now ({detail}). Check again in a moment.",
|
|
114
|
+
),
|
|
109
115
|
"harness-unavailable": (
|
|
110
116
|
"这台电脑的硬件可以运行本地模型,但网关或工具环境检查未通过({detail})。"
|
|
111
117
|
"请先处理该问题后重新检查。",
|
|
@@ -424,9 +424,7 @@ def main(argv: list[str]) -> int:
|
|
|
424
424
|
tally = Tally(slot_dir)
|
|
425
425
|
if not (slot_dir / PREFIX_FILE).exists():
|
|
426
426
|
tally.kept = None # write the leading prefix again
|
|
427
|
-
proxy =
|
|
428
|
-
(host, int(port)), handler(upstream, slot_dir, tally, key)
|
|
429
|
-
)
|
|
427
|
+
proxy = auth_proxy.bind_server((host, int(port)), handler(upstream, slot_dir, tally, key))
|
|
430
428
|
proxy.daemon_threads = True
|
|
431
429
|
child = subprocess.Popen(inner)
|
|
432
430
|
guard = end_with_me(child.pid)
|