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
feat(server): break down rail construction timing
alan_cheng7f7c842c4cd0
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 7981a944ff..550a6d41e4 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -48,6 +48,7 @@ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (JiuWenSwarmDeepAdapter,_AGENT_CARD_ID,_CRON_TOOL_CHANNEL_ID,+ _RailBuildInfo,_agent_def_to_subagent_config,_deep_agent_kv_cache_affinity_config,parse_int,@@ -218,17 +219,6 @@ _TOOL_BUILD_NAMES: dict[str, str] = {}-@dataclass-class _RailBuildInfo:- """Rail 构建信息 — 统一固定和动态 Rails 的构建流程."""- attr_name: str- build_func: Callable- params: dict = None-- def __post_init__(self):- self.params = self.params or {}--def _resolve_coding_memory_dir(*,project_dir: str | None,@@ -656,57 +646,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):rail_name,)- # 统一构建并注册- rails_list = []- for info in rail_infos:- logger.info(- "[JiuwenSwarmCodeAdapter] Building rail: %s with params: %s",- info.attr_name, info.params,- )- rail_instance = info.build_func(**info.params)- if rail_instance is not None:- setattr(self, info.attr_name, rail_instance)- rails_list.append(rail_instance)- logger.info(- "[JiuwenSwarmCodeAdapter] Rail %s built successfully",- info.attr_name,- )- else:- logger.warning(- "[JiuwenSwarmCodeAdapter] Rail %s build returned None",- info.attr_name,- )- logger.info(- "[JiuwenSwarmCodeAdapter] Total rails built: %d, rail names: %s",- len(rails_list),- [type(r).__name__ for r in rails_list],- )- # 用户配置的 hooks(UserHookRail)- try:- hooks_config = load_hooks_config(config_base)- if hooks_config.events:- user_hook_rail = UserHookRail(hooks_config)- rails_list.append(user_hook_rail)- logger.info(- "[JiuwenSwarmCodeAdapter] UserHookRail loaded with %d event types",- len(hooks_config.events),- )- except Exception as e:- logger.warning("[JiuwenSwarmCodeAdapter] Failed to load UserHookRail: %s", e)- # Observability rail: opens an agent-layer span (agent.<name>.task_iteration.<n>- # for task-loop runs, or agent.<name>.invoke for single-round) under the root- # run span per iteration/round. It is the only thing that creates the- # task_iteration / invoke spans that llm.call + tool.* nest under. It- # self-disables (before_* returns early when get_team_span() is None), so- # attaching it unconditionally is safe and also adapts to runtime- # enable/disable of agent_observability without rebuilding the agent.- try:- from openjiuwen.agent_teams.observability.rail import ObservabilityRail- rails_list.append(ObservabilityRail())- logger.info("[JiuwenSwarmCodeAdapter] ObservabilityRail attached")- except Exception as e:- logger.warning("[JiuwenSwarmCodeAdapter] Failed to attach ObservabilityRail: %s", e)- return rails_list+ return self._instantiate_rails(rail_infos, config_base)# ─── Code 专属 Rail 构建 ────────────────diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 6ac377c720..cf0aad1f89 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -446,6 +446,31 @@ _SKILL_RETRIEVAL_TOOL_NAMES = frozenset(# at this scale is directly visible in time-to-first-token._SLOW_RUNTIME_CONFIG_MS = 50.0+# Total rail-construction cost above which the per-rail breakdown is worth an+# INFO line. Rails are built once per agent, so the bar sits higher than the+# per-turn one: this is cold-start budget, not time-to-first-token.+_SLOW_RAIL_BUILD_MS = 100.0+++@dataclass+class _RailBuildInfo:+ """One rail's construction recipe, shared by the agent and code rail sets.++ Attributes:+ attr_name: Adapter attribute the built rail is assigned to. Also names+ the rail in the build-timing breakdown, minus its leading underscore.+ build_func: Callable returning the rail instance, or None to skip it.+ params: Keyword arguments for ``build_func``; empty when omitted.+ """++ attr_name: str+ build_func: Callable+ params: dict = None++ def __post_init__(self):+ """Normalize the optional params mapping to an empty dict."""+ self.params = self.params or {}+_CRON_TOOL_NAMES = frozenset({"cron",@@ -4281,20 +4306,85 @@ class JiuWenSwarmDeepAdapter:)return None- def _build_agent_rails(- self, config: dict[str, Any], config_base: dict[str, Any], *, mode: str = "agent"+ def _instantiate_rails(+ self,+ rail_infos: list["_RailBuildInfo"],+ config_base: dict[str, Any],) -> list[Any]:- """Build DeepAgent rails consistently for cold start and hot reload."""+ """Build each declared rail in order, then attach the two standing ones.++ Shared by the agent and code rail sets, which differ only in what they+ declare. Rail construction is the bulk of ``create_instance``, so each+ one is timed separately and the breakdown is logged slowest-first once+ the total crosses :data:`_SLOW_RAIL_BUILD_MS` — an aggregate over a+ dozen-plus rails says nothing about which to look at.++ Args:+ rail_infos: Rails to build, in the order they should be attached.+ config_base: Full config snapshot, used for the user hook rail.++ Returns:+ The successfully built rails. A rail whose builder returns None is+ skipped with a warning rather than failing the whole set.+ """+ log_prefix = f"[{type(self).__name__}]"+ stage_timer = StageTimer()+ rails_list = []+ for info in rail_infos:+ rail_instance = info.build_func(**info.params)+ stage_timer.mark(info.attr_name.lstrip("_"))+ if rail_instance is not None:+ setattr(self, info.attr_name, rail_instance)+ rails_list.append(rail_instance)+ else:+ logger.warning("%s Rail %s build returned None", log_prefix, info.attr_name)++ # 用户配置的 hooks(UserHookRail)+ try:+ hooks_config = load_hooks_config(config_base)+ if hooks_config.events:+ rails_list.append(UserHookRail(hooks_config))+ logger.info(+ "%s UserHookRail loaded with %d event types",+ log_prefix,+ len(hooks_config.events),+ )+ except Exception as exc:+ logger.warning("%s Failed to load UserHookRail: %s", log_prefix, exc)+ stage_timer.mark("user_hook_rail")- @dataclass- class _RailBuildInfo:- attr_name: str- build_func: callable- params: dict = None+ # Observability rail: opens an agent-layer span (agent.<name>.task_iteration.<n>+ # for task-loop runs, or agent.<name>.invoke for single-round) under the root+ # run span per iteration/round. It is the only thing that creates the+ # task_iteration / invoke spans that llm.call + tool.* nest under. It+ # self-disables (before_* returns early when get_team_span() is None), so+ # attaching it unconditionally is safe and also adapts to runtime+ # enable/disable of agent_observability without rebuilding the agent.+ try:+ from openjiuwen.agent_teams.observability.rail import ObservabilityRail++ rails_list.append(ObservabilityRail())+ except Exception as exc:+ logger.warning("%s Failed to attach ObservabilityRail: %s", log_prefix, exc)+ stage_timer.mark("observability_rail")- def __post_init__(self):- self.params = self.params or {}+ total_ms = stage_timer.total_ms()+ log_rail_build = (+ server_logger.info if total_ms >= _SLOW_RAIL_BUILD_MS else logger.debug+ )+ log_rail_build(+ "[AgentServer] agent rails built: adapter=%s count=%d total_ms=%.1f %s",+ type(self).__name__,+ len(rails_list),+ total_ms,+ stage_timer.render(slowest_first=True),+ )+ return rails_list+ def _build_agent_rails(+ self, config: dict[str, Any], config_base: dict[str, Any], *, mode: str = "agent"+ ) -> list[Any]:+ """Build DeepAgent rails consistently for cold start and hot reload."""rail_infos = [_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),_RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),@@ -4367,56 +4457,7 @@ class JiuWenSwarmDeepAdapter:if isinstance(mode, str) and mode.startswith("agent"):rail_infos.append(_RailBuildInfo("_ask_user_rail", self._build_structured_ask_user_rail))- rails_list = []- for info in rail_infos:- logger.info(- "[JiuWenSwarmDeepAdapter] Building rail: %s with params: %s",- info.attr_name,- sorted(info.params),- )- rail_instance = info.build_func(**info.params)- if rail_instance is not None:- setattr(self, info.attr_name, rail_instance)- rails_list.append(rail_instance)- logger.info(- "[JiuWenSwarmDeepAdapter] Rail %s built successfully and added to rails_list",- info.attr_name,- )- else:- logger.warning(- "[JiuWenSwarmDeepAdapter] Rail %s build returned None", info.attr_name- )- logger.info(- "[JiuWenSwarmDeepAdapter] Total rails built: %d, rail names: %s",- len(rails_list),- [type(r).__name__ for r in rails_list],- )- # 用户配置的 hooks(UserHookRail)- try:- hooks_config = load_hooks_config(config_base)- if hooks_config.events:- user_hook_rail = UserHookRail(hooks_config)- rails_list.append(user_hook_rail)- logger.info(- "[JiuWenSwarmDeepAdapter] UserHookRail loaded with %d event types",- len(hooks_config.events),- )- except Exception as e:- logger.warning("[JiuWenSwarmDeepAdapter] Failed to load UserHookRail: %s", e)- # Observability rail: opens an agent-layer span (agent.<name>.task_iteration.<n>- # for task-loop runs, or agent.<name>.invoke for single-round) under the root- # run span per iteration/round. It is the only thing that creates the- # task_iteration / invoke spans that llm.call + tool.* nest under. It- # self-disables (before_* returns early when get_team_span() is None), so- # attaching it unconditionally is safe and also adapts to runtime- # enable/disable of agent_observability without rebuilding the agent.- try:- from openjiuwen.agent_teams.observability.rail import ObservabilityRail- rails_list.append(ObservabilityRail())- logger.info("[JiuWenSwarmDeepAdapter] ObservabilityRail attached")- except Exception as e:- logger.warning("[JiuWenSwarmDeepAdapter] Failed to attach ObservabilityRail: %s", e)- return rails_list+ return self._instantiate_rails(rail_infos, config_base)@staticmethoddef _resolve_enable_task_loop(diff --git a/tests/unit_tests/agentserver/test_deep_adapter_rail_build_timing.py b/tests/unit_tests/agentserver/test_deep_adapter_rail_build_timing.pynew file mode 100644index 0000000000..66c494d8b7--- /dev/null+++ b/tests/unit_tests/agentserver/test_deep_adapter_rail_build_timing.py@@ -0,0 +1,183 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for the shared rail construction loop and its per-rail timing."""++from __future__ import annotations++import sys+import types++import pytest++from jiuwenswarm.server.runtime.agent_adapter import interface_deep+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+ _RailBuildInfo,+)+++class _RecordingLogger:+ """Logger double capturing the args of each call."""++ def __init__(self) -> None:+ self.records: list[tuple[str, tuple]] = []++ def info(self, msg: str, *args) -> None:+ self.records.append((msg, args))++ def debug(self, msg: str, *args, **kwargs) -> None:+ self.records.append((msg, args))++ def warning(self, msg: str, *args, **kwargs) -> None:+ self.records.append((msg, args))++[email protected](name="loggers")+def _loggers(monkeypatch: pytest.MonkeyPatch) -> tuple[_RecordingLogger, _RecordingLogger]:+ server_log = _RecordingLogger()+ module_log = _RecordingLogger()+ monkeypatch.setattr(interface_deep, "server_logger", server_log)+ monkeypatch.setattr(interface_deep, "logger", module_log)+ monkeypatch.setattr(interface_deep, "load_hooks_config", lambda config_base: _NoHooks())+ return server_log, module_log+++class _NoHooks:+ events: dict = {}+++_OBSERVABILITY_RAIL_MODULE = "openjiuwen.agent_teams.observability.rail"++[email protected](autouse=True)+def _stub_observability_rail(monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep the standing observability rail out of these tests entirely.++ ``_instantiate_rails`` attaches it unconditionally, and both constructing it+ and merely importing its module start an OTLP exporter that leaves an+ unclosed socket behind — which pytest later surfaces as an unraisable+ exception during some unrelated test's setup. Injecting a stand-in module+ means the function-level import resolves without the real one ever loading.+ """+ stub_module = types.ModuleType(_OBSERVABILITY_RAIL_MODULE)+ stub_module.ObservabilityRail = lambda: object()+ monkeypatch.setitem(sys.modules, _OBSERVABILITY_RAIL_MODULE, stub_module)+++def _make_adapter() -> JiuWenSwarmDeepAdapter:+ return object.__new__(JiuWenSwarmDeepAdapter)+++def _breakdown_of(records: list[tuple[str, tuple]]) -> str:+ """Return the breakdown string of the single rail-build summary line."""+ summary = [rec for rec in records if "agent rails built" in rec[0]]+ assert len(summary) == 1+ return summary[0][1][-1]+++def test_built_rails_are_assigned_and_returned(loggers) -> None:+ """Each builder's result lands on its attribute and in the returned list."""+ adapter = _make_adapter()+ first, second = object(), object()+ rail_infos = [+ _RailBuildInfo("_alpha_rail", lambda: first),+ _RailBuildInfo("_beta_rail", lambda: second),+ ]++ rails = adapter._instantiate_rails(rail_infos, {})++ assert adapter._alpha_rail is first+ assert adapter._beta_rail is second+ # The two standing rails may or may not import in this environment, so only+ # the declared ones are asserted on by identity.+ assert rails[:2] == [first, second]+++def test_builder_params_are_forwarded(loggers) -> None:+ """Declared params reach the builder unchanged."""+ adapter = _make_adapter()+ seen: dict = {}++ def _build(**kwargs):+ seen.update(kwargs)+ return object()++ adapter._instantiate_rails([_RailBuildInfo("_x_rail", _build, {"config": {"k": 1}})], {})++ assert seen == {"config": {"k": 1}}+++def test_none_result_is_skipped_without_failing_the_set(loggers) -> None:+ """One rail declining to build must not take the rest down with it."""+ server_log, module_log = loggers+ adapter = _make_adapter()+ survivor = object()+ rail_infos = [+ _RailBuildInfo("_absent_rail", lambda: None),+ _RailBuildInfo("_present_rail", lambda: survivor),+ ]++ rails = adapter._instantiate_rails(rail_infos, {})++ assert survivor in rails+ assert not hasattr(adapter, "_absent_rail")+ assert any("build returned None" in rec[0] for rec in module_log.records)+++def test_every_rail_appears_in_the_breakdown(loggers, monkeypatch: pytest.MonkeyPatch) -> None:+ """The breakdown must name each rail, so a slow one is identifiable."""+ server_log, module_log = loggers+ monkeypatch.setattr(interface_deep, "_SLOW_RAIL_BUILD_MS", 0.0)+ adapter = _make_adapter()+ rail_infos = [+ _RailBuildInfo("_alpha_rail", lambda: object()),+ _RailBuildInfo("_beta_rail", lambda: object()),+ ]++ adapter._instantiate_rails(rail_infos, {})++ breakdown = _breakdown_of(server_log.records)+ # Attribute underscore is stripped so the breakdown reads as rail names.+ assert "alpha_rail=" in breakdown+ assert "beta_rail=" in breakdown+ assert "user_hook_rail=" in breakdown+ assert "observability_rail=" in breakdown+++def test_breakdown_is_ordered_slowest_first(loggers, monkeypatch: pytest.MonkeyPatch) -> None:+ """The point of the line is the offender, so it leads."""+ server_log, module_log = loggers+ monkeypatch.setattr(interface_deep, "_SLOW_RAIL_BUILD_MS", 0.0)+ clock = {"t": 0.0}+ monkeypatch.setattr("jiuwenswarm.common.stage_timer.monotonic", lambda: clock["t"])+ adapter = _make_adapter()++ def _fast():+ clock["t"] += 0.001+ return object()++ def _slow():+ clock["t"] += 0.500+ return object()++ rail_infos = [+ _RailBuildInfo("_fast_rail", _fast),+ _RailBuildInfo("_slow_rail", _slow),+ ]++ adapter._instantiate_rails(rail_infos, {})++ breakdown = _breakdown_of(server_log.records)+ assert breakdown.startswith("slow_rail=500.0")+++def test_fast_build_stays_at_debug(loggers, monkeypatch: pytest.MonkeyPatch) -> None:+ """A cheap rail set must not add an INFO line to the agent log stream."""+ server_log, module_log = loggers+ monkeypatch.setattr(interface_deep, "_SLOW_RAIL_BUILD_MS", 10_000.0)+ adapter = _make_adapter()++ adapter._instantiate_rails([_RailBuildInfo("_x_rail", lambda: object())], {})++ assert not any("agent rails built" in rec[0] for rec in server_log.records)+ assert any("agent rails built" in rec[0] for rec in module_log.records)