Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

perf(server): cache the parsed config.yaml by file identity

alan_cheng7daa0d2ec0be
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index 5b9523a45f..26c42010ed 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -135,12 +135,64 @@ def _normalize_config(config: dict[str, Any] | None) -> None:
_ch_conf["send_file_allowed"] = True
+# Parsed YAML per file path, keyed on the file's identity so an edit — by this
+# process or any other — invalidates it. Only the parse is cached: reading and
+# parsing config.yaml costs ~11 ms while everything downstream of it (env
+# resolution, normalization) costs ~0.3 ms, and ``get_config`` sits on every
+# request path. Deliberately not caching past the parse keeps env var changes
+# (``load_dotenv_runtime`` runs with override=True before some reads) taking
+# effect immediately, so this needs no explicit invalidation hook.
+_YAML_PARSE_CACHE: dict[str, tuple[tuple[int, int], dict[str, Any]]] = {}
+_YAML_PARSE_CACHE_LOCK = threading.Lock()
+
+
+def _yaml_file_stamp(filepath: Path) -> tuple[int, int] | None:
+ """Return the identity a cached parse of this file is keyed on.
+
+ Args:
+ filepath: YAML file to stamp.
+
+ Returns:
+ ``(mtime_ns, size)``, or None when the file cannot be stat'd — in which
+ case the caller must not use or populate the cache.
+ """
+ try:
+ stat_result = filepath.stat()
+ except OSError:
+ return None
+ return stat_result.st_mtime_ns, stat_result.st_size
+
+
def _read_with_retry(filepath: Path, max_attempts: int = 3) -> dict[str, Any]:
- """读取 YAML,遇解析错误重试(应对跨进程写竞态)。"""
+ """读取 YAML,遇解析错误重试(应对跨进程写竞态)。
+
+ 解析结果按文件身份(mtime + size)缓存;调用方会就地修改返回值
+ (``_normalize_config`` 即是),故命中与写入缓存时都做深拷贝,
+ 保证各调用方拿到互不影响的副本。
+
+ Args:
+ filepath: 待读取的 YAML 文件路径。
+ max_attempts: 解析失败时的最大尝试次数。
+
+ Returns:
+ 解析后的字典;文件为空时返回空字典。
+ """
+ stamp = _yaml_file_stamp(filepath)
+ cache_key = str(filepath)
+ if stamp is not None:
+ with _YAML_PARSE_CACHE_LOCK:
+ cached = _YAML_PARSE_CACHE.get(cache_key)
+ if cached is not None and cached[0] == stamp:
+ return deepcopy(cached[1])
+
for attempt in range(max_attempts):
try:
with open(filepath, "r", encoding="utf-8") as f:
- return yaml.safe_load(f) or {}
+ parsed = yaml.safe_load(f) or {}
+ if stamp is not None:
+ with _YAML_PARSE_CACHE_LOCK:
+ _YAML_PARSE_CACHE[cache_key] = (stamp, deepcopy(parsed))
+ return parsed
except yaml.YAMLError:
if attempt < max_attempts - 1:
time.sleep(0.05 * (attempt + 1))
diff --git a/tests/unit_tests/common/test_config_parse_cache.py b/tests/unit_tests/common/test_config_parse_cache.py
new file mode 100644
index 0000000000..fab0462593
--- /dev/null
+++ b/tests/unit_tests/common/test_config_parse_cache.py
@@ -0,0 +1,113 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for the config.yaml parse cache."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.common import config as config_module
+from jiuwenswarm.common.config import _read_with_retry
+
+
[email protected](name="yaml_file")
+def _yaml_file(tmp_path: Path) -> Path:
+ """Write a small YAML file and clear the cache around the test."""
+ path = tmp_path / "config.yaml"
+ path.write_text("alpha: 1\nnested:\n key: value\n", encoding="utf-8")
+ config_module._YAML_PARSE_CACHE.clear()
+ yield path
+ config_module._YAML_PARSE_CACHE.clear()
+
+
+def _parse_count(monkeypatch: pytest.MonkeyPatch) -> dict[str, int]:
+ """Count how often the YAML parser actually runs."""
+ calls = {"n": 0}
+ real_load = config_module.yaml.safe_load
+
+ def _counting_load(stream):
+ calls["n"] += 1
+ return real_load(stream)
+
+ monkeypatch.setattr(config_module.yaml, "safe_load", _counting_load)
+ return calls
+
+
+def test_repeat_reads_parse_once(yaml_file: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The parse is the expensive part, so it must not repeat."""
+ calls = _parse_count(monkeypatch)
+
+ for _ in range(5):
+ assert _read_with_retry(yaml_file) == {"alpha": 1, "nested": {"key": "value"}}
+
+ assert calls["n"] == 1
+
+
+def test_edit_invalidates_the_cache(yaml_file: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A rewritten file must be re-parsed, not served from cache."""
+ calls = _parse_count(monkeypatch)
+ _read_with_retry(yaml_file)
+
+ yaml_file.write_text("alpha: 2\n", encoding="utf-8")
+ # Size differs here; the stamp also carries mtime for same-size edits.
+ assert _read_with_retry(yaml_file) == {"alpha": 2}
+ assert calls["n"] == 2
+
+
+def test_same_size_edit_still_invalidates(
+ yaml_file: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Byte-identical length must not defeat invalidation."""
+ yaml_file.write_text("alpha: 1\n", encoding="utf-8")
+ calls = _parse_count(monkeypatch)
+ _read_with_retry(yaml_file)
+
+ stat_result = yaml_file.stat()
+ yaml_file.write_text("alpha: 9\n", encoding="utf-8")
+ os.utime(yaml_file, ns=(stat_result.st_atime_ns, stat_result.st_mtime_ns + 1_000_000))
+
+ assert _read_with_retry(yaml_file) == {"alpha": 9}
+ assert calls["n"] == 2
+
+
+def test_callers_get_independent_copies(yaml_file: Path) -> None:
+ """Downstream mutates the result in place, so copies must not be shared.
+
+ ``_normalize_config`` edits the dict it is handed; sharing one object across
+ callers would let it accumulate normalizations into the cache.
+ """
+ first = _read_with_retry(yaml_file)
+ first["injected"] = True
+ first["nested"]["key"] = "mutated"
+
+ second = _read_with_retry(yaml_file)
+
+ assert "injected" not in second
+ assert second["nested"]["key"] == "value"
+
+
+def test_missing_file_is_not_cached(tmp_path: Path) -> None:
+ """An unstattable path must fall through rather than poison the cache."""
+ missing = tmp_path / "absent.yaml"
+
+ with pytest.raises(OSError):
+ _read_with_retry(missing)
+
+ assert str(missing) not in config_module._YAML_PARSE_CACHE
+
+
+def test_distinct_paths_do_not_collide(tmp_path: Path) -> None:
+ """Two config files must not serve each other's contents."""
+ config_module._YAML_PARSE_CACHE.clear()
+ first = tmp_path / "a.yaml"
+ second = tmp_path / "b.yaml"
+ first.write_text("which: a\n", encoding="utf-8")
+ second.write_text("which: b\n", encoding="utf-8")
+
+ assert _read_with_retry(first) == {"which": "a"}
+ assert _read_with_retry(second) == {"which": "b"}
+ assert _read_with_retry(first) == {"which": "a"}