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(common): 使用 CSafeLoader 加速 YAML 配置解析

wangjiudong11baea2adddd
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.py
index a3f3c60094..a117ae3b3d 100644
--- a/jiuwenswarm/common/utils.py
+++ b/jiuwenswarm/common/utils.py
@@ -432,11 +432,13 @@ def fill_template_defaults(
def load_yaml_dict(path: Path) -> dict[str, Any]:
- """用 yaml.safe_load 读取 YAML 文件为 dict;不存在或无效时返回空 dict。"""
+ """安全读取 YAML 字典;缺失或非映射返回空字典,解析错误仍抛出。"""
+ # C 实现减少解析开销;未安装 LibYAML 的环境仍使用原有安全解析器。
+ loader = getattr(yaml, "CSafeLoader", yaml.SafeLoader)
if not path.exists():
return {}
with open(path, "r", encoding="utf-8") as f:
- data = yaml.safe_load(f)
+ data = yaml.load(f, Loader=loader)
return data if isinstance(data, dict) else {}
diff --git a/tests/unit_tests/common/test_utils_yaml_loader.py b/tests/unit_tests/common/test_utils_yaml_loader.py
new file mode 100644
index 0000000000..b799133e13
--- /dev/null
+++ b/tests/unit_tests/common/test_utils_yaml_loader.py
@@ -0,0 +1,91 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""只读 YAML 解析器的兼容性、安全限制及 C 扩展回退。"""
+
+import pytest
+import yaml
+
+from jiuwenswarm.common import utils
+
+
[email protected](not hasattr(yaml, "CSafeLoader"), reason="当前 PyYAML 未提供 C 扩展")
+def test_each_of_four_loads_uses_c_safe_loader_without_caching(tmp_path, monkeypatch):
+ template, user = tmp_path / "template.yaml", tmp_path / "user.yaml"
+ template.write_text("nested:\n value: 1\n", encoding="utf-8")
+ user.write_text("message: 中文\n", encoding="utf-8")
+ calls = []
+ original = yaml.load
+
+ def counted_load(stream, Loader):
+ calls.append((stream.name, Loader))
+ return original(stream, Loader=Loader)
+
+ monkeypatch.setattr(yaml, "load", counted_load)
+ first = utils.load_yaml_dict(template)
+ first["nested"]["value"] = 99
+ assert utils.load_yaml_dict(template) == {"nested": {"value": 1}}
+ assert utils.load_yaml_dict(template) == {"nested": {"value": 1}}
+ assert utils.load_yaml_dict(user) == {"message": "中文"}
+ assert calls == [
+ (str(path), yaml.CSafeLoader) for path in (template, template, template, user)
+ ]
+
+
+def test_safe_loader_fallback_when_c_extension_is_unavailable(tmp_path, monkeypatch):
+ monkeypatch.delattr(yaml, "CSafeLoader", raising=False)
+ config = tmp_path / "fallback.yaml"
+ config.write_text("message: 中文\nflag: true\n", encoding="utf-8")
+ calls = []
+ original = yaml.load
+
+ def counted_load(stream, Loader):
+ calls.append(Loader)
+ return original(stream, Loader=Loader)
+
+ monkeypatch.setattr(yaml, "load", counted_load)
+ assert utils.load_yaml_dict(config) == {"message": "中文", "flag": True}
+ assert calls == [yaml.SafeLoader]
+
+
+def _typed(value):
+ if isinstance(value, dict):
+ return type(value), frozenset((_typed(k), _typed(v)) for k, v in value.items())
+ if isinstance(value, (tuple, list)):
+ return type(value), tuple(_typed(v) for v in value)
+ return type(value), value
+
+
+ "message: 你好 👋\nprompt: |\n 第一行\n second line\nenv: ${UNSET_VALUE:-default}\n",
+ "defaults: &defaults\n flag: true\n retries: 3\nagent:\n <<: *defaults\n retries: 4\n",
+ "yes_value: yes\nfalse_value: off\nnone_value: null\nhex: 0x10\noctal: 012\nfloat: 1.5\nquoted: '001'\n",
+ "date: 2026-10-16\ntimestamp: 2026-10-16T07:00:00Z\nbinary: !!binary aGVsbG8=\n",
+ "duplicate: first\nduplicate: last\n",
+ "# 空配置\n",
+ "[one, two]\n",
+ "scalar\n",
+])
+def test_values_and_types_match_safe_load(tmp_path, text):
+ config = tmp_path / "compatibility.yaml"
+ config.write_text(text, encoding="utf-8")
+ expected = yaml.safe_load(text)
+ result = utils.load_yaml_dict(config)
+ assert _typed(result) == _typed(expected if isinstance(expected, dict) else {})
+
+
+ "value: [unterminated\n",
+ "value: !unknown data\n",
+ "value: !!python/object/apply:builtins.str [123]\n",
+ "first: 1\n---\nsecond: 2\n",
+])
+def test_invalid_documents_and_python_object_tags_remain_rejected(tmp_path, text):
+ config = tmp_path / "invalid.yaml"
+ config.write_text(text, encoding="utf-8")
+ with pytest.raises(yaml.YAMLError) as caught:
+ utils.load_yaml_dict(config)
+ assert caught.value.problem_mark.name == str(config)
+
+
+def test_missing_file_still_returns_empty_mapping(tmp_path):
+ assert utils.load_yaml_dict(tmp_path / "missing.yaml") == {}