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): 缓存语言解析,消除冷启动租户播种的重复 YAML 解析
abundantshfd5916930eb2
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.pyindex d17658bf69..7bb0df20ff 100644--- a/jiuwenswarm/common/utils.py+++ b/jiuwenswarm/common/utils.py@@ -681,6 +681,37 @@ def _find_package_root() -> Path | None:return current+# 播种在冷启动时按租户逐次调用,每次都要重解析出厂模板,故按文件 mtime/size 缓存语言解析结果。+_PREFERRED_LANGUAGE_CACHE: dict[str, tuple[tuple[int, int], str | None]] = {}+++def _read_preferred_language_cached(cfg_path: Path) -> str | None:+ """读取该路径声明的 zh/en;文件缺失、解析异常或值非法时返回 None。"""+ try:+ st = cfg_path.stat()+ except OSError:+ return None+ cache_key = str(cfg_path)+ stamp = (st.st_mtime_ns, st.st_size)+ cached = _PREFERRED_LANGUAGE_CACHE.get(cache_key)+ if cached is not None and cached[0] == stamp:+ # 缓存也记住“该路径无有效语言”,但解析异常不缓存,保持每次报错可见。+ return cached[1]+ value: str | None = None+ try:+ rt = YAML()+ with open(cfg_path, "r", encoding="utf-8") as f:+ data = rt.load(f) or {}+ lang = str(data.get("preferred_language") or "").strip().lower()+ if lang in ("zh", "en"):+ value = lang+ except Exception as e:+ logger.error(f"Failed to load config.yaml: {e}")+ return None+ _PREFERRED_LANGUAGE_CACHE[cache_key] = (stamp, value)+ return value++def _resolve_preferred_language(config_yaml_dest: Path, explicit: Optional[str]) -> str:@@ -690,16 +721,9 @@ def _resolve_preferred_language(return lang if lang in ("zh", "en") else "zh"# 稀疏 override 模式:先读 override,再读模板for cfg_path in (config_yaml_dest, resolve_shipped_template_config_path()):- if cfg_path.exists():- try:- rt = YAML()- with open(cfg_path, "r", encoding="utf-8") as f:- data = rt.load(f) or {}- lang = str(data.get("preferred_language") or "").strip().lower()- if lang in ("zh", "en"):- return lang- except Exception as e:- logger.error(f"Failed to load config.yaml: {e}")+ lang = _read_preferred_language_cached(cfg_path)+ if lang is not None:+ return langreturn "zh"diff --git a/tests/unit_tests/agentserver/test_deepresearch_document_rewrite.py b/tests/unit_tests/agentserver/test_deepresearch_document_rewrite.pyindex 36ec53da07..7996dfa017 100644--- a/tests/unit_tests/agentserver/test_deepresearch_document_rewrite.py+++ b/tests/unit_tests/agentserver/test_deepresearch_document_rewrite.py@@ -2149,7 +2149,14 @@ def test_context_store_is_bounded_and_evicts_earliest_expiry(with rewrite_module._CONTEXT_LOCK:rewrite_module._CONTEXTS.clear()- tokens = [_prepare(tmp_path, report, "text")["context_token"] for _ in range(5)]+ # 连续 _prepare 可能落在同一个单调时钟 tick,expires_at 相同时淘汰会退化为按 token 字符串比较;+ # 显式让每个 token 的过期时间严格递增,使"最早过期"没有歧义。+ tokens = []+ for _ in range(5):+ token = _prepare(tmp_path, report, "text")["context_token"]+ with rewrite_module._CONTEXT_LOCK:+ rewrite_module._CONTEXTS[token].expires_at = rewrite_module.time.monotonic() + len(tokens)+ tokens.append(token)with rewrite_module._CONTEXT_LOCK:assert len(rewrite_module._CONTEXTS) == 3@@ -2178,7 +2185,14 @@ def test_context_is_compact_under_large_citation_cache_saturation(with rewrite_module._CONTEXT_LOCK:rewrite_module._CONTEXTS.clear()- tokens = [_prepare(tmp_path, report, "claim")["context_token"] for _ in range(5)]+ # 同 test_context_store_is_bounded_and_evicts_earliest_expiry:+ # 让每个 token 的过期时间严格递增,避免同一时钟 tick 下淘汰顺序不确定。+ tokens = []+ for _ in range(5):+ token = _prepare(tmp_path, report, "claim")["context_token"]+ with rewrite_module._CONTEXT_LOCK:+ rewrite_module._CONTEXTS[token].expires_at = rewrite_module.time.monotonic() + len(tokens)+ tokens.append(token)with rewrite_module._CONTEXT_LOCK:assert set(rewrite_module._CONTEXTS) == set(tokens[-3:])diff --git a/tests/unit_tests/test_utils.py b/tests/unit_tests/test_utils.pyindex 40ae2dc0c8..88fa1bc9e3 100644--- a/tests/unit_tests/test_utils.py+++ b/tests/unit_tests/test_utils.py@@ -822,3 +822,127 @@ class TestWorkspaceToJiuwenclawWorkspaceMigration:)new_ws = agent_root / "jiuwenclaw_workspace"assert projects["projects"][0]["project_dir"] == str(new_ws / "work" / "demo")+++class TestPreferredLanguageResolutionCache:+ """语言解析结果按文件 mtime/size 缓存,避免播种路径重复解析 YAML。"""++ @staticmethod+ def _isolate_cache(monkeypatch):+ """替换模块级缓存字典,避免用例间互相污染。"""+ monkeypatch.setattr(utils, "_PREFERRED_LANGUAGE_CACHE", {})++ @staticmethod+ def _count_yaml_parses(monkeypatch):+ """包装 utils.YAML,统计构造次数(每次构造即一次解析)。"""+ counts = {"n": 0}+ real_yaml = utils.YAML++ class _CountingYAML:+ def __init__(self, *args, **kwargs):+ counts["n"] += 1+ self._inner = real_yaml(*args, **kwargs)++ def __getattr__(self, name):+ return getattr(self._inner, name)++ monkeypatch.setattr(utils, "YAML", _CountingYAML)+ return counts++ def test_same_config_parsed_once(self, monkeypatch, tmp_path: Path):+ """同一份配置重复解析,只应真正读一次 YAML。"""+ cfg = tmp_path / "config.yaml"+ cfg.write_text("preferred_language: en\n", encoding="utf-8")+ self._isolate_cache(monkeypatch)+ counts = self._count_yaml_parses(monkeypatch)++ for _ in range(3):+ assert utils._resolve_preferred_language(cfg, None) == "en"++ assert counts["n"] == 1++ def test_seed_repeated_call_parses_once(self, monkeypatch, tmp_path: Path):+ """同一租户重复播种,语言解析同样只应读一次 YAML。"""+ cfg = tmp_path / "config.yaml"+ cfg.write_text("preferred_language: en\n", encoding="utf-8")+ tenant = tmp_path / "service_s" / "agent_a"+ tenant.mkdir(parents=True)+ self._isolate_cache(monkeypatch)+ counts = self._count_yaml_parses(monkeypatch)+ monkeypatch.setattr(utils, "get_config_file", lambda: cfg)++ for _ in range(3):+ utils.seed_tenant_agent_workspace(tenant)++ assert counts["n"] == 1++ def test_cache_invalidated_on_config_change(self, monkeypatch, tmp_path: Path):+ """config.yaml 被重写(语言切换)后,缓存须失效并读到新值。"""+ cfg = tmp_path / "config.yaml"+ cfg.write_text("preferred_language: en\n", encoding="utf-8")+ self._isolate_cache(monkeypatch)++ assert utils._resolve_preferred_language(cfg, None) == "en"++ cfg.write_text('preferred_language: "zh"\n', encoding="utf-8")+ assert utils._resolve_preferred_language(cfg, None) == "zh"++ def test_explicit_wins_and_skips_cache(self, monkeypatch, tmp_path: Path):+ """显式参数仍短路,不触发任何 YAML 解析。"""+ cfg = tmp_path / "config.yaml"+ cfg.write_text("preferred_language: zh\n", encoding="utf-8")+ self._isolate_cache(monkeypatch)+ counts = self._count_yaml_parses(monkeypatch)++ assert utils._resolve_preferred_language(cfg, "EN") == "en"+ assert utils._resolve_preferred_language(cfg, "bogus") == "zh"+ assert counts["n"] == 0+++class TestSeedTenantAgentWorkspace:+ """播种语义回归:补齐模板、单侧缺失自愈、齐全时不写文件。"""++ _TEMPLATES = (+ "AGENT.md",+ "HEARTBEAT.md",+ "IDENTITY.md",+ "SOUL.md",+ "USER.md",+ "memory/MEMORY.md",+ )++ @classmethod+ def _rel(cls):+ return utils.get_agent_workspace_relative_dir()++ def test_fills_all_templates(self, tmp_path: Path):+ tenant = tmp_path / "service_s" / "agent_a"+ tenant.mkdir(parents=True)+ utils.seed_tenant_agent_workspace(tenant)++ workspace = tenant / self._rel()+ for name in self._TEMPLATES:+ assert (workspace / name).is_file()++ def test_self_heals_single_missing_template(self, tmp_path: Path):+ tenant = tmp_path / "service_s" / "agent_a"+ tenant.mkdir(parents=True)+ utils.seed_tenant_agent_workspace(tenant)+ workspace = tenant / self._rel()++ (workspace / "SOUL.md").unlink()+ utils.seed_tenant_agent_workspace(tenant)++ assert (workspace / "SOUL.md").is_file()++ def test_no_write_when_all_present(self, tmp_path: Path):+ tenant = tmp_path / "service_s" / "agent_a"+ tenant.mkdir(parents=True)+ utils.seed_tenant_agent_workspace(tenant)+ workspace = tenant / self._rel()++ mtimes = {name: (workspace / name).stat().st_mtime_ns for name in self._TEMPLATES}+ utils.seed_tenant_agent_workspace(tenant)++ for name in self._TEMPLATES:+ assert (workspace / name).stat().st_mtime_ns == mtimes[name]