Skip to content

The agent that grows with you

fix(pm): bound the install lock, gate an unsatisfiable extra, retry a partial cache seed

ethernet045f4d9c8b8a
diff --git a/hermes_cli/runtime_paths.py b/hermes_cli/runtime_paths.py
index 5ef76e7f262..6c0431cb77e 100644
--- a/hermes_cli/runtime_paths.py
+++ b/hermes_cli/runtime_paths.py
@@ -124,8 +124,12 @@ def activate_dependencies(project_root: Path) -> None:
state = install_state_dir(project_root)
if state.is_dir():
from hermes_cli.runtime_state import runtime_lock, recover_publication, lease_generation
- with runtime_lock(project_root):
- recover_publication(project_root)
+ # The lock's holder may be another profile's backend running a full dependency rebuild;
+ # this process only reads the committed selection, so it proceeds without waiting rather
+ # than leaving the backend unbound (see runtime_lock).
+ with runtime_lock(project_root) as held:
+ if held:
+ recover_publication(project_root)
environment = selected_venv(project_root)
lease_generation(environment)
selected = site_packages(environment)
diff --git a/hermes_cli/runtime_state.py b/hermes_cli/runtime_state.py
index faf5fd2ca75..c245bcc0fbf 100644
--- a/hermes_cli/runtime_state.py
+++ b/hermes_cli/runtime_state.py
@@ -7,6 +7,7 @@ import base64
from contextlib import contextmanager
import hashlib
import json
+import logging
import os
from pathlib import Path
import shutil
@@ -16,8 +17,20 @@ import uuid
from hermes_cli.runtime_paths import dependency_home_root, install_state_dir, runtime_facts_path
+LOG = logging.getLogger(__name__)
-def _lock(fd: int, *, wait: bool) -> bool:
+# How long a process that only needs to READ the install state waits for a writer. The holder can
+# be another profile's backend rebuilding the whole dependency environment (measured: tens of
+# seconds on a bundle, minutes when a sync falls back to an sdist build), and a backend that never
+# binds its port is worse than one that binds against the previous generation. Losers skip — the
+# same rule boot_bootstrap._RecordLock states for home maintenance.
+INSTALL_LOCK_TIMEOUT_SECONDS = 10.0
+_LOCK_POLL_SECONDS = 0.05
+
+
+def _lock(fd: int, *, wait: bool, timeout: float | None = None) -> bool:
+ """Take the byte lock; ``timeout`` bounds the retry loop (None waits forever, 0 tries once)."""
+ deadline = None if timeout is None else time.monotonic() + timeout
if os.name == "nt":
import msvcrt
while True:
@@ -28,26 +41,41 @@ def _lock(fd: int, *, wait: bool) -> bool:
except OSError as exc:
if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
raise
- if not wait:
- return False
- time.sleep(0.05)
+ if not wait or (deadline is not None and time.monotonic() >= deadline):
+ return False
+ time.sleep(_LOCK_POLL_SECONDS)
else:
import fcntl
- try:
- fcntl.flock(fd, fcntl.LOCK_EX | (0 if wait else fcntl.LOCK_NB))
- return True
- except BlockingIOError:
- return False
+ while True:
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return True
+ except BlockingIOError:
+ pass
+ if not wait or (deadline is not None and time.monotonic() >= deadline):
+ return False
+ time.sleep(_LOCK_POLL_SECONDS)
@contextmanager
-def runtime_lock(project: Path):
+def runtime_lock(project: Path, *, timeout: float | None = INSTALL_LOCK_TIMEOUT_SECONDS):
+ """Hold the per-install dependency lock; yields True when held, False when the wait expired.
+
+ Callers decide what a lost race means: readers skip the work the lock guards and carry on
+ (``activate_dependencies`` still selects and leases the committed generation), writers that
+ cannot be skipped pass ``timeout=None`` — an install the user asked for is theirs to wait on.
+ """
state = install_state_dir(project)
state.mkdir(parents=True, exist_ok=True)
fd = os.open(state / ".install.lock", os.O_CREAT | os.O_RDWR, 0o600)
try:
- _lock(fd, wait=True)
- yield
+ if not _lock(fd, wait=True, timeout=timeout):
+ LOG.warning(
+ "dependency lock still held after %ss; continuing without it (%s)",
+ timeout, state / ".install.lock")
+ yield False
+ return
+ yield True
finally:
os.close(fd)
@@ -155,7 +183,12 @@ def finish_publication(project: Path) -> None:
def lease_generation(environment: Path) -> None:
- """Hold a kernel lock until process exit; call under runtime_lock at boot."""
+ """Hold a kernel lock until process exit.
+
+ Call under ``runtime_lock`` at boot; when that lock times out it is still safe to lease
+ without it, because the collector only removes generations that are NOT selected and are
+ older than a day — the generation being leased here is the selected one.
+ """
generation = environment.parent
if not (generation / ".lease-managed").is_file():
return # Generations produced before leases stay conservatively retained.
@@ -177,7 +210,9 @@ def collect_generations(project: Path, *, min_age_seconds: float = 86400) -> lis
root = install_state_dir(project)
if not root.exists():
return removed
- with runtime_lock(project):
+ with runtime_lock(project) as held:
+ if not held:
+ return removed # maintenance: another process owns the install, skip rather than queue
recover_publication(project)
selected = selected_venv(project).parent.resolve()
generations = root / "environments"
diff --git a/pm/ensure.py b/pm/ensure.py
index 4a9f159fa14..71616a9fc56 100644
--- a/pm/ensure.py
+++ b/pm/ensure.py
@@ -588,9 +588,23 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plu
)
package = get_package("venv")
- from hermes_cli.runtime_state import runtime_lock, recover_publication, finish_publication
+ from hermes_cli.runtime_state import (
+ INSTALL_LOCK_TIMEOUT_SECONDS, runtime_lock, recover_publication, finish_publication)
from pm.publication import PluginSelection, StagedPlugin, candidate_members
- with runtime_lock(paths.repo_root()):
+ # Holding this lock means rebuilding the whole dependency environment, which takes tens of
+ # seconds on a bundle. Only an install the user asked for may queue for it; an opportunistic
+ # one (a lazy extra at first use, the only non-explicit caller) refuses instead of holding
+ # a sibling profile's backend off its port behind a rebuild it did not request.
+ lock_timeout = None if (explicit or repair) else INSTALL_LOCK_TIMEOUT_SECONDS
+ with runtime_lock(paths.repo_root(), timeout=lock_timeout) as held:
+ if not held:
+ error = InstallError(
+ "venv",
+ f"another Hermes process is installing dependencies (waited {INSTALL_LOCK_TIMEOUT_SECONDS:.0f}s)",
+ "retry in a moment, or run `hermes pm install` to install explicitly",
+ )
+ receipt.record_refusal("install-busy", str(error))
+ raise error
recover_publication(paths.repo_root())
if sum(value is not None for value in (selection, staged_plugin, plugin_dirs)) + bool(extra_plugin_dirs) > 1:
raise ValueError("publication owns plugin member discovery")
diff --git a/pm/packages.py b/pm/packages.py
index 24b36bacf4d..6bc9287580a 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -3,6 +3,7 @@ live in pm/lock.json (written by `pm lock`), never here."""
from __future__ import annotations
+import logging
import os
import platform
import shutil
@@ -34,6 +35,8 @@ from pm.update import (
pbs_versions,
)
+LOG = logging.getLogger(__name__)
+
_RUST_TRIPLE = {
"win32-x64": "x86_64-pc-windows-msvc",
"win32-arm64": "aarch64-pc-windows-msvc",
@@ -309,32 +312,33 @@ def uv_cache_dir() -> Path:
marker = machine_cache / ".seeded"
if not marker.is_file():
# Seed from a shipped bundle cache when present (payload root =
- # store_root().parent on a sealed install).
+ # store_root().parent on a sealed install). Record completion ONLY after a clean copy: a
+ # partial seed that marked itself done would never be retried, and every later offline
+ # sync that needs the missing entries fails closed.
try:
from pm.paths import store_root
payload_cache = store_root().parent / "uv-cache"
if payload_cache.is_dir():
machine_cache.mkdir(parents=True, exist_ok=True)
- import shutil as _shutil
-
for entry in payload_cache.iterdir():
if entry.name == ".seeded":
continue
dest = machine_cache / entry.name
if not dest.exists():
(
- _shutil.copytree(entry, dest)
+ shutil.copytree(entry, dest)
if entry.is_dir()
- else _shutil.copy2(entry, dest)
+ else shutil.copy2(entry, dest)
)
- except OSError:
- pass # seeding is best-effort; a cold sync still works
- try:
- marker.parent.mkdir(parents=True, exist_ok=True)
- marker.write_text("1", encoding="utf-8")
- except OSError:
- pass
+ except OSError as exc:
+ LOG.warning("uv cache seed incomplete, retrying on the next install: %s", exc)
+ else:
+ try:
+ marker.parent.mkdir(parents=True, exist_ok=True)
+ marker.write_text("1", encoding="utf-8")
+ except OSError:
+ pass
return machine_cache
diff --git a/pyproject.toml b/pyproject.toml
index 966e675c935..e6e58217a88 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -542,6 +542,12 @@ google-chat = "platform_machine != 'ARM64' or sys_platform != 'win32'"
mem0 = "platform_machine != 'ARM64' or sys_platform != 'win32'"
# Match the engine dependency markers so PM refuses an unsupported install.
wake-openwakeword = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or sys_platform != 'darwin')"
+# faster-whisper's closure is prebuilt-only: ctranslate2 has no win_arm64 wheel and onnxruntime
+# none for darwin-x64. Its ANCHOR is faster_whisper, so an unsupported machine could install the
+# extra, rebuild the whole dependency environment and still fail the anchor on every retry.
+# Gate the extra that carries only faster-whisper; [voice] also has ungated deps (sounddevice,
+# numpy) and stays installable, see test_declared_extra_gates_match_dependency_selection.
+stt-whisper = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or platform_system != 'Darwin')"
# NeuTTS excludes Python 3.14. KittenTTS's misaki dependency excludes 3.13+.
neutts = "python_version < '3.14'"
kittentts = "python_version < '3.13'"