Skip to content

The agent that grows with you

fix(moa): preserve strict reads and serialize config updates

Tharanee6ca3d65ae74e
diff --git a/hermes_cli/web_routers/models.py b/hermes_cli/web_routers/models.py
index 7a742fa845b..43c7e06e721 100644
--- a/hermes_cli/web_routers/models.py
+++ b/hermes_cli/web_routers/models.py
@@ -29,7 +29,7 @@ _config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_pro
_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
load_config = late("load_config", "hermes_cli.config")
save_config = late("save_config", "hermes_cli.config")
-read_raw_config = late("read_raw_config", "hermes_cli.config")
+require_readable_config_before_write = late("require_readable_config_before_write", "hermes_cli.config")
_EMPTY_MODEL_INFO: dict = {
@@ -304,12 +304,12 @@ def _preset_dict(preset) -> dict:
def set_moa_models(body: MoaConfigPayload, profile: Optional[str] = None):
"""Persist the Mixture-of-Agents provider/model slots."""
with http_failure("PUT /api/model/moa failed", 500, detail="Failed to save MoA config"):
+ from hermes_cli import config as config_mod
from hermes_cli.moa_config import normalize_moa_config, validate_moa_payload
- # load→mutate→save runs on a worker thread (sync-def endpoint); the
- # desktop's debounced PUT /api/config autosave races it, so the whole
- # span holds _CONFIG_MUTATION_LOCK or one of the two saves is dropped.
- with config_write_scope(body.profile or profile):
+ # Serialize the full RMW with dashboard autosaves and with non-HTTP
+ # save_config callers, which only hold the config module's reentrant lock.
+ with config_write_scope(body.profile or profile), config_mod._CONFIG_LOCK:
legacy_flat_update = not body.presets
if not legacy_flat_update:
raw = {
@@ -333,7 +333,9 @@ def set_moa_models(body: MoaConfigPayload, profile: Optional[str] = None):
# ``merge_existing=True`` deep-merges dicts, which resurrects omitted preset names.
# Keep unknown MoA keys and sibling sections by rebuilding only the MoA section on
# the raw document, while treating the submitted named map as authoritative.
- raw_cfg = read_raw_config()
+ # Strict read: the merge below builds a new dict and would discard the
+ # failed-read marker, allowing a transient fallback to replace the file.
+ raw_cfg = require_readable_config_before_write()
existing_moa = raw_cfg.get("moa")
if isinstance(existing_moa, dict) and "privacy_filter" in existing_moa:
# ``privacy_filter`` is emitted by the normalizer but is not declared by
@@ -359,7 +361,6 @@ def set_moa_models(body: MoaConfigPayload, profile: Optional[str] = None):
existing_active = existing_moa.get("active_preset")
if isinstance(existing_active, str) and existing_active in existing_presets:
normalized["active_preset"] = existing_active
- from hermes_cli import config as config_mod
updated = config_mod._merge_partial_save(raw_cfg, {"moa": normalized})
if not legacy_flat_update:
# ``_merge_partial_save`` retains undeclared metadata on surviving presets;
diff --git a/tests/hermes_cli/test_moa_preset_deletion.py b/tests/hermes_cli/test_moa_preset_deletion.py
index f2756469240..0cb491cc40e 100644
--- a/tests/hermes_cli/test_moa_preset_deletion.py
+++ b/tests/hermes_cli/test_moa_preset_deletion.py
@@ -14,10 +14,12 @@ merge that caused the bug.
from __future__ import annotations
+import errno
import json
import os
import subprocess
import sys
+import threading
from pathlib import Path
import pytest
@@ -87,6 +89,87 @@ def test_omitted_preset_is_deleted_from_disk(tmp_path, monkeypatch):
assert set(presets) == {"keep_a", "keep_b"}
+def test_deletion_survives_autosave_restart_and_backup_with_sparse_yaml(tmp_path, monkeypatch):
+ """The real HTTP save keeps user YAML intact and never revives omitted names."""
+ from starlette.testclient import TestClient
+
+ from hermes_cli.config import load_config, read_raw_config
+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app
+
+ moa = _three_presets()
+ moa.update(privacy_filter="full", save_traces=True, trace_dir="/custom/traces")
+ moa["presets"]["keep_a"]["operator_note"] = None
+ _seed(tmp_path, monkeypatch, moa)
+ config_path = tmp_path / "config.yaml"
+ untouched = (
+ '# Operator rationale\n'
+ 'operator_settings:\n'
+ ' keep: null # explicit null, not an omitted key\n'
+ ' label: "off"\n\n'
+ )
+ config_path.write_text(untouched + config_path.read_text(encoding="utf-8"), encoding="utf-8")
+ # Backup filenames have second precision. Model a later edit explicitly so
+ # this checks MoA fallback merging, not the upstream same-second collision
+ # (which can leave ANY config setting's backup stale).
+ from hermes_cli import config_backups
+
+ with monkeypatch.context() as clock:
+ clock.setattr(config_backups.time, "strftime", lambda _fmt: "20000101-000000")
+ # Prime both caches before deleting; subsequent reads must see the save.
+ assert "doomed" in read_raw_config()["moa"]["presets"]
+ assert "doomed" in load_config()["moa"]["presets"]
+ client = TestClient(app)
+ client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
+ survivors = {"keep_a", "keep_b"}
+ response = client.put("/api/model/moa", json={
+ "default_preset": "keep_a",
+ "presets": {name: _preset("gpt-5.8").model_dump() for name in sorted(survivors)},
+ })
+ assert response.status_code == 200, response.text
+ assert set(read_raw_config()["moa"]["presets"]) == survivors
+ effective = client.get("/api/config")
+ assert effective.status_code == 200, effective.text
+ assert set(effective.json()["moa"]["presets"]) == survivors
+
+ # Desktop settings autosave sends only edited keys, not its stale MoA snapshot.
+ autosave = client.put("/api/config", json={"config": {"display": {"skin": "mono"}}})
+ assert autosave.status_code == 200, autosave.text
+ saved = _on_disk(tmp_path)
+ assert set(saved["moa"]["presets"]) == survivors
+ assert saved["operator_settings"] == {"keep": None, "label": "off"}
+ assert saved["moa"]["presets"]["keep_a"]["operator_note"] is None
+ assert saved["moa"]["privacy_filter"] == "full"
+ assert saved["moa"]["save_traces"] is True
+ assert saved["moa"]["trace_dir"] == "/custom/traces"
+ assert saved["display"]["skin"] == "mono"
+ assert "terminal" not in saved, "effective defaults leaked into sparse YAML"
+ text = config_path.read_text(encoding="utf-8")
+ # The round-trip writer may spell YAML null as an empty value; preserve
+ # its semantic value (asserted above), comments, quoting and key order.
+ assert text.startswith("# Operator rationale\noperator_settings:\n")
+ assert "# explicit null, not an omitted key" in text
+ assert ' label: "off"\n\n' in text
+ assert list(saved)[:2] == ["operator_settings", "moa"]
+
+ # Fresh imports use the actual saved YAML, then the persisted last-good backup.
+ probe = (
+ "import json; from hermes_cli.config import load_config; "
+ "print(json.dumps(sorted(load_config()['moa']['presets'])))"
+ )
+ for broken in (False, True):
+ if broken:
+ config_path.write_text("moa: [unterminated\n", encoding="utf-8")
+ result = subprocess.run(
+ [sys.executable, "-B", "-c", probe],
+ cwd=Path(__file__).resolve().parents[2],
+ env={**os.environ, "HERMES_HOME": str(tmp_path)},
+ capture_output=True, text=True, check=True, timeout=30,
+ )
+ assert json.loads(result.stdout.splitlines()[-1]) == sorted(survivors)
+ if broken:
+ assert set(load_config()["moa"]["presets"]) == survivors
+
+
def test_deletion_preserves_undeclared_moa_keys_and_other_sections(tmp_path, monkeypatch):
"""Authoritative presets must not cost us #58819 (save_traces) or #89184 (siblings)."""
home = tmp_path / ".hermes"
@@ -111,6 +194,107 @@ def test_deletion_preserves_undeclared_moa_keys_and_other_sections(tmp_path, mon
assert on_disk["fallback_providers"] == chain, "MoA save clobbered fallback_providers (#89184)"
[email protected]("legacy", [False, True], ids=["named", "legacy-flat"])
+def test_moa_save_preserves_a_concurrent_partial_config_write(tmp_path, monkeypatch, legacy):
+ """A writer outside the dashboard lock must not lose its update to a stale MoA read."""
+ from concurrent.futures import ThreadPoolExecutor
+
+ from starlette.testclient import TestClient
+
+ from hermes_cli import config as config_mod
+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app
+
+ _seed(tmp_path, monkeypatch, _three_presets(), display={"skin": "slate"})
+ read_complete, resume_read = threading.Event(), threading.Event()
+ real_read = config_mod.require_readable_config_before_write
+
+ def gated_read(*args, **kwargs):
+ raw = real_read(*args, **kwargs)
+ if not read_complete.is_set():
+ read_complete.set()
+ assert resume_read.wait(30), "concurrent writer never reached the config lock"
+ return raw
+
+ def write_other_setting():
+ assert read_complete.wait(30), "MoA save never read the config"
+ # If MoA owns the RMW lock, let it finish before this writer proceeds.
+ # Otherwise land this update inside its read/save gap, without a timing race.
+ acquired = config_mod._CONFIG_LOCK.acquire(blocking=False)
+ try:
+ if not acquired:
+ resume_read.set()
+ config_mod.save_config({"display": {"skin": "mono"}}, merge_existing=True)
+ finally:
+ if acquired:
+ config_mod._CONFIG_LOCK.release()
+ resume_read.set()
+
+ monkeypatch.setattr(config_mod, "require_readable_config_before_write", gated_read)
+ payload = (
+ _preset("gpt-5.8").model_dump()
+ if legacy else
+ {"default_preset": "keep_a", "presets": {"keep_a": _preset("gpt-5.8").model_dump()}}
+ )
+ client = TestClient(app)
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ moa_save = pool.submit(
+ client.put, "/api/model/moa", json=payload,
+ headers={_SESSION_HEADER_NAME: _SESSION_TOKEN},
+ )
+ other_save = pool.submit(write_other_setting)
+ try:
+ response = moa_save.result(timeout=60)
+ other_save.result(timeout=60)
+ finally:
+ resume_read.set()
+ assert response.status_code == 200, response.text
+ saved = _on_disk(tmp_path)
+ assert saved["display"]["skin"] == "mono"
+ assert set(saved["moa"]["presets"]) == ({"keep_a", "doomed", "keep_b"} if legacy else {"keep_a"})
+ assert saved["moa"]["presets"]["keep_a"]["reference_models"][0]["model"] == "gpt-5.8"
+
+
[email protected]("legacy", [False, True], ids=["named", "legacy-flat"])
+def test_moa_save_refuses_transient_read_failure_without_losing_config(tmp_path, monkeypatch, legacy):
+ """A recovered second read must not turn the first read's fallback into a full write."""
+ from starlette.testclient import TestClient
+
+ from hermes_cli import config as config_mod
+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app
+
+ _seed(tmp_path, monkeypatch, _three_presets(), operator_settings={"keep": None})
+ config_path = tmp_path / "config.yaml"
+ before = config_path.read_bytes()
+ real_load = config_mod.fast_safe_load
+ failed_reads = []
+
+ def fail_once(stream):
+ if getattr(stream, "name", None) == str(config_path) and not failed_reads:
+ failed_reads.append(str(config_path))
+ raise OSError(errno.EMFILE, "Too many open files")
+ return real_load(stream)
+
+ monkeypatch.setattr(config_mod, "fast_safe_load", fail_once)
+ payload = (
+ _preset("gpt-5.8").model_dump()
+ if legacy else
+ {"default_preset": "keep_a", "presets": {"keep_a": _preset("gpt-5.8").model_dump()}}
+ )
+ client = TestClient(app)
+ headers = {_SESSION_HEADER_NAME: _SESSION_TOKEN}
+ refused = client.put("/api/model/moa", json=payload, headers=headers)
+ assert failed_reads == [str(config_path)]
+ assert refused.status_code == 500, refused.text
+ assert config_path.read_bytes() == before
+
+ retry = client.put("/api/model/moa", json=payload, headers=headers)
+ assert retry.status_code == 200, retry.text
+ saved = _on_disk(tmp_path)
+ assert saved["operator_settings"] == {"keep": None}
+ assert set(saved["moa"]["presets"]) == ({"keep_a", "doomed", "keep_b"} if legacy else {"keep_a"})
+ assert saved["moa"]["presets"]["keep_a"]["reference_models"][0]["model"] == "gpt-5.8"
+
+
def test_adding_a_preset_still_works(tmp_path, monkeypatch):
"""Authoritative writes must not break the add/edit path."""
home = tmp_path / ".hermes"
diff --git a/tests/hermes_cli/test_moa_set_models_preserves_extra_keys.py b/tests/hermes_cli/test_moa_set_models_preserves_extra_keys.py
index 5db29bcfdc1..f47dd4a3f8a 100644
--- a/tests/hermes_cli/test_moa_set_models_preserves_extra_keys.py
+++ b/tests/hermes_cli/test_moa_set_models_preserves_extra_keys.py
@@ -58,7 +58,7 @@ class TestSetMoaModelsPreservesUndeclaredKeys:
saved_cfg = {}
- def fake_read_raw_config():
+ def fake_readable_config():
return dict(existing_cfg) # shallow copy
def fake_save_config(cfg, **_kwargs):
@@ -67,7 +67,7 @@ class TestSetMoaModelsPreservesUndeclaredKeys:
payload = _base_payload()
with (
- patch("hermes_cli.config.read_raw_config", side_effect=fake_read_raw_config),
+ patch("hermes_cli.config.require_readable_config_before_write", side_effect=fake_readable_config),
patch("hermes_cli.config.save_config", side_effect=fake_save_config),
patch("hermes_cli.web_server_profiles._profile_scope"),
):