Skip to content

The agent that grows with you

fix(model): decide the route before snapshotting config for /model save

Teknium3a02759c2979
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index c31d89d3478..ccb756d8b65 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -1812,8 +1812,12 @@ def selection_route_changed(model_cfg: dict, result: ModelSwitchResult) -> bool:
def apply_model_selection(model_cfg: Any, result: ModelSwitchResult) -> dict:
"""Apply the canonical shape to an in-memory ``model:`` dict (``None`` = key removed) for
callers that save a whole config document they are already mutating."""
+ return _merge_selection_updates(model_cfg, model_selection_config_updates(result, model_cfg))
+
+
+def _merge_selection_updates(model_cfg: Any, updates: dict[str, Any]) -> dict:
model_cfg = dict(model_cfg) if isinstance(model_cfg, dict) else {}
- for key, value in model_selection_config_updates(result, model_cfg).items():
+ for key, value in updates.items():
if value is None:
model_cfg.pop(key, None)
else:
@@ -1828,13 +1832,24 @@ def persist_model_selection(result: ModelSwitchResult, config_path: Any = None)
Build the complete selection from one raw snapshot, preserving sibling settings and secret
references, then publish once. Per-key publication can leave a mixed route after a failed
write or an overlapping selection. ``should_clear_context_pin`` can do cold-start disk I/O
- — async callers run this on a worker thread."""
+ — async callers run this on a worker thread.
+
+ The replace deletes keys missing from the snapshot, so every route decision (and its disk
+ I/O) is made from a pre-read BEFORE the snapshot; read -> merge -> replace is then a pure
+ in-memory section. Only when another writer changed ``model:`` in between are the updates
+ recomputed against the fresh block. ``_CONFIG_LOCK`` is in-process only: a cross-process
+ config lock, once one exists, must wrap the same section."""
from pathlib import Path
from hermes_cli.config import _CONFIG_LOCK, atomic_config_replace, get_config_path, read_user_config_raw
path = Path(config_path) if config_path else get_config_path()
+ planned_from = read_user_config_raw(path).get("model")
+ updates = model_selection_config_updates(result, planned_from)
with _CONFIG_LOCK:
config = read_user_config_raw(path)
- config["model"] = apply_model_selection(config.get("model"), result)
+ model_cfg = config.get("model")
+ if model_cfg != planned_from:
+ updates = model_selection_config_updates(result, model_cfg)
+ config["model"] = _merge_selection_updates(model_cfg, updates)
atomic_config_replace(path, config)
try: # owner-only: config files contain API keys
os.chmod(path, 0o600)
diff --git a/tests/hermes_cli/test_model_selection_atomic_persistence.py b/tests/hermes_cli/test_model_selection_atomic_persistence.py
index e369f966679..50efdea324c 100644
--- a/tests/hermes_cli/test_model_selection_atomic_persistence.py
+++ b/tests/hermes_cli/test_model_selection_atomic_persistence.py
@@ -61,7 +61,7 @@ def profile_config(tmp_path, monkeypatch):
path.write_text(_SEED, encoding="utf-8")
yield path
assert (
- default_config.read_text(encoding="utf-8") == "model: default-profile-model\n"
+ default_config.read_text(encoding="utf-8-sig") == "model: default-profile-model\n"
)
@@ -75,7 +75,7 @@ def test_persist_publishes_only_a_complete_model_route(profile_config, monkeypat
result = replace(source, target)
if Path(target) == profile_config:
published.append(
- yaml.safe_load(profile_config.read_text(encoding="utf-8"))["model"]
+ yaml.safe_load(profile_config.read_text(encoding="utf-8-sig"))["model"]
)
return result
@@ -93,7 +93,7 @@ def test_failed_route_publication_leaves_original_bytes(profile_config, monkeypa
def reject_new_provider(source, target):
if Path(target) == profile_config:
- pending = yaml.safe_load(Path(source).read_text(encoding="utf-8"))
+ pending = yaml.safe_load(Path(source).read_text(encoding="utf-8-sig"))
if pending["model"]["provider"] == _RESULT.target_provider:
raise OSError("synthetic publication failure")
return replace(source, target)
@@ -105,6 +105,38 @@ def test_failed_route_publication_leaves_original_bytes(profile_config, monkeypa
assert profile_config.read_bytes() == original
+def test_setting_saved_while_route_is_decided_survives(profile_config, monkeypatch):
+ """Another process saving a setting during the (I/O-capable) route decision is not erased."""
+ from hermes_cli import model_switch, route_identity
+
+ decide = route_identity.should_clear_context_pin
+ writer = (
+ "import sys, utils\n"
+ "utils.atomic_roundtrip_yaml_update(sys.argv[1], 'display.theme', 'dark')\n"
+ )
+ wrote = []
+
+ def decide_while_other_process_saves(*args):
+ if not wrote:
+ wrote.append(True)
+ subprocess.run(
+ [sys.executable, "-c", writer, str(profile_config)],
+ cwd=Path(model_switch.__file__).resolve().parents[1],
+ check=True,
+ capture_output=True,
+ timeout=60,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ return decide(*args)
+
+ monkeypatch.setattr(route_identity, "should_clear_context_pin", decide_while_other_process_saves)
+ persist_model_selection(_RESULT, profile_config)
+
+ saved = yaml.safe_load(profile_config.read_text(encoding="utf-8-sig"))
+ assert wrote and saved["display"]["theme"] == "dark"
+ assert saved["model"] == _EXPECTED
+
+
def test_same_route_preserves_raw_references_and_siblings(profile_config):
seed = _SEED.replace(" context_length: 32000\n", "")
profile_config.write_text(seed, encoding="utf-8")
@@ -118,7 +150,7 @@ def test_same_route_preserves_raw_references_and_siblings(profile_config):
)
persist_model_selection(same_route, profile_config)
- text = profile_config.read_text(encoding="utf-8")
+ text = profile_config.read_text(encoding="utf-8-sig")
assert yaml.safe_load(text) == yaml.safe_load(seed)
assert "# Keep this header" in text
assert '"keep-this" # Keep this slot' in text
@@ -160,7 +192,7 @@ def test_overlapping_process_selection_cannot_leave_a_mixed_route(
monkeypatch.setattr(utils, "atomic_replace", interleave)
persist_model_selection(_RESULT, profile_config)
- block = yaml.safe_load(profile_config.read_text(encoding="utf-8"))["model"]
+ block = yaml.safe_load(profile_config.read_text(encoding="utf-8-sig"))["model"]
assert block == {
**_EXPECTED,
"default": "other-model",
@@ -184,7 +216,7 @@ def test_unreadable_config_is_not_replaced(profile_config, content):
def test_missing_config_gets_the_complete_route(profile_config):
profile_config.unlink()
persist_model_selection(_RESULT, profile_config)
- assert yaml.safe_load(profile_config.read_text(encoding="utf-8")) == {
+ assert yaml.safe_load(profile_config.read_text(encoding="utf-8-sig")) == {
"model": {
key: value for key, value in _EXPECTED.items() if key != "model_slots"
},