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: add request summary perf package and process exit diagnostics
xiaowenzihwl189baa24e5f3
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.pyindex 857f51984b..30bc187a44 100644--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py@@ -834,14 +834,16 @@ class JiuSwarmStreamEventRail(DeepAgentRail):tool_name = ctx.inputs.tool_namesid = self._resolve_sid(ctx, session)conv_id = self._conversation_ids.get(sid, "")- if not conv_id:- returnif tool_name in _TODO_TOOL_NAMES:- # Emit the main-agent todo snapshot after every todo tool call. The- # todo tool itself is loaded from the main workspace below, so this- # stays authoritative even when a resumed/supplement turn uses a- # different stream session object.- await self._emit_todo_updated(session, conv_id)+ # Prefer conversation_id (main session key for todo.json). Fall back+ # to resolved sid so perf/todo.updated still fire if mapping is late.+ todo_sid = conv_id or sid+ if todo_sid:+ # Emit the main-agent todo snapshot after every todo tool call.+ # The todo tool itself is loaded from the main workspace below, so+ # this stays authoritative even when a resumed/supplement turn uses+ # a different stream session object.+ await self._emit_todo_updated(session, todo_sid)# ------------------------------------------------------------------# on_model_exception: attempt context repair@@ -988,6 +990,24 @@ class JiuSwarmStreamEventRail(DeepAgentRail):)return+ # Parent StreamEventRail only: team-member rails use their own+ # workspace and must not feed request_summaries.tasks.+ if not self._member_name:+ from jiuwenswarm.perf.guard import run_perf_safe+ from jiuwenswarm.perf.todo_tracker import (+ sync_main_agent_todos,+ todos_from_items,+ )++ run_perf_safe(+ "StreamEventRail",+ "perf sync main-agent todos",+ lambda: sync_main_agent_todos(+ todos_from_items(todos_data),+ session_id=session_id,+ ),+ )+todos = self._format_todos_for_frontend(todos_data)try:diff --git a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.pyindex f668f81f39..3ad8e6b49a 100644--- a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py@@ -576,7 +576,7 @@ class TaskExecutionRail(DeepAgentRail):parent_request_id: str = "",) -> None:full_task_id = f"todo:{task_id}"- context = self._active_tasks.get(full_task_id)+ context = self._active_tasks.pop(full_task_id, None)timestamp = time.time()if context:@@ -586,7 +586,6 @@ class TaskExecutionRail(DeepAgentRail):payload_task_id = context.task_idtask_content = context.task_contentsource = context.source- self._active_tasks.pop(full_task_id, None)else:duration_ms = 0payload_task_id = full_task_id@@ -824,5 +823,36 @@ class TaskExecutionRail(DeepAgentRail):@staticmethoddef _extract_request_id(ctx: AgentCallbackContext) -> str:- value = getattr(ctx.inputs, "request_id", "")- return str(value) if value else ""+ value = getattr(ctx.inputs, "request_id", None)+ if value:+ return str(value).strip()+ if isinstance(ctx.inputs, dict):+ raw = ctx.inputs.get("request_id")+ if raw:+ return str(raw).strip()+ # ToolCallInputs usually has no request_id; fall back to the active+ # perf request context so task.* UI payloads still carry+ # parent_request_id when the rail is enabled.+ try:+ from jiuwenswarm.perf.context import (+ extract_session_id_from_callback,+ get_request_context,+ )++ session_id = None+ if ctx.session is not None:+ try:+ session_id = str(ctx.session.get_session_id() or "").strip() or None+ except Exception:+ session_id = extract_session_id_from_callback(ctx)+ else:+ session_id = extract_session_id_from_callback(ctx)+ req_ctx = get_request_context(session_id=session_id)+ if req_ctx:+ return str(req_ctx.get("request_id") or "").strip()+ except Exception:+ logger.debug(+ "[TaskExecutionRail] request_id fallback failed",+ exc_info=True,+ )+ return ""diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex 382c4f8aad..e317c823ef 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -1478,6 +1478,11 @@ async def _run(from openjiuwen.core.runner import Runnerlogger.info("[App] Gateway starting, connecting AgentServer: %s", agent_server_url)++ from jiuwenswarm.perf.config import init_perf_summary_config++ init_perf_summary_config()+restart_request = GatewayRestartRequest()callback_framework = Runner.callback_frameworkdiff --git a/jiuwenswarm/perf/__init__.py b/jiuwenswarm/perf/__init__.pynew file mode 100644index 0000000000..95f2258b8e--- /dev/null+++ b/jiuwenswarm/perf/__init__.py@@ -0,0 +1,22 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Request performance summary collection and persistence."""++from jiuwenswarm.perf.config import get_perf_summary_config, init_perf_summary_config++__all__ = [+ "get_perf_summary_config",+ "init_perf_summary_config",+]+++def get_perf_collector():+ from jiuwenswarm.perf.collector import get_perf_collector as _get++ return _get()+++def mark_first_byte_latency() -> None:+ from jiuwenswarm.perf.context import mark_first_byte_latency as _mark++ _mark()diff --git a/jiuwenswarm/perf/accumulator.py b/jiuwenswarm/perf/accumulator.pynew file mode 100644index 0000000000..ced21a636d--- /dev/null+++ b/jiuwenswarm/perf/accumulator.py@@ -0,0 +1,339 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import time+from dataclasses import dataclass, field+from typing import Any++from jiuwenswarm.perf.events import LlmPerfEvent, TaskPerfEvent, ToolPerfEvent+from jiuwenswarm.perf.stats import (+ LlmStatsAccumulator,+ ToolStatsAccumulator,+ maintain_top_n,+ ms_to_s,+)+++@dataclass+class RequestMeta:+ session_id: str+ request_id: str+ channel_id: str+ mode: str+ trace_id: str | None+ started_at: float+ service_id: str = "default"+ agent_id: str = "default"++ def with_trace_id(self, trace_id: str | None) -> RequestMeta:+ if trace_id:+ return RequestMeta(+ session_id=self.session_id,+ request_id=self.request_id,+ channel_id=self.channel_id,+ mode=self.mode,+ trace_id=trace_id,+ started_at=self.started_at,+ service_id=self.service_id,+ agent_id=self.agent_id,+ )+ return self+++@dataclass+class RequestSummaryAccumulator:+ meta: RequestMeta+ status: str = "ok"+ first_byte_latency_ms: int | None = None+ first_answer_latency_ms: int | None = None+ ended_at: float | None = None+ llm_stats: LlmStatsAccumulator = field(default_factory=LlmStatsAccumulator)+ tool_stats: ToolStatsAccumulator = field(default_factory=ToolStatsAccumulator)+ task_count: int = 0+ task_total_ms: float = 0.0+ task_fail_count: int = 0+ unattributed_ms: float = 0.0+ input_tokens: int = 0+ output_tokens: int = 0+ cache_read_tokens: int = 0+ tasks: list[dict[str, Any]] = field(default_factory=list)+ bottleneck_llm: list[dict[str, Any]] = field(default_factory=list)+ bottleneck_tool: list[dict[str, Any]] = field(default_factory=list)+ bottleneck_task: list[dict[str, Any]] = field(default_factory=list)+ errors: list[dict[str, Any]] = field(default_factory=list)+ flushed: bool = False+ _bottleneck_top_n: int = 3+ _include_errors: bool = False+ _include_by_agent: bool = False+ _recorded_task_ids: set[str] = field(default_factory=set)+ _task_stats: dict[str, tuple[LlmStatsAccumulator, ToolStatsAccumulator]] = field(+ default_factory=dict+ )+ _agent_llm: dict[str, LlmStatsAccumulator] = field(default_factory=dict)+ _agent_tool: dict[str, ToolStatsAccumulator] = field(default_factory=dict)+ _agent_tokens: dict[str, dict[str, int]] = field(default_factory=dict)++ def _task_stat_pair(self, task_id: str) -> tuple[LlmStatsAccumulator, ToolStatsAccumulator]:+ pair = self._task_stats.get(task_id)+ if pair is None:+ pair = (LlmStatsAccumulator(), ToolStatsAccumulator())+ self._task_stats[task_id] = pair+ return pair++ @staticmethod+ def _agent_key(agent_id: str | None) -> str:+ return (agent_id or "").strip() or "unknown"++ def _agent_token_bucket(self, agent_id: str | None) -> dict[str, int]:+ key = self._agent_key(agent_id)+ bucket = self._agent_tokens.get(key)+ if bucket is None:+ bucket = {"input": 0, "output": 0}+ self._agent_tokens[key] = bucket+ return bucket++ def _append_error(self, entry: dict[str, Any]) -> None:+ if not self._include_errors:+ return+ self.errors.append(entry)++ def set_first_byte_latency_ms(self, latency_ms: float) -> None:+ """First history-visible assistant event (tool_call / reasoning / answer)."""+ if self.first_byte_latency_ms is None and latency_ms >= 0:+ self.first_byte_latency_ms = int(round(latency_ms))++ def set_first_answer_latency_ms(self, latency_ms: float) -> None:+ """First answer token (chat.delta / chat.final), excluding tool/reasoning."""+ if self.first_answer_latency_ms is None and latency_ms >= 0:+ self.first_answer_latency_ms = int(round(latency_ms))++ def record_llm(self, event: LlmPerfEvent) -> None:+ self.llm_stats.record(+ duration_ms=event.duration_ms,+ status=event.status,+ )+ self.input_tokens += max(0, event.input_tokens)+ self.output_tokens += max(0, event.output_tokens)+ if self._include_by_agent:+ agent_key = self._agent_key(event.agent_id)+ self._agent_llm.setdefault(agent_key, LlmStatsAccumulator()).record(+ duration_ms=event.duration_ms,+ status=event.status,+ )+ token_bucket = self._agent_token_bucket(agent_key)+ token_bucket["input"] += max(0, event.input_tokens)+ token_bucket["output"] += max(0, event.output_tokens)+ if event.task_id:+ llm_acc, _ = self._task_stat_pair(event.task_id)+ llm_acc.record(+ duration_ms=event.duration_ms,+ status=event.status,+ )+ else:+ self.unattributed_ms += event.duration_ms++ entry: dict[str, Any] = {+ "duration_s": ms_to_s(event.duration_ms),+ "agent_id": event.agent_id,+ "task_id": event.task_id,+ "model": event.model,+ "iteration": event.iteration,+ "input_tokens": event.input_tokens,+ "output_tokens": event.output_tokens,+ }+ if event.stream_source_id:+ entry["stream_source_id"] = event.stream_source_id+ if event.status != "ok":+ error_entry: dict[str, Any] = {+ "kind": "llm",+ "status": "error",+ "name": event.model or "unknown",+ "error": event.error_message or "unknown error",+ "task_id": event.task_id,+ "agent_id": event.agent_id,+ "iteration": event.iteration,+ "duration_s": ms_to_s(event.duration_ms),+ }+ self._append_error(error_entry)+ self.bottleneck_llm = maintain_top_n(+ self.bottleneck_llm,+ entry,+ top_n=self._bottleneck_top_n,+ )++ def record_tool(self, event: ToolPerfEvent) -> None:+ self.tool_stats.record(+ duration_ms=event.duration_ms,+ status=event.status,+ name=event.name,+ iteration=event.iteration,+ )+ if self._include_by_agent:+ agent_key = self._agent_key(event.agent_id)+ self._agent_tool.setdefault(agent_key, ToolStatsAccumulator()).record(+ duration_ms=event.duration_ms,+ status=event.status,+ name=event.name,+ iteration=event.iteration,+ )+ if event.task_id:+ _, tool_acc = self._task_stat_pair(event.task_id)+ tool_acc.record(+ duration_ms=event.duration_ms,+ status=event.status,+ name=event.name,+ iteration=event.iteration,+ )+ else:+ self.unattributed_ms += event.duration_ms+ if event.status != "ok":+ error_entry: dict[str, Any] = {+ "kind": "tool",+ "status": "error",+ "name": event.name or "unknown",+ "call_id": event.tool_call_id,+ "error": event.error_message or "unknown error",+ "task_id": event.task_id,+ "agent_id": event.agent_id,+ "iteration": event.iteration,+ "duration_s": ms_to_s(event.duration_ms),+ }+ self._append_error(error_entry)+ entry = {+ "duration_s": ms_to_s(event.duration_ms),+ "name": event.name,+ "tool_call_id": event.tool_call_id,+ "agent_id": event.agent_id,+ "task_id": event.task_id,+ "iteration": event.iteration,+ }+ self.bottleneck_tool = maintain_top_n(+ self.bottleneck_tool,+ entry,+ top_n=self._bottleneck_top_n,+ )++ def record_task(self, event: TaskPerfEvent) -> None:+ # Dedupe by task_id within one request (safe if callers retry).+ if event.task_id in self._recorded_task_ids:+ return+ self._recorded_task_ids.add(event.task_id)++ self.task_count += 1+ self.task_total_ms += event.duration_ms+ if event.status not in ("completed", "succeeded", "ok"):+ self.task_fail_count += 1++ task_stats = self._task_stats.pop(event.task_id, None)+ if task_stats is None:+ llm_stats = LlmStatsAccumulator()+ tool_stats = ToolStatsAccumulator()+ else:+ llm_stats, tool_stats = task_stats++ task_entry = {+ "order": len(self.tasks) + 1,+ "task_id": event.task_id,+ "task_content": event.task_content,+ "source": event.source,+ "started_at": event.started_at,+ "ended_at": event.ended_at,+ "duration_s": ms_to_s(event.duration_ms),+ "status": event.status,+ "stats": {+ "llm": llm_stats.to_dict(),+ "tool": tool_stats.to_dict(),+ },+ }+ self.tasks.append(task_entry)+ task_rank_entry = {+ "duration_s": ms_to_s(event.duration_ms),+ "task_id": event.task_id,+ "task_content": event.task_content,+ }+ self.bottleneck_task = maintain_top_n(+ self.bottleneck_task,+ task_rank_entry,+ top_n=self._bottleneck_top_n,+ )++ def _by_agent_dict(self) -> dict[str, Any]:+ agent_ids = sorted(+ set(self._agent_llm) | set(self._agent_tool) | set(self._agent_tokens)+ )+ out: dict[str, Any] = {}+ for agent_id in agent_ids:+ llm = self._agent_llm.get(agent_id) or LlmStatsAccumulator()+ tool = self._agent_tool.get(agent_id) or ToolStatsAccumulator()+ tokens = self._agent_tokens.get(agent_id) or {"input": 0, "output": 0}+ out[agent_id] = {+ "llm": llm.to_dict(),+ "tool": tool.to_dict(),+ "tokens": {+ "input": int(tokens.get("input") or 0),+ "output": int(tokens.get("output") or 0),+ },+ }+ return out++ def finalize(self, *, status: str | None = None, ended_at: float | None = None) -> dict[str, Any]:+ if status is not None:+ self.status = status+ self.ended_at = ended_at if ended_at is not None else time.time()+ total_s = ms_to_s(max(0.0, (self.ended_at - self.meta.started_at) * 1000))+ # Nested parent/subagent durations can sum above wall clock; clamp.+ unattributed_s = min(ms_to_s(self.unattributed_ms), total_s)+ if self.first_byte_latency_ms is None:+ first_byte_latency_s = 0.0+ else:+ first_byte_latency_s = ms_to_s(float(self.first_byte_latency_ms))+ if self.first_answer_latency_ms is None:+ first_answer_latency_s = 0.0+ else:+ first_answer_latency_s = ms_to_s(float(self.first_answer_latency_ms))++ summary: dict[str, Any] = {+ "schema_version": 1,+ "meta": {+ "session_id": self.meta.session_id,+ "request_id": self.meta.request_id,+ "channel_id": self.meta.channel_id,+ "mode": self.meta.mode,+ "trace_id": self.meta.trace_id,+ "started_at": self.meta.started_at,+ "ended_at": self.ended_at,+ },+ "summary": {+ "total_s": total_s,+ "first_byte_latency_s": first_byte_latency_s,+ "first_answer_latency_s": first_answer_latency_s,+ "status": self.status,+ "stats": {+ "llm": self.llm_stats.to_dict(),+ "tool": self.tool_stats.to_dict(),+ "task": {+ "count": self.task_count,+ "total_s": ms_to_s(self.task_total_ms),+ "fail_count": self.task_fail_count,+ },+ "unattributed_s": unattributed_s,+ },+ "tokens": {+ "input": self.input_tokens,+ "output": self.output_tokens,+ "cache_read": self.cache_read_tokens,+ },+ },+ "tasks": self.tasks,+ "bottleneck": {+ "task": self.bottleneck_task,+ "llm": self.bottleneck_llm,+ "tool": self.bottleneck_tool,+ },+ }+ if self._include_by_agent:+ summary["summary"]["stats"]["by_agent"] = self._by_agent_dict()+ if self._include_errors:+ summary["errors"] = self.errors+ return summarydiff --git a/jiuwenswarm/perf/collector.py b/jiuwenswarm/perf/collector.pynew file mode 100644index 0000000000..c9d0857707--- /dev/null+++ b/jiuwenswarm/perf/collector.py@@ -0,0 +1,228 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import logging+import threading+import time+from typing import Any++from jiuwenswarm.perf.accumulator import RequestMeta, RequestSummaryAccumulator+from jiuwenswarm.perf.config import get_perf_summary_config+from jiuwenswarm.perf.events import LlmPerfEvent, TaskPerfEvent, ToolPerfEvent+from jiuwenswarm.perf.writer import append_request_summary+from jiuwenswarm.perf.guard import run_perf_safe+++def _normalize_tenant_scope_id(value: str | None, *, default: str = "default") -> str:+ if value is None:+ return default+ stripped = str(value).strip()+ return stripped or default+++logger = logging.getLogger(__name__)+++class PerfCollector:+ """In-memory request summary aggregator with process-wide routing."""++ _MAX_WRITTEN_IDS = 4096+ _STALE_ORPHAN_AGE_S = 7200.0++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._accumulators: dict[str, RequestSummaryAccumulator] = {}+ self._active_request_ids: set[str] = set()+ self._written_request_ids: set[str] = set()+ self._inflight_finalize_ids: set[str] = set()++ def begin_request(+ self,+ *,+ session_id: str,+ request_id: str,+ channel_id: str,+ mode: str,+ trace_id: str | None = None,+ started_at: float | None = None,+ service_id: str | None = None,+ agent_id: str | None = None,+ ) -> RequestSummaryAccumulator | None:+ cfg = get_perf_summary_config()+ if not cfg.enabled:+ return None+ rid = (request_id or "").strip()+ if not rid:+ return None++ from jiuwenswarm.perf.todo_tracker import clear_todo_tracker++ meta = RequestMeta(+ session_id=(session_id or "default").strip() or "default",+ request_id=rid,+ channel_id=(channel_id or "").strip(),+ mode=(mode or "agent.plan").strip() or "agent.plan",+ trace_id=trace_id,+ started_at=started_at if started_at is not None else time.time(),+ service_id=_normalize_tenant_scope_id(service_id),+ agent_id=_normalize_tenant_scope_id(agent_id),+ )+ acc = RequestSummaryAccumulator(+ meta=meta,+ _bottleneck_top_n=cfg.bottleneck_top_n,+ _include_errors=cfg.include_errors,+ _include_by_agent=cfg.include_by_agent,+ )+ with self._lock:+ self._prune_stale_accumulators_locked()+ self._active_request_ids.add(rid)+ existing = self._accumulators.get(rid)+ if existing is not None:+ return existing+ self._accumulators[rid] = acc+ # Fresh request must not inherit leftover todo tracking for a reused id.+ clear_todo_tracker(rid)+ return acc++ def get_accumulator(self, request_id: str) -> RequestSummaryAccumulator | None:+ rid = (request_id or "").strip()+ if not rid:+ return None+ with self._lock:+ return self._accumulators.get(rid)++ def record_llm(self, request_id: str, event: LlmPerfEvent) -> None:+ acc = self.get_accumulator(request_id)+ if acc is None:+ return+ acc.record_llm(event)++ def record_tool(self, request_id: str, event: ToolPerfEvent) -> None:+ acc = self.get_accumulator(request_id)+ if acc is None:+ return+ acc.record_tool(event)++ def record_task(self, request_id: str, event: TaskPerfEvent) -> None:+ cfg = get_perf_summary_config()+ if not cfg.include_tasks:+ return+ acc = self.get_accumulator(request_id)+ if acc is None:+ return+ acc.record_task(event)++ def mark_first_byte_latency(self, request_id: str, latency_ms: float) -> None:+ acc = self.get_accumulator(request_id)+ if acc is None:+ return+ acc.set_first_byte_latency_ms(latency_ms)++ def mark_first_answer_latency(self, request_id: str, latency_ms: float) -> None:+ acc = self.get_accumulator(request_id)+ if acc is None:+ return+ acc.set_first_answer_latency_ms(latency_ms)++ def finalize_request(+ self,+ request_id: str,+ *,+ status: str = "ok",+ ended_at: float | None = None,+ ) -> None:+ cfg = get_perf_summary_config()+ if not cfg.enabled:+ return++ rid = (request_id or "").strip()+ if not rid:+ return++ from jiuwenswarm.perf.todo_tracker import clear_todo_tracker++ try:+ with self._lock:+ # Skip duplicate / concurrent finalize for the same request_id.+ if rid in self._written_request_ids or rid in self._inflight_finalize_ids:+ self._active_request_ids.discard(rid)+ return+ acc = self._accumulators.pop(rid, None)+ self._active_request_ids.discard(rid)+ if acc is not None and not acc.flushed:+ self._inflight_finalize_ids.add(rid)++ if acc is None or acc.flushed:+ if acc is None:+ logger.warning(+ "finalize_request: accumulator missing for request_id=%s",+ rid,+ )+ return++ try:+ from jiuwenswarm.perf.context import get_request_wall_start++ wall_start = get_request_wall_start()+ if acc.first_byte_latency_ms is None and wall_start is not None:+ acc.set_first_byte_latency_ms(+ max(0.0, (time.time() - wall_start) * 1000)+ )++ summary = acc.finalize(status=status, ended_at=ended_at)++ def _write_summary() -> None:+ append_request_summary(+ acc.meta.session_id,+ summary,+ service_id=acc.meta.service_id,+ agent_id=acc.meta.agent_id,+ )+ acc.flushed = True+ with self._lock:+ self._written_request_ids.add(rid)+ self._trim_written_request_ids_locked()++ run_perf_safe("PerfCollector", "request summary write", _write_summary)+ if not acc.flushed:+ with self._lock:+ if rid not in self._written_request_ids:+ self._accumulators.setdefault(rid, acc)+ finally:+ with self._lock:+ self._inflight_finalize_ids.discard(rid)+ finally:+ # Always drop todo tracking for this request (success, miss, or retry).+ clear_todo_tracker(rid)++ def _prune_stale_accumulators_locked(self) -> None:+ now = time.time()+ stale: list[str] = []+ for rid, acc in self._accumulators.items():+ if rid in self._active_request_ids:+ continue+ if not acc.meta.started_at:+ continue+ if now - acc.meta.started_at <= self._STALE_ORPHAN_AGE_S:+ continue+ stale.append(rid)+ for rid in stale:+ self._accumulators.pop(rid, None)+ logger.warning(+ "pruned orphan accumulator request_id=%s",+ rid,+ )++ def _trim_written_request_ids_locked(self) -> None:+ overflow = len(self._written_request_ids) - self._MAX_WRITTEN_IDS+ while overflow > 0 and self._written_request_ids:+ self._written_request_ids.pop()+ overflow -= 1+++_COLLECTOR = PerfCollector()+++def get_perf_collector() -> PerfCollector:+ return _COLLECTORdiff --git a/jiuwenswarm/perf/config.py b/jiuwenswarm/perf/config.pynew file mode 100644index 0000000000..d6badb437d--- /dev/null+++ b/jiuwenswarm/perf/config.py@@ -0,0 +1,86 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Performance summary configuration — loaded once at process startup."""++from __future__ import annotations++import os+from dataclasses import dataclass+++@dataclass(frozen=True)+class PerfSummaryConfig:+ enabled: bool = True+ bottleneck_top_n: int = 3+ include_tasks: bool = True+ include_errors: bool = False+ include_by_agent: bool = False+++_CONFIG: PerfSummaryConfig | None = None+++def _bool_env(key: str, default: bool) -> bool:+ val = os.getenv(key)+ if val is None:+ return default+ return val.strip().lower() in ("true", "1", "yes")+++def _int_env(key: str, default: int) -> int:+ val = os.getenv(key)+ if val is None:+ return default+ try:+ parsed = int(val.strip())+ except ValueError:+ return default+ return parsed if parsed >= 0 else default+++def load_perf_summary_config() -> PerfSummaryConfig:+ """Load perf.summary config from env vars, falling back to config.yaml."""+ yaml_cfg: dict = {}+ try:+ from jiuwenswarm.common.config import get_config++ yaml_cfg = get_config().get("perf", {}) or {}+ except Exception:+ yaml_cfg = {}++ summary_cfg = yaml_cfg.get("summary", {}) if isinstance(yaml_cfg, dict) else {}+ if not isinstance(summary_cfg, dict):+ summary_cfg = {}++ # Default on when yaml/env omit the key; env PERF_SUMMARY_ENABLED wins when set.+ enabled_default = bool(summary_cfg.get("enabled", True))+ top_n_raw = summary_cfg.get("bottleneck_top_n")+ top_n_default = int(top_n_raw) if top_n_raw is not None else 3+ include_tasks_default = bool(summary_cfg.get("include_tasks", True))+ include_errors_default = bool(summary_cfg.get("include_errors", False))+ include_by_agent_default = bool(summary_cfg.get("include_by_agent", False))++ return PerfSummaryConfig(+ enabled=_bool_env("PERF_SUMMARY_ENABLED", enabled_default),+ bottleneck_top_n=_int_env("PERF_SUMMARY_TOP_N", top_n_default),+ include_tasks=_bool_env("PERF_SUMMARY_INCLUDE_TASKS", include_tasks_default),+ include_errors=_bool_env("PERF_SUMMARY_INCLUDE_ERRORS", include_errors_default),+ include_by_agent=_bool_env(+ "PERF_SUMMARY_INCLUDE_BY_AGENT", include_by_agent_default+ ),+ )+++def init_perf_summary_config() -> PerfSummaryConfig:+ """Initialize the startup config snapshot."""+ global _CONFIG+ _CONFIG = load_perf_summary_config()+ return _CONFIG+++def get_perf_summary_config() -> PerfSummaryConfig:+ """Return the startup snapshot, loading defaults if init was skipped."""+ global _CONFIG+ if _CONFIG is None:+ _CONFIG = load_perf_summary_config()+ return _CONFIGdiff --git a/jiuwenswarm/perf/context.py b/jiuwenswarm/perf/context.pynew file mode 100644index 0000000000..eeab8d8ab4--- /dev/null+++ b/jiuwenswarm/perf/context.py@@ -0,0 +1,311 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import logging+import threading+import time+from contextvars import ContextVar+from typing import Any++logger = logging.getLogger(__name__)++_request_context: ContextVar[dict[str, Any] | None] = ContextVar("perf_request_context", default=None)+_request_wall_start: ContextVar[float | None] = ContextVar("perf_request_wall_start", default=None)+_current_llm_call_id: ContextVar[str | None] = ContextVar("perf_current_llm_call_id", default=None)+_current_llm_call_start: ContextVar[float | None] = ContextVar("perf_current_llm_call_start", default=None)+_tool_starts: ContextVar[dict[str, tuple[str, float]] | None] = ContextVar(+ "perf_tool_starts",+ default=None,+)+_inherited_task_id: ContextVar[str | None] = ContextVar("perf_inherited_task_id", default=None)+_react_iteration: ContextVar[int] = ContextVar("perf_react_iteration", default=0)++# DeepAgent runs LLM/tool hooks on a long-lived supervisor/round Task that does+# NOT inherit the stream-handler ContextVar. Session registry bridges that gap.+_REGISTRY_LOCK = threading.Lock()+_SESSION_ACTIVE: dict[str, dict[str, Any]] = {}+++def normalize_session_key(session_id: str | None) -> str:+ """Map subagent session ids back to the parent session key."""+ sid = (session_id or "").strip() or "default"+ marker = "_sub_"+ if marker in sid:+ parent = sid.split(marker, 1)[0].strip()+ return parent or sid+ return sid+++def set_request_context(+ *,+ session_id: str,+ request_id: str,+ channel_id: str,+ mode: str,+ trace_id: str | None = None,+ service_id: str | None = None,+ agent_id: str | None = None,+) -> dict[str, Any]:+ started_at = time.time()+ ctx: dict[str, Any] = {+ "session_id": session_id,+ "request_id": request_id,+ "channel_id": channel_id,+ "mode": mode,+ "trace_id": trace_id,+ "started_at": started_at,+ "service_id": service_id,+ "agent_id": agent_id,+ }+ _request_context.set(ctx)+ _request_wall_start.set(started_at)+ with _REGISTRY_LOCK:+ _SESSION_ACTIVE[normalize_session_key(session_id)] = ctx+ from jiuwenswarm.perf.collector import get_perf_collector++ get_perf_collector().begin_request(+ session_id=session_id,+ request_id=request_id,+ channel_id=channel_id,+ mode=mode,+ trace_id=trace_id,+ started_at=started_at,+ service_id=service_id,+ agent_id=agent_id,+ )+ return ctx+++def clear_request_context(+ *,+ session_id: str | None = None,+ request_id: str | None = None,+) -> None:+ _request_context.set(None)+ _request_wall_start.set(None)+ _current_llm_call_id.set(None)+ _current_llm_call_start.set(None)+ _tool_starts.set(None)+ _inherited_task_id.set(None)+ _react_iteration.set(0)++ rid = (request_id or "").strip()+ with _REGISTRY_LOCK:+ if rid:+ for key, value in list(_SESSION_ACTIVE.items()):+ if str(value.get("request_id") or "").strip() == rid:+ _SESSION_ACTIVE.pop(key, None)+ elif session_id is not None:+ _SESSION_ACTIVE.pop(normalize_session_key(session_id), None)+++def reset_react_iteration() -> None:+ _react_iteration.set(0)+++def increment_react_iteration() -> int:+ iteration = int(_react_iteration.get() or 0) + 1+ _react_iteration.set(iteration)+ return iteration+++def get_react_iteration() -> int:+ return int(_react_iteration.get() or 0)+++def set_inherited_task_id(task_id: str | None) -> None:+ _inherited_task_id.set(task_id)+++def set_active_task_id(+ task_id: str | None,+ *,+ session_id: str | None = None,+ request_id: str | None = None,+) -> None:+ """Bind the current main-agent todo id onto the active request context.++ Stored on the shared request-context dict (ContextVar + session registry ++ rail binding all reference the same object when set at request entry), so+ interaction-round LLM/tool hooks can attribute without TaskExecutionRail.+ """+ tid = (task_id or "").strip() or None+ ctx = _request_context.get()+ if ctx is not None:+ ctx["active_task_id"] = tid++ rid = (request_id or "").strip()+ with _REGISTRY_LOCK:+ if rid:+ for value in _SESSION_ACTIVE.values():+ if str(value.get("request_id") or "").strip() == rid:+ value["active_task_id"] = tid+ return+ if session_id is not None:+ entry = _SESSION_ACTIVE.get(normalize_session_key(session_id))+ if entry is not None:+ entry["active_task_id"] = tid+++def resolve_task_id(+ *,+ request_ctx: dict[str, Any] | None = None,+ session_id: str | None = None,+) -> str | None:+ """Resolve task_id for llm/tool attribution.++ Order: TaskExecutionRail ContextVar (if enabled) → inherited ContextVar →+ active_task_id on the request context (main-agent todo binding).+ """+ try:+ from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (+ get_current_task_id,+ )++ task_id = get_current_task_id()+ except Exception:+ task_id = None+ if task_id:+ return str(task_id).strip() or None++ inherited = _inherited_task_id.get()+ if inherited:+ return str(inherited).strip() or None++ ctx = request_ctx if request_ctx is not None else get_request_context(session_id=session_id)+ if ctx is None:+ return None+ return str(ctx.get("active_task_id") or "").strip() or None+++def get_request_context(*, session_id: str | None = None) -> dict[str, Any] | None:+ """Return active request context (task-local ContextVar, else session registry)."""+ ctx = _request_context.get()+ if ctx is not None:+ return ctx+ if session_id is None:+ return None+ with _REGISTRY_LOCK:+ return _SESSION_ACTIVE.get(normalize_session_key(session_id))+++def extract_session_id_from_callback(ctx: Any) -> str | None:+ """Best-effort session id from AgentCallbackContext / agent inputs."""+ if ctx is None:+ return None+ session = getattr(ctx, "session", None)+ if session is not None:+ getter = getattr(session, "get_session_id", None)+ if callable(getter):+ try:+ sid = str(getter() or "").strip()+ if sid:+ return sid+ except Exception as exc:+ logger.debug(+ "[perf] session.get_session_id() failed, falling back: %s",+ exc,+ exc_info=True,+ )+ sid = str(getattr(session, "session_id", "") or "").strip()+ if sid:+ return sid++ inputs = getattr(ctx, "inputs", None)+ if inputs is not None:+ for attr in ("conversation_id", "session_id", "parent_session_id"):+ value = getattr(inputs, attr, None)+ if value is None and isinstance(inputs, dict):+ value = inputs.get(attr)+ sid = str(value or "").strip()+ if sid:+ return sid+ return None+++def get_request_wall_start(*, session_id: str | None = None) -> float | None:+ wall = _request_wall_start.get()+ if wall is not None:+ return wall+ ctx = get_request_context(session_id=session_id)+ if ctx is None:+ return None+ started = ctx.get("started_at")+ return float(started) if isinstance(started, (int, float)) else None+++def mark_first_byte_latency() -> None:+ wall_start = _request_wall_start.get()+ ctx = _request_context.get()+ if wall_start is None or ctx is None:+ return+ request_id = str(ctx.get("request_id") or "")+ latency_ms = max(0.0, (time.time() - wall_start) * 1000)+ from jiuwenswarm.perf.collector import get_perf_collector++ get_perf_collector().mark_first_byte_latency(request_id, latency_ms)+++def mark_first_answer_latency() -> None:+ wall_start = _request_wall_start.get()+ ctx = _request_context.get()+ if wall_start is None or ctx is None:+ return+ request_id = str(ctx.get("request_id") or "")+ latency_ms = max(0.0, (time.time() - wall_start) * 1000)+ from jiuwenswarm.perf.collector import get_perf_collector++ get_perf_collector().mark_first_answer_latency(request_id, latency_ms)+++def set_current_llm_call(call_id: str, start_monotonic: float) -> None:+ _current_llm_call_id.set(call_id)+ _current_llm_call_start.set(start_monotonic)+++def get_current_llm_call() -> tuple[str | None, float | None]:+ return _current_llm_call_id.get(), _current_llm_call_start.get()+++def clear_current_llm_call() -> None:+ _current_llm_call_id.set(None)+ _current_llm_call_start.set(None)+++def set_tool_start(tool_call_id: str, tool_name: str, start_monotonic: float) -> None:+ # Copy-on-write: asyncio.create_task copies ContextVar *values* by reference;+ # mutating a shared dict would race parent/child tool timings.+ key = (tool_call_id or "").strip() or f"__anon__{tool_name}_{start_monotonic}"+ starts = dict(_tool_starts.get() or {})+ starts[key] = (tool_name, start_monotonic)+ _tool_starts.set(starts)+++def pop_tool_start(tool_call_id: str, tool_name: str = "") -> tuple[str, float] | None:+ key = (tool_call_id or "").strip()+ starts = _tool_starts.get()+ if not starts:+ return None+ # Copy-on-write before mutate (see set_tool_start).+ starts = dict(starts)+ if key and key in starts:+ tool_name_stored, start_monotonic = starts.pop(key)+ _tool_starts.set(starts or None)+ return tool_name_stored, start_monotonic+ if len(starts) == 1:+ only_key = next(iter(starts))+ tool_name_stored, start_monotonic = starts.pop(only_key)+ _tool_starts.set(None)+ return tool_name_stored, start_monotonic+ anon_for_name = [+ candidate_key+ for candidate_key, value in list(starts.items())+ if candidate_key.startswith("__anon__") and tool_name and value[0] == tool_name+ ]+ if len(anon_for_name) == 1:+ candidate_key = anon_for_name[0]+ value = starts.pop(candidate_key)+ _tool_starts.set(starts or None)+ return value+ return Nonediff --git a/jiuwenswarm/perf/events.py b/jiuwenswarm/perf/events.pynew file mode 100644index 0000000000..612dc18cc4--- /dev/null+++ b/jiuwenswarm/perf/events.py@@ -0,0 +1,43 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from dataclasses import dataclass+++@dataclass(frozen=True)+class LlmPerfEvent:+ llm_call_id: str+ duration_ms: float+ model: str+ iteration: int+ input_tokens: int+ output_tokens: int+ status: str+ agent_id: str = ""+ task_id: str | None = None+ stream_source_id: str | None = None+ error_message: str | None = None+++@dataclass(frozen=True)+class ToolPerfEvent:+ tool_call_id: str+ name: str+ duration_ms: float+ status: str+ agent_id: str = ""+ task_id: str | None = None+ iteration: int = 0+ error_message: str | None = None+++@dataclass(frozen=True)+class TaskPerfEvent:+ task_id: str+ task_content: str+ source: str+ started_at: float+ ended_at: float+ duration_ms: float+ status: strdiff --git a/jiuwenswarm/perf/extract.py b/jiuwenswarm/perf/extract.pynew file mode 100644index 0000000000..466b01875a--- /dev/null+++ b/jiuwenswarm/perf/extract.py@@ -0,0 +1,329 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import json+import logging+from typing import Any++logger = logging.getLogger(__name__)++_OK_STATUS_VALUES = frozenset({"ok", "success", "succeeded", "completed", "skipped"})+_ERROR_STATUS_VALUES = frozenset({"error", "failed", "failure", "timeout", "cancelled"})+++def extract_agent_id(agent: Any, *, deep_agent: Any | None = None) -> str:+ """Extract a stable agent identifier (card.id / subagent_id), not internal instance uuid.++ Prefer the explicit ``deep_agent`` / ``agent`` card (the rail owner). Ambient+ ContextVar subagent ids are last-resort only — after TaskTool returns, leftover+ subagent context must not relabel the parent's tool/LLM events.+ """+ for source in (deep_agent, agent):+ if source is None:+ continue+ card = getattr(source, "card", None)+ if card is not None:+ for attr in ("id", "name"):+ value = str(getattr(card, attr, "") or "").strip()+ if value and not _is_internal_instance_id(value):+ return value++ if agent is not None:+ raw_id = str(getattr(agent, "id", "") or "").strip()+ if raw_id and not _is_internal_instance_id(raw_id):+ return raw_id++ subagent_id = resolve_subagent_id()+ if subagent_id:+ return subagent_id+ return ""+++def _is_internal_instance_id(value: str) -> bool:+ """32-char hex string —openjiuwen runtime instance id, not a logical agent id."""+ text = value.strip().lower()+ return len(text) == 32 and all(ch in "0123456789abcdef" for ch in text)+++def extract_model_info(agent: Any) -> tuple[str, str]:+ """Extract (model_name, provider) from an agent instance."""+ if agent is None:+ return "", "unknown"++ config = getattr(agent, "_config", None)+ model_name = getattr(agent, "model_name", "")+ if not model_name and config is not None:+ model_name = getattr(config, "model_name", "")++ provider = getattr(agent, "model_provider", "")+ if not provider and config is not None:+ provider = getattr(config, "model_provider", "")++ if not provider:+ mcc = getattr(agent, "model_client_config", None)+ if mcc is None and config is not None:+ mcc = getattr(config, "model_client_config", None)+ if mcc is not None:+ if isinstance(mcc, dict):+ provider = mcc.get("client_provider", "")+ else:+ provider = getattr(mcc, "client_provider", "")++ system = str(provider).lower() if provider else "unknown"+ return str(model_name or ""), system+++def extract_llm_result(ctx: Any) -> Any:+ inputs = getattr(ctx, "inputs", None)+ if inputs is not None:+ result = getattr(inputs, "response", None)+ if result is None and isinstance(inputs, dict):+ result = inputs.get("response")+ if result is not None:+ return result+ return getattr(ctx, "result", None)+++def extract_usage_tokens(result: Any) -> tuple[int, int, int]:+ if result is None:+ return 0, 0, 0+ usage = getattr(result, "usage_metadata", None)+ if usage is None and isinstance(result, dict):+ usage = result.get("usage_metadata", result)+ if usage is None:+ return 0, 0, 0+ if isinstance(usage, dict):+ input_tokens = int(usage.get("input_tokens") or 0)+ output_tokens = int(usage.get("output_tokens") or 0)+ cache_read = int(+ usage.get("cache_read_input_tokens")+ or usage.get("cache_read_tokens")+ or 0+ )+ return input_tokens, output_tokens, cache_read+ input_tokens = int(getattr(usage, "input_tokens", 0) or 0)+ output_tokens = int(getattr(usage, "output_tokens", 0) or 0)+ cache_read = int(+ getattr(usage, "cache_read_input_tokens", 0)+ or getattr(usage, "cache_read_tokens", 0)+ or 0+ )+ return input_tokens, output_tokens, cache_read+++def llm_status_from_ctx(ctx: Any) -> str:+ err = getattr(ctx, "error", None)+ return "error" if err else "ok"+++def extract_llm_error(ctx: Any) -> str | None:+ err = getattr(ctx, "error", None)+ if err is None:+ return None+ text = str(err).strip()+ return text[:512] if text else None+++def _normalize_status(value: Any) -> str | None:+ if value is None:+ return None+ norm = str(value).strip().lower()+ if norm in _OK_STATUS_VALUES:+ return "ok"+ if norm in _ERROR_STATUS_VALUES:+ return "error"+ return None+++def _looks_like_success_text(text: str) -> bool:+ lower = text.strip().lower()+ if not lower:+ return True+ if lower.startswith("successfully"):+ return True+ if lower.startswith("ok"):+ return True+ if "跳过大纲确认" in text or "skipped" in lower:+ return True+ return False+++def _extract_explicit_error_field(result: Any) -> str | None:+ """Read only explicit error fields —never treat informational message as failure."""+ if result is None:+ return None+ if isinstance(result, dict):+ err = result.get("error")+ if err:+ text = str(err).strip()+ if text and not _looks_like_success_text(text):+ return text[:512]+ return None+ if hasattr(result, "error"):+ err = getattr(result, "error", None)+ if err:+ text = str(err).strip()+ if text and not _looks_like_success_text(text):+ return text[:512]+ return None+++def tool_status_from_result(result: Any) -> str:+ if result is None:+ return "ok"++ if isinstance(result, dict):+ if "success" in result:+ return "ok" if bool(result["success"]) else "error"+ status = _normalize_status(result.get("status"))+ if status is not None:+ return status+ if _extract_explicit_error_field(result):+ return "error"+ return "ok"++ if hasattr(result, "success"):+ return "ok" if bool(getattr(result, "success")) else "error"+ if hasattr(result, "status"):+ status = _normalize_status(getattr(result, "status"))+ if status is not None:+ return status+ if _extract_explicit_error_field(result):+ return "error"++ result_str = str(result)+ if not result_str:+ return "ok"+ if _looks_like_success_text(result_str):+ return "ok"+ lower = result_str.lower()+ if "traceback (most recent call last)" in lower:+ return "error"+ if lower.startswith("error:") or lower.startswith("exception:"):+ return "error"+ if "execution error" in lower or "execution timeout" in lower:+ return "error"+ if "timeout after" in lower:+ return "error"+ return "ok"+++def extract_tool_error(result: Any) -> str | None:+ if tool_status_from_result(result) != "error":+ return None+ explicit = _extract_explicit_error_field(result)+ if explicit:+ return explicit+ if isinstance(result, str):+ text = result.strip()+ return text[:512] if text else "unknown error"+ text = str(result).strip()+ return text[:512] if text else "unknown error"+++def extract_tool_call_info(ctx: Any) -> tuple[str, str, dict[str, Any]]:+ tool_name = ""+ tool_call_id = ""+ arguments: dict[str, Any] = {}+ inputs = getattr(ctx, "inputs", None)+ if inputs is not None:+ if hasattr(inputs, "tool_call"):+ tc = inputs.tool_call+ tool_name = getattr(tc, "name", "") or ""+ tool_call_id = getattr(tc, "id", "") or ""+ arguments = getattr(tc, "arguments", {}) or {}+ elif hasattr(inputs, "tool_name"):+ tool_name = getattr(inputs, "tool_name", "") or ""+ if isinstance(arguments, str):+ try:+ arguments = json.loads(arguments)+ except (json.JSONDecodeError, TypeError):+ arguments = {}+ if not isinstance(arguments, dict):+ arguments = {}+ return tool_name, tool_call_id, arguments+++def extract_tool_result(ctx: Any) -> Any:+ inputs = getattr(ctx, "inputs", None)+ if inputs is not None and hasattr(inputs, "tool_result"):+ return inputs.tool_result+ return None+++def resolve_subagent_id() -> str | None:+ """Best-effort subagent id for perf attribution; safe when APIs differ."""+ try:+ from jiuwenswarm.agents.harness.common.rails import subagent_rail as _subagent_rail++ getter = getattr(_subagent_rail, "get_current_subagent_id", None)+ if callable(getter):+ subagent_id = getter()+ if subagent_id:+ return str(subagent_id)+ except Exception as exc:+ logger.debug(+ "[perf] resolve_subagent_id failed: %s",+ exc,+ exc_info=True,+ )+ return None+++def extract_stream_source_id(ctx: Any) -> str | None:+ for attr in ("stream_source_id",):+ value = getattr(ctx, attr, None)+ if value:+ return str(value)+ extra = getattr(ctx, "extra", None)+ if isinstance(extra, dict):+ value = extra.get("stream_source_id")+ if value:+ return str(value)+ return None+++def extract_react_iteration(ctx: Any) -> int:+ """Read ReAct loop iteration —perf counter first, then framework inputs."""+ from jiuwenswarm.perf.context import get_react_iteration++ perf_iter = get_react_iteration()+ if perf_iter > 0:+ return perf_iter++ inputs = getattr(ctx, "inputs", None)+ if inputs is None:+ return 0+ for attr in ("iteration", "iter", "step", "round"):+ value = getattr(inputs, attr, None)+ if value is not None:+ try:+ parsed = int(value)+ if parsed > 0:+ return parsed+ except (TypeError, ValueError):+ pass+ if isinstance(inputs, dict):+ for key in ("iteration", "iter", "step", "round"):+ if key in inputs:+ try:+ parsed = int(inputs[key])+ if parsed > 0:+ return parsed+ except (TypeError, ValueError):+ pass+ return 0+++def current_trace_id_hex() -> str | None:+ try:+ from opentelemetry import trace++ span = trace.get_current_span()+ span_context = span.get_span_context()+ if span_context is None or not span_context.trace_id:+ return None+ return format(span_context.trace_id, "032x")+ except Exception:+ return Nonediff --git a/jiuwenswarm/perf/guard.py b/jiuwenswarm/perf/guard.pynew file mode 100644index 0000000000..24bfeb8368--- /dev/null+++ b/jiuwenswarm/perf/guard.py@@ -0,0 +1,28 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Best-effort perf helpers — failures must never break the agent path."""++from __future__ import annotations++import logging+from collections.abc import Callable+from typing import TypeVar++logger = logging.getLogger(__name__)++T = TypeVar("T")+++def run_perf_safe(+ component: str,+ action: str,+ callback: Callable[[], T],+ *,+ default: T | None = None,+) -> T | None:+ """Run a perf-side effect; log and return default instead of raising."""+ try:+ return callback()+ except Exception as exc:+ logger.warning("[%s] %s failed: %s", component, action, exc)+ return defaultdiff --git a/jiuwenswarm/perf/install_hooks.py b/jiuwenswarm/perf/install_hooks.pynew file mode 100644index 0000000000..42d9eb3988--- /dev/null+++ b/jiuwenswarm/perf/install_hooks.py@@ -0,0 +1,18 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Install swarm-side perf hooks (DeepAdapter is wired separately).++Parent request boundaries live in ``interface_deep`` / ``interface_code``.+This installer patches ``DeepAgent.create_subagent`` so TaskTool children also+get ``RequestSummaryRail(record_only=True)``.+"""++from __future__ import annotations++from typing import Any++from jiuwenswarm.perf.subagent_hooks import apply_create_subagent_perf_patch+++def install_perf_hooks(_adapter: Any = None) -> None:+ """Apply create_subagent RequestSummaryRail patch (idempotent)."""+ apply_create_subagent_perf_patch()diff --git a/jiuwenswarm/perf/interface_hooks.py b/jiuwenswarm/perf/interface_hooks.pynew file mode 100644index 0000000000..9fbac007c1--- /dev/null+++ b/jiuwenswarm/perf/interface_hooks.py@@ -0,0 +1,154 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Deep adapter integration hooks for request_summaries.jsonl."""++from __future__ import annotations++from typing import Any++from jiuwenswarm.perf.collector import get_perf_collector+from jiuwenswarm.perf.config import get_perf_summary_config+from jiuwenswarm.perf.context import (+ clear_request_context,+ mark_first_answer_latency,+ mark_first_byte_latency,+ set_request_context,+)+from jiuwenswarm.perf.guard import run_perf_safe++_COMPONENT = "JiuWenSwarmDeepAdapter"++# Align with history.jsonl assistant surface: first tool/reasoning/answer event.+_FIRST_BYTE_EVENT_TYPES = frozenset(+ {"chat.delta", "chat.final", "chat.tool_call", "chat.reasoning"}+)+# Answer-token only (excludes tool_call / reasoning).+_FIRST_ANSWER_EVENT_TYPES = frozenset({"chat.delta", "chat.final"})+++def set_perf_summary_context(+ rail: Any | None = None,+ *,+ channel_id: str = "",+ session_id: str = "",+ request_id: str = "",+ mode: str = "agent.plan",+ service_id: str | None = None,+ agent_id: str | None = None,+) -> None:+ """Bind perf request context at parent-agent request entry.++ Always begins the collector request (even if ``rail`` is None). When a+ RequestSummaryRail is present, also bind on the rail instance so LLM/tool+ hooks running on DeepAgent's interaction-round Task can resolve request_id+ without relying on ContextVar inheritance.+ """++ def _setup() -> None:+ if not get_perf_summary_config().enabled:+ return+ ctx = set_request_context(+ session_id=session_id,+ request_id=request_id,+ channel_id=channel_id,+ mode=mode,+ service_id=service_id,+ agent_id=agent_id,+ )+ bind = getattr(rail, "bind_request_context", None)+ if callable(bind):+ bind(ctx)++ run_perf_safe(+ _COMPONENT,+ "perf summary context setup",+ _setup,+ )+++def mark_request_first_byte() -> None:+ """Record first history-visible assistant event latency."""+ run_perf_safe(+ _COMPONENT,+ "perf summary first-byte mark",+ mark_first_byte_latency,+ )+++def mark_request_first_answer() -> None:+ """Record first answer-token latency (chat.delta / chat.final)."""+ run_perf_safe(+ _COMPONENT,+ "perf summary first-answer mark",+ mark_first_answer_latency,+ )+++def maybe_mark_answer_first_byte(payload: Any) -> None:+ """Mark first-byte / first-answer from a streamed chat payload."""+ if not isinstance(payload, dict):+ return+ event_type = payload.get("event_type")+ if event_type in _FIRST_BYTE_EVENT_TYPES:+ mark_request_first_byte()+ if event_type in _FIRST_ANSWER_EVENT_TYPES:+ mark_request_first_answer()+++def finalize_perf_summary_request(+ request_id: str | None,+ *,+ status: str = "ok",+) -> None:+ """Finalize and persist request summary; safe to call from finally blocks."""+ rid = (request_id or "").strip()+ if not rid:+ return++ def _finalize() -> None:+ from jiuwenswarm.perf.extract import current_trace_id_hex++ trace_id = current_trace_id_hex()+ acc = get_perf_collector().get_accumulator(rid)+ if acc is not None and trace_id:+ acc.meta = acc.meta.with_trace_id(trace_id)+ get_perf_collector().finalize_request(rid, status=status)++ run_perf_safe(+ _COMPONENT,+ f"perf summary finalize request_id={rid} status={status}",+ _finalize,+ )+++def clear_perf_summary_context(+ rail: Any | None = None,+ *,+ session_id: str | None = None,+ request_id: str | None = None,+) -> None:+ """Clear perf ContextVar + session registry + optional rail binding."""++ def _clear() -> None:+ clear_fn = getattr(rail, "clear_bound_request_context", None)+ if callable(clear_fn):+ clear_fn()+ clear_request_context(session_id=session_id, request_id=request_id)++ run_perf_safe(+ _COMPONENT,+ "perf summary context clear",+ _clear,+ )+++def install_perf_hooks(_adapter: Any = None) -> None:+ """Install create_subagent RequestSummaryRail(record_only) attachment.++ Parent DeepAdapter already wires the rail in ``interface_deep`` /+ ``interface_code``. This covers TaskTool / SessionSpawn children via+ ``DeepAgent.create_subagent`` patching.+ """+ from jiuwenswarm.perf.subagent_hooks import apply_create_subagent_perf_patch++ apply_create_subagent_perf_patch()diff --git a/jiuwenswarm/perf/request_summary_rail.py b/jiuwenswarm/perf/request_summary_rail.pynew file mode 100644index 0000000000..60e8a02298--- /dev/null+++ b/jiuwenswarm/perf/request_summary_rail.py@@ -0,0 +1,327 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""RequestSummaryRail — collect per-request performance summaries via DeepAgent hooks."""++from __future__ import annotations++import functools+import logging+import os+import time+from typing import Any++from openjiuwen.harness.rails.base import DeepAgentRail++from jiuwenswarm.perf.collector import get_perf_collector+from jiuwenswarm.perf.config import get_perf_summary_config+from jiuwenswarm.perf.context import (+ clear_current_llm_call,+ clear_request_context,+ extract_session_id_from_callback,+ get_current_llm_call,+ get_request_context,+ increment_react_iteration,+ pop_tool_start,+ reset_react_iteration,+ resolve_task_id,+ set_current_llm_call,+ set_tool_start,+ set_request_context,+)+from jiuwenswarm.perf.events import LlmPerfEvent, ToolPerfEvent+from jiuwenswarm.perf.extract import (+ current_trace_id_hex,+ extract_agent_id,+ extract_llm_error,+ extract_llm_result,+ extract_model_info,+ extract_react_iteration,+ extract_stream_source_id,+ extract_tool_call_info,+ extract_tool_error,+ extract_tool_result,+ extract_usage_tokens,+ llm_status_from_ctx,+ tool_status_from_result,+)+from jiuwenswarm.perf.guard import run_perf_safe++logger = logging.getLogger(__name__)+++def _hook_safe(method):+ @functools.wraps(method)+ async def wrapper(self: RequestSummaryRail, *args, **kwargs):+ if self.is_hook_degraded():+ return None+ try:+ return await method(self, *args, **kwargs)+ except Exception as exc:+ self.register_hook_failure(method.__name__, exc)+ return None++ return wrapper+++def _resolve_request_id(req_ctx: dict[str, Any] | None) -> str | None:+ if req_ctx is None:+ return None+ request_id = str(req_ctx.get("request_id") or "").strip()+ return request_id or None+++class RequestSummaryRail(DeepAgentRail):+ """Collect llm/tool timings into request_summaries.jsonl."""++ priority = 11++ def __init__(self, *, record_only: bool = False) -> None:+ super().__init__()+ self._record_only = record_only+ self._deep_agent: Any | None = None+ self._fixed_agent_id: str = ""+ self._bound_request_ctx: dict[str, Any] | None = None+ self._failure_count = 0+ self._degraded = False+ try:+ self._failure_threshold = int(os.getenv("PERF_SUMMARY_HOOK_FAILURE_THRESHOLD", "10"))+ except ValueError:+ self._failure_threshold = 10++ def init(self, agent: Any) -> None:+ """Store DeepAgent reference for stable card.id extraction."""+ self._deep_agent = agent+ # Freeze owner id at init so TaskTool's nested subagent invoke cannot+ # relabel this rail's subsequent parent after_tool_call events.+ self._fixed_agent_id = extract_agent_id(agent, deep_agent=agent)++ def _event_agent_id(self, ctx: Any) -> str:+ if self._fixed_agent_id:+ return self._fixed_agent_id+ agent = getattr(ctx, "agent", None) if ctx is not None else None+ return extract_agent_id(agent, deep_agent=self._deep_agent)++ def is_hook_degraded(self) -> bool:+ return self._degraded++ def register_hook_failure(self, hook_name: str, exc: Exception) -> None:+ self._failure_count += 1+ logger.warning(+ "[RequestSummaryRail] hook %s failed (%d/%d): %s",+ hook_name,+ self._failure_count,+ self._failure_threshold,+ exc,+ )+ if self._failure_count >= self._failure_threshold:+ self._degraded = True+ logger.warning(+ "[RequestSummaryRail] circuit breaker tripped — hooks disabled until restart"+ )++ def bind_request_context(self, ctx: dict[str, Any] | None) -> None:+ """Keep a task-independent binding for interaction-round hooks."""+ self._bound_request_ctx = ctx++ def clear_bound_request_context(self) -> None:+ self._bound_request_ctx = None++ def _active_request_context(self, callback_ctx: Any = None) -> dict[str, Any] | None:+ """Resolve request meta across stream Task vs interaction-round Task.++ Preference order:+ 1. task-local ContextVar (stream / same-task callers)+ 2. rail instance binding (parent adapter set at request entry)+ 3. session registry (subagent rails / round Task without ContextVar)+ """+ ctx = get_request_context()+ if ctx is not None:+ return ctx+ if self._bound_request_ctx is not None:+ return self._bound_request_ctx+ session_id = extract_session_id_from_callback(callback_ctx)+ if session_id:+ return get_request_context(session_id=session_id)+ return None++ def set_request_context(+ self,+ *,+ channel_id: str = "",+ session_id: str = "",+ request_id: str = "",+ mode: str = "agent.plan",+ trace_id: str | None = None,+ service_id: str | None = None,+ agent_id: str | None = None,+ ) -> None:+ if not get_perf_summary_config().enabled:+ return++ def _bind() -> None:+ ctx = set_request_context(+ session_id=session_id,+ request_id=request_id,+ channel_id=channel_id,+ mode=mode,+ trace_id=trace_id,+ service_id=service_id,+ agent_id=agent_id,+ )+ self.bind_request_context(ctx)++ run_perf_safe(+ "RequestSummaryRail",+ "set_request_context",+ _bind,+ )++ @_hook_safe+ async def before_invoke(self, ctx: Any) -> None:+ if not get_perf_summary_config().enabled:+ return+ reset_react_iteration()++ @_hook_safe+ async def after_invoke(self, ctx: Any) -> None:+ if not get_perf_summary_config().enabled:+ return+ if self._record_only:+ return+ req_ctx = self._active_request_context(ctx)+ request_id = _resolve_request_id(req_ctx)+ if request_id is None:+ return++ status = "error" if getattr(ctx, "error", None) else "ok"+ trace_id = current_trace_id_hex()+ acc = get_perf_collector().get_accumulator(request_id)+ if acc is not None and trace_id:+ acc.meta = acc.meta.with_trace_id(trace_id)+ get_perf_collector().finalize_request(request_id, status=status)+ session_id = str((req_ctx or {}).get("session_id") or "") or None+ clear_request_context(session_id=session_id, request_id=request_id)+ self.clear_bound_request_context()++ @_hook_safe+ async def before_model_call(self, ctx: Any) -> None:+ if not get_perf_summary_config().enabled:+ return+ increment_react_iteration()+ call_id = str(time.monotonic_ns())+ set_current_llm_call(call_id, time.monotonic())++ @_hook_safe+ async def after_model_call(self, ctx: Any) -> None:+ if not get_perf_summary_config().enabled:+ return+ call_id, start_monotonic = get_current_llm_call()+ if not call_id or start_monotonic is None:+ clear_current_llm_call()+ return++ req_ctx = self._active_request_context(ctx)+ request_id = _resolve_request_id(req_ctx)+ if request_id is None:+ clear_current_llm_call()+ return++ duration_ms = max(0.0, (time.monotonic() - start_monotonic) * 1000.0)+ agent = getattr(ctx, "agent", None)+ model_name, _ = extract_model_info(agent)+ result = extract_llm_result(ctx)+ input_tokens, output_tokens, cache_read = extract_usage_tokens(result)+ acc = get_perf_collector().get_accumulator(request_id)+ if acc is not None and cache_read:+ acc.cache_read_tokens += cache_read++ llm_status = llm_status_from_ctx(ctx)+ event = LlmPerfEvent(+ llm_call_id=str(call_id),+ duration_ms=duration_ms,+ model=model_name,+ iteration=extract_react_iteration(ctx),+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ status=llm_status,+ agent_id=self._event_agent_id(ctx),+ task_id=resolve_task_id(request_ctx=req_ctx),+ stream_source_id=extract_stream_source_id(ctx),+ error_message=extract_llm_error(ctx) if llm_status != "ok" else None,+ )+ get_perf_collector().record_llm(request_id, event)+ clear_current_llm_call()++ @_hook_safe+ async def on_model_exception(self, ctx: Any) -> None:+ if not get_perf_summary_config().enabled:+ return+ call_id, start_monotonic = get_current_llm_call()+ if not call_id or start_monotonic is None:+ clear_current_llm_call()+ return++ req_ctx = self._active_request_context(ctx)+ request_id = _resolve_request_id(req_ctx)+ if request_id is None:+ clear_current_llm_call()+ return++ duration_ms = max(0.0, (time.monotonic() - start_monotonic) * 1000.0)+ agent = getattr(ctx, "agent", None)+ model_name, _ = extract_model_info(agent)+ event = LlmPerfEvent(+ llm_call_id=str(call_id),+ duration_ms=duration_ms,+ model=model_name,+ iteration=extract_react_iteration(ctx),+ input_tokens=0,+ output_tokens=0,+ status="error",+ agent_id=self._event_agent_id(ctx),+ task_id=resolve_task_id(request_ctx=req_ctx),+ stream_source_id=extract_stream_source_id(ctx),+ error_message=extract_llm_error(ctx) or "model exception",+ )+ get_perf_collector().record_llm(request_id, event)+ clear_current_llm_call()++ @_hook_safe+ async def before_tool_call(self, ctx: Any) -> None:+ if not get_perf_summary_config().enabled:+ return+ tool_name, tool_call_id, _ = extract_tool_call_info(ctx)+ set_tool_start(tool_call_id, tool_name, time.monotonic())++ @_hook_safe+ async def after_tool_call(self, ctx: Any) -> None:+ if not get_perf_summary_config().enabled:+ return++ tool_name, tool_call_id, _ = extract_tool_call_info(ctx)+ tool_start = pop_tool_start(tool_call_id, tool_name)+ if tool_start is not None:+ resolved_name, start_monotonic = tool_start+ tool_name = tool_name or resolved_name+ duration_ms = max(0.0, (time.monotonic() - start_monotonic) * 1000.0)+ else:+ duration_ms = 0.0++ req_ctx = self._active_request_context(ctx)+ request_id = _resolve_request_id(req_ctx)+ if request_id is None:+ return++ result = extract_tool_result(ctx)+ tool_status = tool_status_from_result(result)+ event = ToolPerfEvent(+ tool_call_id=tool_call_id or f"tool_{time.monotonic_ns()}",+ name=tool_name or "unknown",+ duration_ms=duration_ms,+ status=tool_status,+ agent_id=self._event_agent_id(ctx),+ task_id=resolve_task_id(request_ctx=req_ctx),+ iteration=extract_react_iteration(ctx),+ error_message=extract_tool_error(result) if tool_status != "ok" else None,+ )+ get_perf_collector().record_tool(request_id, event)diff --git a/jiuwenswarm/perf/stats.py b/jiuwenswarm/perf/stats.pynew file mode 100644index 0000000000..f6368039e8--- /dev/null+++ b/jiuwenswarm/perf/stats.py@@ -0,0 +1,136 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any+++def ms_to_s(ms: float) -> float:+ """Convert milliseconds to seconds (3 decimal places)."""+ return round(ms / 1000.0, 3)+++def percentile_s(values: list[float], pct: float) -> float:+ """Return percentile duration in seconds from millisecond samples."""+ if not values:+ return 0.0+ if len(values) == 1:+ return ms_to_s(values[0])+ ordered = sorted(values)+ rank = max(0, min(len(ordered) - 1, int(round((len(ordered) - 1) * pct))))+ return ms_to_s(ordered[rank])+++@dataclass+class LlmStatsAccumulator:+ count: int = 0+ total_ms: float = 0.0+ fail_count: int = 0+ max_ms: float = 0.0+ durations: list[float] = field(default_factory=list)++ def record(+ self,+ *,+ duration_ms: float,+ status: str,+ ) -> None:+ self.count += 1+ self.total_ms += duration_ms+ self.durations.append(duration_ms)+ if duration_ms > self.max_ms:+ self.max_ms = duration_ms+ if status != "ok":+ self.fail_count += 1++ def to_dict(self) -> dict[str, Any]:+ if self.count == 0:+ return {+ "count": 0,+ "total_s": 0.0,+ "fail_count": 0,+ "max_s": 0.0,+ "p90_duration_s": 0.0,+ }+ return {+ "count": self.count,+ "total_s": ms_to_s(self.total_ms),+ "fail_count": self.fail_count,+ "max_s": ms_to_s(self.max_ms),+ "p90_duration_s": percentile_s(self.durations, 0.90),+ }+++@dataclass+class ToolStatsAccumulator:+ count: int = 0+ total_ms: float = 0.0+ fail_count: int = 0+ max_ms: float = 0.0+ durations: list[float] = field(default_factory=list)+ iterations: set[int] = field(default_factory=set)+ by_name: dict[str, int] = field(default_factory=dict)++ def record(+ self,+ *,+ duration_ms: float,+ status: str,+ name: str = "",+ iteration: int = 0,+ ) -> None:+ self.count += 1+ self.total_ms += duration_ms+ self.durations.append(duration_ms)+ if duration_ms > self.max_ms:+ self.max_ms = duration_ms+ if status != "ok":+ self.fail_count += 1+ if iteration > 0:+ self.iterations.add(iteration)+ if name:+ self.by_name[name] = self.by_name.get(name, 0) + 1++ def _tool_list(self) -> list[dict[str, Any]]:+ return [+ {"name": name, "count": count}+ for name, count in sorted(self.by_name.items(), key=lambda item: (-item[1], item[0]))+ ]++ def to_dict(self) -> dict[str, Any]:+ if self.count == 0:+ return {+ "count": 0,+ "round_count": 0,+ "total_s": 0.0,+ "fail_count": 0,+ "max_s": 0.0,+ "p90_duration_s": 0.0,+ "list": [],+ }+ return {+ "count": self.count,+ "round_count": len(self.iterations),+ "total_s": ms_to_s(self.total_ms),+ "fail_count": self.fail_count,+ "max_s": ms_to_s(self.max_ms),+ "p90_duration_s": percentile_s(self.durations, 0.90),+ "list": self._tool_list(),+ }+++def maintain_top_n(+ entries: list[dict[str, Any]],+ candidate: dict[str, Any],+ *,+ top_n: int,+ duration_key: str = "duration_s",+) -> list[dict[str, Any]]:+ """Keep the slowest top_n entries sorted by duration descending."""+ merged = [*entries, candidate]+ merged.sort(key=lambda item: item.get(duration_key, 0), reverse=True)+ trimmed = merged[:top_n]+ for idx, item in enumerate(trimmed, start=1):+ item["rank"] = idx+ return trimmeddiff --git a/jiuwenswarm/perf/subagent_hooks.py b/jiuwenswarm/perf/subagent_hooks.pynew file mode 100644index 0000000000..0d18505998--- /dev/null+++ b/jiuwenswarm/perf/subagent_hooks.py@@ -0,0 +1,104 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Attach RequestSummaryRail to TaskTool/create_subagent children.++Enterprise wires record-only rails inside ``subagent_executor``; jiuwenswarm+uses core ``DeepAgent.create_subagent`` instead. Patching that entry point+covers TaskTool, SessionSpawnExecutor, and the /debug TaskTool reimplementation.+"""++from __future__ import annotations++from typing import Any++from jiuwenswarm.common.utils import logger+from jiuwenswarm.perf.config import get_perf_summary_config+from jiuwenswarm.perf.guard import run_perf_safe++_COMPONENT = "perf.subagent_hooks"+_PATCH_APPLIED = False+++def _agent_has_request_summary_rail(agent: Any) -> bool:+ configured = agent.configured_rails() if hasattr(agent, "configured_rails") else []+ for rail in configured or []:+ if rail.__class__.__name__ == "RequestSummaryRail":+ return True+ return False+++def attach_request_summary_rail(subagent: Any) -> bool:+ """Attach ``RequestSummaryRail(record_only=True)`` after create_subagent.++ Idempotent and best-effort: never raises into the spawn path.+ Returns True when a rail was newly attached.+ """+ if subagent is None:+ return False+ if not get_perf_summary_config().enabled:+ return False++ attached = {"ok": False}++ def _attach() -> None:+ from jiuwenswarm.perf.request_summary_rail import RequestSummaryRail++ if _agent_has_request_summary_rail(subagent):+ return+ add_rail = getattr(subagent, "add_rail", None)+ if not callable(add_rail):+ logger.debug(+ "[perf] subagent has no add_rail; skip RequestSummaryRail attach"+ )+ return+ rail = RequestSummaryRail(record_only=True)+ add_rail(rail)+ attached["ok"] = True+ logger.info(+ "[perf] RequestSummaryRail(record_only) attached to subagent id=%s",+ getattr(getattr(subagent, "card", None), "id", None),+ )++ run_perf_safe(_COMPONENT, "attach RequestSummaryRail to subagent", _attach)+ return bool(attached["ok"])+++def apply_create_subagent_perf_patch() -> None:+ """Wrap ``DeepAgent.create_subagent`` to attach record-only perf rail.++ Idempotent. Safe when perf.summary.enabled is false (attach is a no-op).+ """+ global _PATCH_APPLIED+ if _PATCH_APPLIED:+ return++ try:+ from openjiuwen.harness.deep_agent import DeepAgent+ except Exception as exc: # noqa: BLE001+ logger.warning("[perf] DeepAgent unavailable; skip create_subagent patch: %s", exc)+ return++ if getattr(DeepAgent, "perf_summary_subagent_patch_applied", False):+ _PATCH_APPLIED = True+ return++ _orig_create_subagent = DeepAgent.create_subagent++ def _create_subagent_with_perf(self, *args, **kwargs): # type: ignore[no-untyped-def]+ subagent = _orig_create_subagent(self, *args, **kwargs)+ try:+ attach_request_summary_rail(subagent)+ except Exception as exc: # noqa: BLE001 — never break spawn+ logger.warning("[perf] create_subagent rail attach skipped: %s", exc)+ return subagent++ DeepAgent.create_subagent = _create_subagent_with_perf # type: ignore[method-assign]+ DeepAgent.perf_summary_subagent_patch_applied = True+ _PATCH_APPLIED = True+ logger.info("[perf] DeepAgent.create_subagent RequestSummaryRail patch applied")+++__all__ = [+ "attach_request_summary_rail",+ "apply_create_subagent_perf_patch",+]diff --git a/jiuwenswarm/perf/task_hooks.py b/jiuwenswarm/perf/task_hooks.pynew file mode 100644index 0000000000..7fe93bb0ce--- /dev/null+++ b/jiuwenswarm/perf/task_hooks.py@@ -0,0 +1,51 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Record completed tasks into the request summary accumulator."""++from __future__ import annotations++import logging++from jiuwenswarm.perf.collector import get_perf_collector+from jiuwenswarm.perf.config import get_perf_summary_config+from jiuwenswarm.perf.events import TaskPerfEvent++logger = logging.getLogger(__name__)+++def notify_task_complete(+ *,+ task_id: str,+ task_content: str,+ source: str,+ started_at: float,+ ended_at: float,+ duration_ms: float,+ status: str,+ request_id: str,+) -> None:+ """Record a completed main-agent todo into the request summary."""+ cfg = get_perf_summary_config()+ if not cfg.enabled or not cfg.include_tasks:+ return++ rid = (request_id or "").strip()+ if not rid:+ logger.debug(+ "[perf] skip task.complete record: no request_id task_id=%s",+ task_id,+ )+ return++ get_perf_collector().record_task(+ rid,+ TaskPerfEvent(+ task_id=task_id,+ task_content=task_content,+ source=source,+ started_at=started_at,+ ended_at=ended_at,+ duration_ms=float(duration_ms),+ status=status,+ ),+ )diff --git a/jiuwenswarm/perf/todo_tracker.py b/jiuwenswarm/perf/todo_tracker.pynew file mode 100644index 0000000000..fbbefdbf15--- /dev/null+++ b/jiuwenswarm/perf/todo_tracker.py@@ -0,0 +1,223 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Track main-agent todo transitions into request_summaries ``tasks``.++Source of truth: parent ``StreamEventRail`` (main workspace todo list).+Team-member / subagent todo lists are never synced here.+"""++from __future__ import annotations++import logging+import threading+import time+from dataclasses import dataclass+from typing import Any, Mapping, Sequence++from jiuwenswarm.perf.config import get_perf_summary_config+from jiuwenswarm.perf.context import get_request_context, set_active_task_id+from jiuwenswarm.perf.task_hooks import notify_task_complete++logger = logging.getLogger(__name__)++_DONE = frozenset({"completed", "cancelled", "canceled"})+_ACTIVE = frozenset({"in_progress"})+_STALE_AGE_S = 7200.0++_LOCK = threading.Lock()+# request_id -> todo_id -> state+_STATES: dict[str, dict[str, "_TodoState"]] = {}+_CREATED_AT: dict[str, float] = {}+++@dataclass+class _TodoState:+ content: str+ status: str+ started_at: float | None = None+ recorded: bool = False+++@dataclass(frozen=True)+class _PendingRecord:+ todo_id: str+ content: str+ status: str+ started_at: float+ ended_at: float+++def sync_main_agent_todos(+ todos: Sequence[Mapping[str, Any]] | None,+ *,+ session_id: str | None = None,+ request_id: str | None = None,+ now: float | None = None,+) -> None:+ """Diff a main-agent todo snapshot and record newly finished items."""+ cfg = get_perf_summary_config()+ if not cfg.enabled or not cfg.include_tasks:+ return++ rid = (request_id or "").strip()+ if not rid:+ req_ctx = get_request_context(session_id=session_id)+ if req_ctx is None:+ logger.debug(+ "[perf] skip todo sync: no request context session_id=%s",+ session_id,+ )+ return+ rid = str(req_ctx.get("request_id") or "").strip()+ if not rid:+ logger.debug(+ "[perf] skip todo sync: empty request_id session_id=%s",+ session_id,+ )+ return++ ts = float(now if now is not None else time.time())+ pending: list[_PendingRecord] = []++ with _LOCK:+ _prune_stale_locked(ts)+ states = _STATES.setdefault(rid, {})+ _CREATED_AT.setdefault(rid, ts)+ for raw in todos or []:+ todo_id = str(raw.get("id") or "").strip()+ if not todo_id:+ continue+ content = str(raw.get("content") or "")+ status = str(raw.get("status") or "pending").strip().lower()+ prev = states.get(todo_id)++ if prev is None:+ # First sight anchors duration when agents skip in_progress.+ state = _TodoState(+ content=content,+ status=status,+ started_at=ts,+ )+ states[todo_id] = state+ if status in _DONE and not state.recorded:+ state.recorded = True+ pending.append(+ _PendingRecord(+ todo_id=todo_id,+ content=content,+ status=status,+ started_at=ts,+ ended_at=ts,+ )+ )+ continue++ if content:+ prev.content = content++ if status in _ACTIVE and prev.status not in _ACTIVE:+ prev.started_at = ts++ if status in _DONE and prev.status not in _DONE and not prev.recorded:+ started_at = prev.started_at if prev.started_at is not None else ts+ prev.recorded = True+ pending.append(+ _PendingRecord(+ todo_id=todo_id,+ content=prev.content or content,+ status=status,+ started_at=started_at,+ ended_at=ts,+ )+ )++ prev.status = status++ # Bind the first in_progress main todo so llm/tool hooks can attribute+ # without enabling TaskExecutionRail (session-registry / shared ctx dict).+ active_task_id = None+ for raw in todos or []:+ todo_id = str(raw.get("id") or "").strip()+ if not todo_id:+ continue+ status = str(raw.get("status") or "pending").strip().lower()+ if status in _ACTIVE:+ active_task_id = f"todo:{todo_id}"+ break+ set_active_task_id(+ active_task_id,+ session_id=session_id,+ request_id=rid,+ )++ for item in pending:+ _emit_record(rid, item)+++def clear_todo_tracker(request_id: str | None) -> None:+ """Drop per-request todo tracking state."""+ rid = (request_id or "").strip()+ if not rid:+ return+ with _LOCK:+ _STATES.pop(rid, None)+ _CREATED_AT.pop(rid, None)+ set_active_task_id(None, request_id=rid)+++def prune_stale_todo_trackers(*, now: float | None = None) -> int:+ """Drop abandoned request trackers older than ``_STALE_AGE_S``."""+ ts = float(now if now is not None else time.time())+ with _LOCK:+ return _prune_stale_locked(ts)+++def _prune_stale_locked(now: float) -> int:+ stale = [+ rid+ for rid, created in _CREATED_AT.items()+ if now - created > _STALE_AGE_S+ ]+ for rid in stale:+ _STATES.pop(rid, None)+ _CREATED_AT.pop(rid, None)+ return len(stale)+++def _emit_record(request_id: str, item: _PendingRecord) -> None:+ duration_ms = max(0.0, (item.ended_at - item.started_at) * 1000.0)+ perf_status = (+ "failed" if item.status in ("cancelled", "canceled") else "succeeded"+ )+ notify_task_complete(+ task_id=f"todo:{item.todo_id}",+ task_content=item.content,+ source="todo",+ started_at=item.started_at,+ ended_at=item.ended_at,+ duration_ms=duration_ms,+ status=perf_status,+ request_id=request_id,+ )+++def todos_from_items(todos_data: Sequence[Any]) -> list[dict[str, str]]:+ """Normalize TodoItem objects / dicts into tracker snapshots."""+ out: list[dict[str, str]] = []+ for item in todos_data or []:+ if isinstance(item, Mapping):+ todo_id = str(item.get("id") or "").strip()+ content = str(item.get("content") or "")+ status_raw = item.get("status", "pending")+ else:+ todo_id = str(getattr(item, "id", "") or "").strip()+ content = str(getattr(item, "content", "") or "")+ status_raw = getattr(item, "status", "pending")+ if not todo_id:+ continue+ if hasattr(status_raw, "value"):+ status = str(status_raw.value)+ else:+ status = str(status_raw or "pending")+ out.append({"id": todo_id, "content": content, "status": status.lower()})+ return outdiff --git a/jiuwenswarm/perf/writer.py b/jiuwenswarm/perf/writer.pynew file mode 100644index 0000000000..7421be6bc3--- /dev/null+++ b/jiuwenswarm/perf/writer.py@@ -0,0 +1,132 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import json+import logging+import queue+import threading+from pathlib import Path+from typing import Any++from jiuwenswarm.common.utils import get_agent_sessions_dir+from jiuwenswarm.perf.guard import run_perf_safe+++def _normalize_tenant_scope_id(value: str | None, *, default: str = "default") -> str:+ if value is None:+ return default+ stripped = str(value).strip()+ return stripped or default++logger = logging.getLogger(__name__)++_FILE_LOCK = threading.Lock()+_WRITE_QUEUE: queue.Queue[tuple[Path, dict[str, Any]]] = queue.Queue(maxsize=20000)+_WORKER_STARTED = False+_WORKER_LOCK = threading.Lock()+++def _resolve_sessions_root(+ *,+ service_id: str | None = None,+ agent_id: str | None = None,+ sessions_root: str | None = None,+) -> Path:+ if sessions_root:+ return Path(sessions_root)+ # develop: single-tenant session layout; tenant ids are kept for metadata only.+ _ = _normalize_tenant_scope_id(service_id)+ _ = _normalize_tenant_scope_id(agent_id)+ return get_agent_sessions_dir()+++def request_summaries_file(+ session_id: str,+ sessions_root: str | None = None,+ *,+ service_id: str | None = None,+ agent_id: str | None = None,+) -> Path:+ root = _resolve_sessions_root(+ service_id=service_id,+ agent_id=agent_id,+ sessions_root=sessions_root,+ )+ session_dir = root / (session_id or "default")+ session_dir.mkdir(parents=True, exist_ok=True)+ return session_dir / "request_summaries.jsonl"+++def _write_item(path: Path, item: dict[str, Any]) -> None:+ with _FILE_LOCK:+ with path.open("a", encoding="utf-8", newline="\n") as fh:+ fh.write(json.dumps(item, ensure_ascii=False))+ fh.write("\n")+++def _ensure_worker_started() -> None:+ global _WORKER_STARTED+ if _WORKER_STARTED:+ return+ with _WORKER_LOCK:+ if _WORKER_STARTED:+ return++ def _worker() -> None:+ while True:+ path, item = _WRITE_QUEUE.get()+ run_perf_safe(+ "RequestSummaryWriter",+ "async write",+ lambda: _write_item(path, item),+ )+ _WRITE_QUEUE.task_done()++ thread = threading.Thread(+ target=_worker,+ name="request-summary-writer",+ daemon=True,+ )+ thread.start()+ _WORKER_STARTED = True+++def flush_request_summary_writer(timeout: float = 5.0) -> None:+ """Block until queued summary writes complete, or until timeout elapses."""+ if not _WORKER_STARTED:+ return+ import time++ deadline = time.monotonic() + max(0.0, timeout)+ while _WRITE_QUEUE.unfinished_tasks > 0:+ if time.monotonic() >= deadline:+ logger.warning(+ "[RequestSummaryWriter] flush timed out with %d pending writes",+ _WRITE_QUEUE.unfinished_tasks,+ )+ return+ time.sleep(0.05)+++def append_request_summary(+ session_id: str,+ summary: dict[str, Any],+ *,+ sessions_root: str | None = None,+ service_id: str | None = None,+ agent_id: str | None = None,+) -> None:+ """Append one request summary line to request_summaries.jsonl."""+ sid = (session_id or "default").strip() or "default"+ path = request_summaries_file(+ sid,+ sessions_root,+ service_id=service_id,+ agent_id=agent_id,+ )+ _ensure_worker_started()+ try:+ _WRITE_QUEUE.put_nowait((path, summary))+ except queue.Full:+ _write_item(path, summary)diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 91b8fd31cc..a8a9775f3b 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -326,6 +326,17 @@ agents:max_iterations: 200completion_timeout: 6000.0+# Request-level performance summaries (request_summaries.jsonl per session).+# Default on; set PERF_SUMMARY_ENABLED=false or enabled: false to opt out.+perf:+ summary:+ enabled: true+ bottleneck_top_n: 3+ include_tasks: true+ include_errors: false+ # Parent+subagent breakdown in stats.by_agent (off by default).+ include_by_agent: false+telemetry:enabled: false # 总开关(环境变量 OTEL_ENABLED 优先)exporter: otlp # otlp / console / nonediff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 07434d2ec7..32ec775697 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -2502,10 +2502,13 @@ class AgentWebSocketServer:)except asyncio.CancelledError:pass- except WebSocketConnectionClosed:+ except WebSocketConnectionClosed as ws_closed_exc:logger.info(- "[AgentWebSocketServer] keepalive 停止,WebSocket 已关闭: request_id=%s",- request.request_id,+ "[AgentWebSocketServer] keepalive 停止,WebSocket 已关闭: %s",+ format_ws_diagnostics(+ {"request_id": request.request_id},+ describe_ws_exception(ws_closed_exc),+ ),)# 启动心跳任务@@ -2547,10 +2550,13 @@ class AgentWebSocketServer:chunk_count - 1,)return- except WebSocketConnectionClosed:+ except WebSocketConnectionClosed as ws_closed_exc:logger.info(- "[AgentWebSocketServer] 流式响应停止,WebSocket 已关闭: request_id=%s",- request.request_id,+ "[AgentWebSocketServer] 流式响应停止,WebSocket 已关闭: %s",+ format_ws_diagnostics(+ {"request_id": request.request_id},+ describe_ws_exception(ws_closed_exc),+ ),)return# 清除 event,让心跳任务重新开始计时diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex 4f84fd917b..a7258e8fa6 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport argparseimport asyncio+import atexitimport loggingimport logging.handlersimport os@@ -142,6 +143,35 @@ from jiuwenswarm.common.thinking.register_hook import register_thinking_hookregister_thinking_hook()+# Attach RequestSummaryRail(record_only=True) after DeepAgent.create_subagent so+# TaskTool / SessionSpawn children contribute llm/tool events to the parent+# request_summaries.jsonl (no-op when perf.summary.enabled is false).+from jiuwenswarm.perf.install_hooks import install_perf_hooks++install_perf_hooks()++# Process exit diagnostics: log reason only; do not change exit code or cleanup order.+_EXIT_REASON = "unknown"+++def _set_exit_reason(reason: str) -> None:+ global _EXIT_REASON+ _EXIT_REASON = reason+++def _atexit_log_exit_reason() -> None:+ # Interpreter/pytest teardown may close handler streams; suppress logging's+ # default "Logging error" spam when emit hits a closed file.+ old_raise = logging.raiseExceptions+ logging.raiseExceptions = False+ try:+ logger.critical("[AgentServer] atexit reason=%s", _EXIT_REASON)+ finally:+ logging.raiseExceptions = old_raise+++atexit.register(_atexit_log_exit_reason)+async def _run(host: str, port: int) -> None:from openjiuwen.core.runner import Runner@@ -153,6 +183,10 @@ async def _run(host: str, port: int) -> None:logger.info("[AgentServer] starting: ws://%s:%s", host, port)+ from jiuwenswarm.perf.config import init_perf_summary_config++ init_perf_summary_config()+# ---------- 扩展系统初始化 ----------callback_framework = Runner.callback_frameworkextension_registry = ExtensionRegistry.create_instance(@@ -221,6 +255,14 @@ async def _run(host: str, port: int) -> None:except Exception as exc:logger.warning("[AgentServer] teammate bootstrap daemon stop failed: %s", exc)await server.stop()+ from jiuwenswarm.perf.guard import run_perf_safe+ from jiuwenswarm.perf.writer import flush_request_summary_writer++ run_perf_safe(+ "AgentServer",+ "request summary flush",+ lambda: flush_request_summary_writer(timeout=5.0),+ )# Shutdown team observability (flush & close spans)try:from jiuwenswarm.agents.harness.team.team_manager import shutdown_team_observability@@ -238,6 +280,7 @@ async def _run(host: str, port: int) -> None:except Exception as exc:logger.warning("[AgentServer] agent observability shutdown failed: %s", exc)logger.info("[AgentServer] stopped")+ _set_exit_reason("clean_shutdown")def main() -> None:@@ -285,7 +328,16 @@ def main() -> None:port = 18092install_async_dump_handler("agentserver")- asyncio.run(_run(host=host, port=port))+ try:+ asyncio.run(_run(host=host, port=port))+ if _EXIT_REASON == "unknown":+ _set_exit_reason("asyncio_run_returned")+ except SystemExit as exc:+ _set_exit_reason(f"SystemExit({exc.code})")+ raise+ except BaseException as exc:+ _set_exit_reason(f"{type(exc).__name__}: {exc}")+ raiseif __name__ == "__main__":diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 57e804de94..1344925ce2 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -349,6 +349,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):# 固定 Rails 名字集合 — 用于动态 Rails 去重_FIXED_RAIL_NAMES = frozenset({+ "RequestSummaryRail","RuntimePromptRail", "ResponsePromptRail","JiuSwarmStreamEventRail", "SecurityRail","LspRail", "ProjectMemoryRail", "PermissionInterruptRail",@@ -575,6 +576,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):"""# 固定 Rails — code 模式特有rail_infos = [+ _RailBuildInfo("_request_summary_rail", self._build_request_summary_rail),_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),_RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),_RailBuildInfo("_skill_retrieval_prompt_rail", self._build_skill_retrieval_prompt_rail),diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex bbe31c0a55..e35239103f 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -310,6 +310,14 @@ from jiuwenswarm.common.mcp_config import (preflight_mcp_server_reachable,)from jiuwenswarm.common.mcp_call_timeout_patch import apply_mcp_call_timeout_patch+from jiuwenswarm.perf.interface_hooks import (+ clear_perf_summary_context,+ finalize_perf_summary_request,+ mark_request_first_answer,+ mark_request_first_byte,+ maybe_mark_answer_first_byte,+ set_perf_summary_context,+)from jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargsfrom jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (build_filesystem_policy,@@ -1410,6 +1418,7 @@ class JiuWenSwarmDeepAdapter:self._skill_rail: SkillUseRail | None = Noneself._stream_event_rail: JiuSwarmStreamEventRail | None = Noneself._task_execution_rail: TaskExecutionRail | None = None+ self._request_summary_rail: Any | None = None# Track session IDs currently executing on this adapter instance.# Used by process_interrupt to avoid aborting sessions that are not# the target of the interrupt request (cross-session contamination).@@ -4785,6 +4794,23 @@ class JiuWenSwarmDeepAdapter:task_rail = Nonereturn task_rail+ @staticmethod+ def _build_request_summary_rail() -> Any | None:+ """Build RequestSummaryRail for per-request performance summaries."""+ try:+ from jiuwenswarm.perf.request_summary_rail import RequestSummaryRail++ # Parent adapter owns finalize; rail only records llm/tool events.+ rail = RequestSummaryRail(record_only=True)+ logger.info("[JiuWenSwarmDeepAdapter] RequestSummaryRail create success")+ except Exception as exc:+ logger.warning(+ "[JiuWenSwarmDeepAdapter] RequestSummaryRail create failed: %s",+ exc,+ )+ rail = None+ return rail+@staticmethoddef _build_multimodal_image_rail(enable_image_multimodal: bool | None = None,@@ -5210,6 +5236,7 @@ class JiuWenSwarmDeepAdapter:) -> list[Any]:"""Build DeepAgent rails consistently for cold start and hot reload."""rail_infos = [+ _RailBuildInfo("_request_summary_rail", self._build_request_summary_rail),_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),_RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),_RailBuildInfo(@@ -9309,6 +9336,15 @@ class JiuWenSwarmDeepAdapter:error_text: str | None = Noneinteraction_stream = Noneinteraction_stream_abort = True+ first_byte_marked = False+ set_perf_summary_context(+ getattr(self, "_request_summary_rail", None),+ channel_id=request.channel_id or "",+ session_id=request.session_id or "",+ request_id=request.request_id or "",+ mode=mode,+ )+ perf_summary_status = "ok"try:await self._update_runtime_config(self._RuntimeConfig(@@ -9413,6 +9449,9 @@ class JiuWenSwarmDeepAdapter:)if text:collected_content.append(text)+ if not first_byte_marked:+ first_byte_marked = True+ mark_request_first_byte()else:# check for error in other typed chunks (e.g. controller_output.task_failed)parsed = self._parse_stream_chunk(chunk)@@ -9422,14 +9461,19 @@ class JiuWenSwarmDeepAdapter:err = parsed.get("error") or parsed.get("message") or ""if err:error_text = str(err)+ perf_summary_status = "error"else:parsed = self._parse_stream_chunk(chunk)if parsed is not None:text = parsed.get("content", "")if text:collected_content.append(text)+ if not first_byte_marked:+ first_byte_marked = True+ mark_request_first_byte()interaction_stream_abort = Falseexcept asyncio.CancelledError:+ perf_summary_status = "cancelled"logger.info("[JiuWenSwarmDeepAdapter] Agent 任务被取消: request_id=%s session_id=%s",request.request_id,@@ -9437,6 +9481,7 @@ class JiuWenSwarmDeepAdapter:)raiseexcept Exception as e:+ perf_summary_status = "error"logger.error("[JiuWenSwarmDeepAdapter] Agent 任务执行异常: %s", e)raisefinally:@@ -9472,6 +9517,12 @@ class JiuWenSwarmDeepAdapter:# cron_* 在 checkpointer 恒为空、web 恢复读不到历史。此处显式补一次。if str(session_id).startswith("cron_"):await self._persist_cron_checkpoint(session_id, request.request_id)+ finalize_perf_summary_request(request.request_id, status=perf_summary_status)+ clear_perf_summary_context(+ getattr(self, "_request_summary_rail", None),+ session_id=session_id,+ request_id=request.request_id,+ )content = "".join(collected_content) if collected_content else ""@@ -9573,94 +9624,144 @@ class JiuWenSwarmDeepAdapter:if mode in ("team", "team.plan", "code.team"):from jiuwenswarm.server.runtime.agent_adapter.team_helpers import process_team_message_stream- resolved_model = self._resolve_model_for_request(request)- self._apply_model_to_react_agent(resolved_model)- inputs = self._prepare_multimodal_image_inputs(request, inputs)- enable_read_image_multimodal = self._native_image_input_enabled(- self._config_cache,- resolved_model,- )- inputs = self._prepare_react_image_tool_prompt(- request,- inputs,- enable_read_image_multimodal=enable_read_image_multimodal,- )- resolved_language = self._resolve_runtime_language()- resolved_channel = str(cid or self._resolve_prompt_channel(session_id) or "web").strip() or "web"- if self._runtime_prompt_rail:- self._runtime_prompt_rail.set_model_name(self._resolve_model_name())- self._runtime_prompt_rail.set_mode(mode)- self._runtime_prompt_rail.set_session_id(session_id)- self._write_runtime_state(+ set_perf_summary_context(+ getattr(self, "_request_summary_rail", None),+ channel_id=request.channel_id or "",+ session_id=request.session_id or "",+ request_id=request.request_id or "",mode=mode,- language=resolved_language,- channel=resolved_channel,- session_id=session_id,- project_dir=inputs.get("project_dir")- or inputs.get("cwd")- or self._project_dir- or self._workspace_dir,)+ perf_summary_status = "ok"+ try:+ resolved_model = self._resolve_model_for_request(request)+ self._apply_model_to_react_agent(resolved_model)+ inputs = self._prepare_multimodal_image_inputs(request, inputs)+ enable_read_image_multimodal = self._native_image_input_enabled(+ self._config_cache,+ resolved_model,+ )+ inputs = self._prepare_react_image_tool_prompt(+ request,+ inputs,+ enable_read_image_multimodal=enable_read_image_multimodal,+ )+ resolved_language = self._resolve_runtime_language()+ resolved_channel = str(cid or self._resolve_prompt_channel(session_id) or "web").strip() or "web"+ if self._runtime_prompt_rail:+ self._runtime_prompt_rail.set_model_name(self._resolve_model_name())+ self._runtime_prompt_rail.set_mode(mode)+ self._runtime_prompt_rail.set_session_id(session_id)+ self._write_runtime_state(+ mode=mode,+ language=resolved_language,+ channel=resolved_channel,+ session_id=session_id,+ project_dir=inputs.get("project_dir")+ or inputs.get("cwd")+ or self._project_dir+ or self._workspace_dir,+ )- async for chunk in process_team_message_stream(request, inputs, self._instance):- yield chunk- _LLM_TRACE_SESSION_ID.reset(token_trace_sid)- _LLM_TRACE_REQUEST_ID.reset(token_trace_rid)- _LLM_TRACE_ITERATION.reset(token_trace_iter)- _LLM_TRACE_MODEL_NAME.reset(token_trace_model)+ async for chunk in process_team_message_stream(request, inputs, self._instance):+ maybe_mark_answer_first_byte(getattr(chunk, "payload", None))+ yield chunk+ except asyncio.CancelledError:+ perf_summary_status = "cancelled"+ raise+ except Exception:+ perf_summary_status = "error"+ raise+ finally:+ finalize_perf_summary_request(request.request_id, status=perf_summary_status)+ clear_perf_summary_context(+ getattr(self, "_request_summary_rail", None),+ session_id=session_id,+ request_id=request.request_id,+ )+ _LLM_TRACE_SESSION_ID.reset(token_trace_sid)+ _LLM_TRACE_REQUEST_ID.reset(token_trace_rid)+ _LLM_TRACE_ITERATION.reset(token_trace_iter)+ _LLM_TRACE_MODEL_NAME.reset(token_trace_model)return# Auto-Harness 模式处理if mode == "auto_harness":- if self._auto_harness_service is None:- self._auto_harness_service = AutoHarnessService(- self._stream_event_rail,- agent=self._instance,+ set_perf_summary_context(+ getattr(self, "_request_summary_rail", None),+ channel_id=request.channel_id or "",+ session_id=request.session_id or "",+ request_id=request.request_id or "",+ mode=mode,+ )+ perf_summary_status = "ok"+ try:+ if self._auto_harness_service is None:+ self._auto_harness_service = AutoHarnessService(+ self._stream_event_rail,+ agent=self._instance,+ )++ await self._update_runtime_config(+ self._RuntimeConfig(+ session_id=session_id,+ mode=mode,+ request_id=request.request_id,+ channel_id=request.channel_id,+ request_metadata=request.metadata,+ trusted_dirs=inputs.get("trusted_dirs"),+ cwd=inputs.get("cwd"),+ project_dir=inputs.get("project_dir"),+ supports_user_interaction=inputs.get(+ "supports_user_interaction", True+ ),+ request_system_prompt=self._extract_request_system_prompt(request),+ ))- await self._update_runtime_config(- self._RuntimeConfig(+ activate_response = request.params.get("activate_response")+ if isinstance(activate_response, dict):+ async for chunk in self._auto_harness_service.resume_activate(+ session_id, rid, cid, activate_response+ ):+ maybe_mark_answer_first_byte(getattr(chunk, "payload", None))+ yield chunk+ else:+ resolved_model = self._resolve_model_for_request(request)+ if self._auto_harness_service.is_activate_only_request(request, query):+ async for chunk in self._auto_harness_service.run_activate_only(+ request, session_id, rid, query, model=resolved_model+ ):+ maybe_mark_answer_first_byte(getattr(chunk, "payload", None))+ yield chunk+ elif self._auto_harness_service.is_implement_only_request(request, query):+ async for chunk in self._auto_harness_service.run_implement_only(+ request, session_id, rid, query, model=resolved_model+ ):+ maybe_mark_answer_first_byte(getattr(chunk, "payload", None))+ yield chunk+ else:+ async for chunk in self._auto_harness_service.run(+ request, session_id, rid, query=query, model=resolved_model+ ):+ maybe_mark_answer_first_byte(getattr(chunk, "payload", None))+ yield chunk+ except asyncio.CancelledError:+ perf_summary_status = "cancelled"+ raise+ except Exception:+ perf_summary_status = "error"+ raise+ finally:+ finalize_perf_summary_request(request.request_id, status=perf_summary_status)+ clear_perf_summary_context(+ getattr(self, "_request_summary_rail", None),session_id=session_id,- mode=mode,request_id=request.request_id,- channel_id=request.channel_id,- request_metadata=request.metadata,- trusted_dirs=inputs.get("trusted_dirs"),- cwd=inputs.get("cwd"),- project_dir=inputs.get("project_dir"),- supports_user_interaction=inputs.get(- "supports_user_interaction", True- ),- request_system_prompt=self._extract_request_system_prompt(request),)- )-- activate_response = request.params.get("activate_response")- if isinstance(activate_response, dict):- async for chunk in self._auto_harness_service.resume_activate(- session_id, rid, cid, activate_response- ):- yield chunk- return-- resolved_model = self._resolve_model_for_request(request)- if self._auto_harness_service.is_activate_only_request(request, query):- async for chunk in self._auto_harness_service.run_activate_only(- request, session_id, rid, query, model=resolved_model- ):- yield chunk- return- if self._auto_harness_service.is_implement_only_request(request, query):- async for chunk in self._auto_harness_service.run_implement_only(- request, session_id, rid, query, model=resolved_model- ):- yield chunk- return-- async for chunk in self._auto_harness_service.run(- request, session_id, rid, query=query, model=resolved_model- ):- yield chunk+ _LLM_TRACE_SESSION_ID.reset(token_trace_sid)+ _LLM_TRACE_REQUEST_ID.reset(token_trace_rid)+ _LLM_TRACE_ITERATION.reset(token_trace_iter)+ _LLM_TRACE_MODEL_NAME.reset(token_trace_model)return# 拦截斜杠命令 / 结构化 command.goal@@ -9805,9 +9906,37 @@ class JiuWenSwarmDeepAdapter:emitted_ask_user_request_ids.add(request_id)return False+ first_byte_marked = False+ first_answer_marked = False++ def _mark_first_byte_once() -> None:+ nonlocal first_byte_marked+ if first_byte_marked:+ return+ first_byte_marked = True+ mark_request_first_byte()++ def _mark_first_answer_once() -> None:+ nonlocal first_answer_marked+ if first_answer_marked:+ return+ first_answer_marked = True+ mark_request_first_answer()+def note_chat_payload(payload: dict[str, Any]) -> dict[str, Any]:nonlocal had_assistant_output, emitted_terminal_chat_finalevent_type = payload.get("event_type")+ # first_byte: first history-visible assistant event (matches history.jsonl).+ if event_type in (+ "chat.delta",+ "chat.final",+ "chat.tool_call",+ "chat.reasoning",+ ):+ _mark_first_byte_once()+ # first_answer: first answer token only.+ if event_type in ("chat.delta", "chat.final"):+ _mark_first_answer_once()if event_type in ("chat.delta", "chat.reasoning", "chat.final"):had_assistant_output = Trueif event_type == "chat.final":@@ -9851,6 +9980,14 @@ class JiuWenSwarmDeepAdapter:_debug_trace_token = None # reset token for the ContextVar-bound loggerinteraction_stream = Noneinteraction_stream_abort = True+ set_perf_summary_context(+ getattr(self, "_request_summary_rail", None),+ channel_id=request.channel_id or "",+ session_id=request.session_id or "",+ request_id=request.request_id or "",+ mode=mode,+ )+ perf_summary_status = "ok"try:await self._update_runtime_config(self._RuntimeConfig(@@ -10471,6 +10608,7 @@ class JiuWenSwarmDeepAdapter:_debug_logger.end_run(status="ok")interaction_stream_abort = Falseexcept asyncio.CancelledError:+ perf_summary_status = "cancelled"stream_consumer_cancelled = Truelogger.info("[JiuWenSwarmDeepAdapter] 流式任务被取消: request_id=%s session_id=%s",@@ -10487,6 +10625,7 @@ class JiuWenSwarmDeepAdapter:_debug_logger.end_run(status="cancelled")raiseexcept Exception as exc:+ perf_summary_status = "error"logger.exception("[JiuWenSwarmDeepAdapter] 流式任务异常: %s", exc)if _debug_logger is not None:_debug_logger.end_run(status="error", error=exc)@@ -10541,6 +10680,12 @@ class JiuWenSwarmDeepAdapter:session_id,cleanup_rail=True,)+ finalize_perf_summary_request(request.request_id, status=perf_summary_status)+ clear_perf_summary_context(+ getattr(self, "_request_summary_rail", None),+ session_id=session_id,+ request_id=request.request_id,+ )if overlay_token is not None:reset_task_env_overlay(overlay_token)await self._maybe_apply_pending_reload()diff --git a/tests/unit_tests/perf/conftest.py b/tests/unit_tests/perf/conftest.pynew file mode 100644index 0000000000..c9af089184--- /dev/null+++ b/tests/unit_tests/perf/conftest.py@@ -0,0 +1,30 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from dataclasses import replace++import pytest++from jiuwenswarm.perf.config import get_perf_summary_config, init_perf_summary_config++[email protected](autouse=True)+def _enable_perf_summary_for_tests(monkeypatch: pytest.MonkeyPatch) -> None:+ """Tests assume perf summary collection is enabled unless they override config."""+ init_perf_summary_config()+ enabled_cfg = replace(get_perf_summary_config(), enabled=True)+ for target in (+ "jiuwenswarm.perf.config.get_perf_summary_config",+ "jiuwenswarm.perf.collector.get_perf_summary_config",+ "jiuwenswarm.perf.task_hooks.get_perf_summary_config",+ "jiuwenswarm.perf.todo_tracker.get_perf_summary_config",+ "jiuwenswarm.perf.interface_hooks.get_perf_summary_config",+ "jiuwenswarm.perf.subagent_hooks.get_perf_summary_config",+ "jiuwenswarm.perf.request_summary_rail.get_perf_summary_config",+ ):+ try:+ monkeypatch.setattr(target, lambda _cfg=enabled_cfg: _cfg)+ except Exception:+ # Optional modules may pull heavy agent-core deps unavailable in CI envs.+ continuediff --git a/tests/unit_tests/perf/test_interface_deep_perf_wiring.py b/tests/unit_tests/perf/test_interface_deep_perf_wiring.pynew file mode 100644index 0000000000..beb62f8d10--- /dev/null+++ b/tests/unit_tests/perf/test_interface_deep_perf_wiring.py@@ -0,0 +1,78 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Regression: DeepAdapter must wire RequestSummaryRail request boundaries."""++from __future__ import annotations++import ast+from pathlib import Path+++_ROOT = Path(__file__).resolve().parents[3]+_DEEP = _ROOT / "jiuwenswarm" / "server" / "runtime" / "agent_adapter" / "interface_deep.py"+_CODE = _ROOT / "jiuwenswarm" / "server" / "runtime" / "agent_adapter" / "interface_code.py"+_CONFIG_YAML = _ROOT / "jiuwenswarm" / "resources" / "config.yaml"+++def test_interface_deep_wires_request_summary_rail() -> None:+ src = _DEEP.read_text(encoding="utf-8")+ required = (+ "from jiuwenswarm.perf.interface_hooks import",+ "set_perf_summary_context",+ "finalize_perf_summary_request",+ "clear_perf_summary_context",+ "mark_request_first_byte",+ "mark_request_first_answer",+ "maybe_mark_answer_first_byte",+ "def _build_request_summary_rail",+ 'RequestSummaryRail(record_only=True)',+ '_RailBuildInfo("_request_summary_rail"',+ "self._request_summary_rail",+ "def _mark_first_byte_once",+ "def _mark_first_answer_once",+ 'perf_summary_status = "ok"',+ 'perf_summary_status = "cancelled"',+ 'perf_summary_status = "error"',+ 'mode in ("team", "team.plan", "code.team")',+ 'mode == "auto_harness"',+ )+ missing = [item for item in required if item not in src]+ assert not missing, f"interface_deep missing perf wiring: {missing}"+++def test_rail_builders_keep_staticmethod() -> None:+ """Regression: inserting a builder must not steal @staticmethod from the next method."""+ tree = ast.parse(_DEEP.read_text(encoding="utf-8"))+ wanted = {+ "_build_request_summary_rail",+ "_build_multimodal_image_rail",+ "_build_task_execution_rail",+ }+ found: dict[str, bool] = {}++ class _Visitor(ast.NodeVisitor):+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:+ if node.name in wanted:+ found[node.name] = any(+ isinstance(d, ast.Name) and d.id == "staticmethod"+ for d in node.decorator_list+ )+ self.generic_visit(node)++ _Visitor().visit(tree)+ assert found == {name: True for name in wanted}+++def test_interface_code_includes_request_summary_rail() -> None:+ src = _CODE.read_text(encoding="utf-8")+ assert '_RailBuildInfo("_request_summary_rail"' in src+ assert '"RequestSummaryRail"' in src+++def test_perf_summary_enabled_by_default_in_resources_config() -> None:+ text = _CONFIG_YAML.read_text(encoding="utf-8")+ # Narrow to the perf.summary block rather than any other enabled: true.+ idx = text.find("perf:\n summary:")+ assert idx >= 0+ block = text[idx : idx + 120]+ assert "enabled: true" in blockdiff --git a/tests/unit_tests/perf/test_request_summary.py b/tests/unit_tests/perf/test_request_summary.pynew file mode 100644index 0000000000..fff0d13317--- /dev/null+++ b/tests/unit_tests/perf/test_request_summary.py@@ -0,0 +1,658 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import json+import time+from pathlib import Path++import pytest++from jiuwenswarm.perf.accumulator import RequestMeta, RequestSummaryAccumulator+from jiuwenswarm.perf.collector import PerfCollector+from jiuwenswarm.perf.config import init_perf_summary_config+from jiuwenswarm.perf.events import LlmPerfEvent, TaskPerfEvent, ToolPerfEvent+from jiuwenswarm.perf.extract import tool_status_from_result+from jiuwenswarm.perf.stats import ms_to_s, percentile_s+from jiuwenswarm.perf.writer import append_request_summary, request_summaries_file+++def test_request_summary_rail_imports_required_symbols() -> None:+ """Regression: ensure request_summary_rail imports all runtime dependencies."""+ import ast++ src = Path(__file__).resolve().parents[3] / "jiuwenswarm" / "perf" / "request_summary_rail.py"+ tree = ast.parse(src.read_text(encoding="utf-8"))+ imported: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom) and node.module and node.module.startswith("jiuwenswarm.perf"):+ for alias in node.names:+ imported.add(alias.name)+ for required in ("get_perf_collector", "get_perf_summary_config"):+ assert required in imported, f"missing import: {required}"+++def test_tool_status_uses_success_and_status_fields() -> None:+ assert tool_status_from_result({"success": True, "result": "done"}) == "ok"+ assert tool_status_from_result({"success": False, "error": "spawn failed"}) == "error"+ assert tool_status_from_result({"status": "ok", "note": "no error occurred"}) == "ok"+ assert tool_status_from_result({"message": "Successfully updated 2 task(s)"}) == "ok"+ assert tool_status_from_result("Successfully created 9 task(s)") == "ok"+ # Regression: Chinese skip text must stay valid UTF-8 success marker.+ assert tool_status_from_result("跳过大纲确认") == "ok"+ assert tool_status_from_result(+ "shell operation execution error, reason: execution timeout after 180 seconds"+ ) == "error"+ assert tool_status_from_result("Traceback (most recent call last):\nValueError") == "error"+++def test_percentile_s_basic() -> None:+ assert percentile_s([10000, 20000, 30000, 40000, 100000], 0.90) == 100.0+ assert percentile_s([5000], 0.99) == 5.0+ assert ms_to_s(1500) == 1.5+++def test_bottleneck_top_n_zero_disables_tracking(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.common.config.get_config",+ lambda: {"perf": {"summary": {"bottleneck_top_n": 0}}},+ )+ from jiuwenswarm.perf.config import load_perf_summary_config++ cfg = load_perf_summary_config()+ assert cfg.bottleneck_top_n == 0+++def test_accumulator_finalize_schema() -> None:+ acc = RequestSummaryAccumulator(+ meta=RequestMeta(+ session_id="sess-1",+ request_id="req-1",+ channel_id="web",+ mode="plan",+ trace_id=None,+ started_at=1000.0,+ ),+ _bottleneck_top_n=3,+ )+ acc.record_llm(+ LlmPerfEvent(+ llm_call_id="llm-1",+ duration_ms=1000.0,+ model="deepseek-chat",+ iteration=1,+ input_tokens=100,+ output_tokens=50,+ status="ok",+ agent_id="main_agent",+ task_id="todo:1",+ )+ )+ acc.record_tool(+ ToolPerfEvent(+ tool_call_id="tool-1",+ name="WebSearch",+ duration_ms=500.0,+ status="ok",+ agent_id="main_agent",+ task_id="todo:1",+ iteration=1,+ )+ )+ summary = acc.finalize(status="ok", ended_at=1002.5)++ assert summary["schema_version"] == 1+ assert summary["meta"]["request_id"] == "req-1"+ assert summary["summary"]["total_s"] == 2.5+ assert summary["summary"]["stats"]["llm"]["count"] == 1+ assert summary["summary"]["stats"]["llm"]["p90_duration_s"] == 1.0+ assert summary["summary"]["stats"]["tool"]["max_s"] == 0.5+ assert summary["summary"]["stats"]["tool"]["list"] == [{"name": "WebSearch", "count": 1}]+ assert "subagent" not in summary["summary"]["stats"]+ assert "by_agent" not in summary["summary"]["stats"]+ assert summary["summary"]["first_answer_latency_s"] == 0.0+ assert "llm_call_id" not in summary["bottleneck"]["llm"][0]+ assert summary["bottleneck"]["tool"][0]["name"] == "WebSearch"+ assert "errors" not in summary+++def test_accumulator_include_by_agent_when_enabled() -> None:+ acc = RequestSummaryAccumulator(+ meta=RequestMeta(+ session_id="sess-1",+ request_id="req-1",+ channel_id="web",+ mode="plan",+ trace_id=None,+ started_at=1000.0,+ ),+ _include_by_agent=True,+ )+ acc.record_llm(+ LlmPerfEvent(+ llm_call_id="llm-1",+ duration_ms=1000.0,+ model="deepseek-chat",+ iteration=1,+ input_tokens=100,+ output_tokens=50,+ status="ok",+ agent_id="main_agent",+ task_id="todo:1",+ )+ )+ summary = acc.finalize(status="ok", ended_at=1001.0)+ assert summary["summary"]["stats"]["by_agent"]["main_agent"]["llm"]["count"] == 1+++def test_accumulator_omits_errors_when_disabled() -> None:+ acc = RequestSummaryAccumulator(+ meta=RequestMeta(+ session_id="sess-1",+ request_id="req-1",+ channel_id="web",+ mode="plan",+ trace_id=None,+ started_at=1000.0,+ ),+ _include_errors=False,+ )+ acc.record_tool(+ ToolPerfEvent(+ tool_call_id="call-err",+ name="bash",+ duration_ms=100.0,+ status="error",+ error_message="command failed",+ )+ )++ summary = acc.finalize(status="ok", ended_at=1001.0)++ assert "errors" not in summary+ assert summary["summary"]["stats"]["tool"]["fail_count"] == 1+++def test_accumulator_merges_subagent_into_total_stats() -> None:+ acc = RequestSummaryAccumulator(+ meta=RequestMeta(+ session_id="sess-1",+ request_id="req-1",+ channel_id="web",+ mode="plan",+ trace_id=None,+ started_at=1000.0,+ ),+ _include_errors=True,+ )+ iteration = 3+ acc.record_tool(+ ToolPerfEvent(+ tool_call_id="call-a",+ name="web_search",+ duration_ms=100.0,+ status="ok",+ iteration=iteration,+ )+ )+ acc.record_tool(+ ToolPerfEvent(+ tool_call_id="call-b",+ name="bash",+ duration_ms=200.0,+ status="error",+ iteration=iteration,+ error_message="command failed",+ agent_id="subagent_abc",+ )+ )+ acc.record_llm(+ LlmPerfEvent(+ llm_call_id="llm-err",+ duration_ms=50.0,+ model="glm",+ iteration=2,+ input_tokens=1,+ output_tokens=0,+ status="error",+ error_message="rate limited",+ agent_id="subagent_abc",+ )+ )++ summary = acc.finalize(status="ok", ended_at=1002.0)+ tool_stats = summary["summary"]["stats"]["tool"]+ llm_stats = summary["summary"]["stats"]["llm"]++ assert "subagent" not in summary["summary"]["stats"]+ assert tool_stats["count"] == 2+ assert tool_stats["round_count"] == 1+ assert tool_stats["list"] == [{"name": "bash", "count": 1}, {"name": "web_search", "count": 1}]+ assert llm_stats["count"] == 1+ assert len(summary["errors"]) == 2+ assert all(err["status"] == "error" for err in summary["errors"])+ assert "call_id" not in summary["errors"][1]+ assert summary["errors"][0]["duration_s"] == 0.2+++def test_parallel_tool_timing_dict() -> None:+ from jiuwenswarm.perf.context import pop_tool_start, set_tool_start++ set_tool_start("call-1", "tool_a", 10.0)+ set_tool_start("call-2", "tool_b", 20.0)+ first = pop_tool_start("call-1")+ second = pop_tool_start("call-2")+ assert first == ("tool_a", 10.0)+ assert second == ("tool_b", 20.0)+++def test_parallel_tool_timing_no_false_anon_match() -> None:+ from jiuwenswarm.perf.context import pop_tool_start, set_tool_start++ set_tool_start("", "bash", 10.0)+ set_tool_start("", "bash", 20.0)+ assert pop_tool_start("", "bash") is None++ set_tool_start("call-1", "tool_a", 10.0)+ set_tool_start("call-2", "tool_b", 20.0)+ assert pop_tool_start("", "tool_a") is None+++def test_request_summary_rail_supports_record_only() -> None:+ """DeepAdapter rail wiring is deferred; package API must support record_only."""+ from jiuwenswarm.perf.request_summary_rail import RequestSummaryRail++ rail = RequestSummaryRail(record_only=True)+ assert rail._record_only is True+++def test_extract_react_iteration_from_inputs() -> None:+ from types import SimpleNamespace++ from jiuwenswarm.perf.context import increment_react_iteration, reset_react_iteration+ from jiuwenswarm.perf.extract import extract_react_iteration++ reset_react_iteration()+ increment_react_iteration()+ increment_react_iteration()+ assert extract_react_iteration(SimpleNamespace(inputs=None)) == 2++ reset_react_iteration()+ ctx = SimpleNamespace(inputs=SimpleNamespace(iteration=3))+ assert extract_react_iteration(ctx) == 3+ assert extract_react_iteration(SimpleNamespace(inputs={"step": 5})) == 5+++def test_extract_agent_id_prefers_subagent_and_card() -> None:+ from types import SimpleNamespace++ from jiuwenswarm.perf.extract import extract_agent_id++ card = SimpleNamespace(id="spawn_researcher", name="spawn_researcher")+ deep = SimpleNamespace(card=card)+ inner = SimpleNamespace(id="262923614bdb45709ece791ffb3d3409", card=None)++ assert extract_agent_id(inner, deep_agent=deep) == "spawn_researcher"+ assert extract_agent_id(inner, deep_agent=None) == ""+++def test_extract_agent_id_prefers_deep_agent_over_contextvar(monkeypatch: pytest.MonkeyPatch) -> None:+ from types import SimpleNamespace++ from jiuwenswarm.perf.extract import extract_agent_id++ monkeypatch.setattr(+ "jiuwenswarm.perf.extract.resolve_subagent_id",+ lambda: "general-purpose",+ )+ parent = SimpleNamespace(card=SimpleNamespace(id="jiuwenswarm", name="jiuwenswarm"))+ assert extract_agent_id(None, deep_agent=parent) == "jiuwenswarm"+++def test_get_request_context_returns_none_without_binding() -> None:+ from jiuwenswarm.perf.context import clear_request_context, get_request_context++ clear_request_context()+ assert get_request_context() is None+++def test_accumulator_record_task_with_attributed_stats() -> None:+ acc = RequestSummaryAccumulator(+ meta=RequestMeta(+ session_id="sess-1",+ request_id="req-1",+ channel_id="web",+ mode="plan",+ trace_id=None,+ started_at=1000.0,+ ),+ )+ task_id = "todo:abc"+ acc.record_llm(+ LlmPerfEvent(+ llm_call_id="llm-1",+ duration_ms=100.0,+ model="glm",+ iteration=1,+ input_tokens=10,+ output_tokens=5,+ status="ok",+ task_id=task_id,+ )+ )+ acc.record_tool(+ ToolPerfEvent(+ tool_call_id="call-1",+ name="web_search",+ duration_ms=50.0,+ status="ok",+ task_id=task_id,+ )+ )+ acc.record_task(+ TaskPerfEvent(+ task_id=task_id,+ task_content="Stage 1",+ source="todo",+ started_at=1000.0,+ ended_at=1001.0,+ duration_ms=1000.0,+ status="succeeded",+ )+ )++ summary = acc.finalize(status="ok", ended_at=1002.0)+ assert summary["summary"]["stats"]["task"]["count"] == 1+ assert summary["summary"]["stats"]["unattributed_s"] == 0.0+ assert summary["tasks"][0]["stats"]["llm"]["count"] == 1+ assert summary["tasks"][0]["duration_s"] == 1.0+++def test_collector_restores_accumulator_on_write_failure(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ init_perf_summary_config()+ collector = PerfCollector()+ collector.begin_request(+ session_id="sess-z",+ request_id="req-z",+ channel_id="web",+ mode="agent.plan",+ started_at=1000.0,+ )++ write_attempts = {"count": 0}++ def _append_once_fail(*_args, **_kwargs) -> None:+ write_attempts["count"] += 1+ if write_attempts["count"] == 1:+ raise OSError("disk full")++ monkeypatch.setattr("jiuwenswarm.perf.collector.append_request_summary", _append_once_fail)+ monkeypatch.setattr("jiuwenswarm.perf.guard.logger.warning", lambda *_a, **_k: None)+ collector.finalize_request("req-z", status="ok", ended_at=1001.0)++ restored = collector.get_accumulator("req-z")+ assert restored is not None+ assert restored.flushed is False++ collector.finalize_request("req-z", status="ok", ended_at=1001.0)+ assert write_attempts["count"] == 2+ assert collector.get_accumulator("req-z") is None+++def test_collector_does_not_prune_active_long_running_request() -> None:+ init_perf_summary_config()+ collector = PerfCollector()+ stale_started_at = time.time() - PerfCollector._STALE_ORPHAN_AGE_S - 60.0++ collector.begin_request(+ session_id="sess-long",+ request_id="req-long",+ channel_id="web",+ mode="agent.plan",+ started_at=stale_started_at,+ )+ collector.record_llm(+ "req-long",+ LlmPerfEvent(+ llm_call_id="llm-long",+ duration_ms=100.0,+ model="gpt-4",+ iteration=1,+ input_tokens=1,+ output_tokens=1,+ status="ok",+ ),+ )++ collector.begin_request(+ session_id="sess-other",+ request_id="req-other",+ channel_id="web",+ mode="agent.plan",+ )++ assert collector.get_accumulator("req-long") is not None+ assert "req-long" in collector._active_request_ids++ summary = collector.get_accumulator("req-long").finalize(status="ok")+ assert summary["summary"]["stats"]["llm"]["count"] == 1+++def test_collector_prunes_inactive_orphan_accumulator(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ init_perf_summary_config()+ collector = PerfCollector()+ stale_started_at = time.time() - PerfCollector._STALE_ORPHAN_AGE_S - 60.0+ monkeypatch.setattr("jiuwenswarm.perf.collector.logger.warning", lambda *_a, **_k: None)++ collector.begin_request(+ session_id="sess-orphan",+ request_id="req-orphan",+ channel_id="web",+ mode="agent.plan",+ started_at=stale_started_at,+ )+ collector._active_request_ids.discard("req-orphan")++ collector.begin_request(+ session_id="sess-trigger",+ request_id="req-trigger",+ channel_id="web",+ mode="agent.plan",+ )++ assert collector.get_accumulator("req-orphan") is None+ assert collector.get_accumulator("req-trigger") is not None+++def test_collector_finalize_writes_jsonl(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ init_perf_summary_config()+ monkeypatch.setattr(+ "jiuwenswarm.perf.writer.get_agent_sessions_dir",+ lambda: tmp_path,+ )++ collector = PerfCollector()+ collector.begin_request(+ session_id="sess-x",+ request_id="req-x",+ channel_id="web",+ mode="agent.plan",+ started_at=1000.0,+ )+ collector.record_llm(+ "req-x",+ LlmPerfEvent(+ llm_call_id="llm-x",+ duration_ms=800.0,+ model="gpt-4",+ iteration=1,+ input_tokens=10,+ output_tokens=5,+ status="ok",+ ),+ )+ collector.finalize_request("req-x", status="ok", ended_at=1001.0)+ from jiuwenswarm.perf.writer import flush_request_summary_writer++ flush_request_summary_writer()++ out_path = request_summaries_file("sess-x", str(tmp_path))+ assert out_path.exists()+ payload = json.loads(out_path.read_text(encoding="utf-8").strip())+ assert payload["schema_version"] == 1+ assert payload["summary"]["stats"]["llm"]["total_s"] == 0.8+++def test_collector_finalize_writes_tenant_jsonl(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ init_perf_summary_config()+ monkeypatch.setattr(+ "jiuwenswarm.perf.writer.get_agent_sessions_dir",+ lambda: tmp_path,+ )++ collector = PerfCollector()+ collector.begin_request(+ session_id="sess-office",+ request_id="req-office",+ channel_id="officeclaw",+ mode="agent.plan",+ started_at=1000.0,+ service_id="default",+ agent_id="office",+ )+ collector.finalize_request("req-office", status="ok", ended_at=1001.0)+ from jiuwenswarm.perf.writer import flush_request_summary_writer++ flush_request_summary_writer()++ out_path = tmp_path / "sess-office" / "request_summaries.jsonl"+ assert out_path.exists()+ payload = json.loads(out_path.read_text(encoding="utf-8").strip())+ assert payload["meta"]["request_id"] == "req-office"+++def test_append_request_summary_sync_fallback(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.perf.writer.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ append_request_summary("sess-y", {"schema_version": 5, "meta": {"request_id": "req-y"}})+ from jiuwenswarm.perf.writer import flush_request_summary_writer++ flush_request_summary_writer()+ out_path = request_summaries_file("sess-y", str(tmp_path))+ assert "req-y" in out_path.read_text(encoding="utf-8")+++def test_set_perf_summary_context_works_without_rail() -> None:+ """Rail build failure must not skip begin_request / ContextVar bind."""+ from jiuwenswarm.perf.collector import get_perf_collector+ from jiuwenswarm.perf.context import clear_request_context, get_request_context+ from jiuwenswarm.perf.interface_hooks import (+ clear_perf_summary_context,+ finalize_perf_summary_request,+ set_perf_summary_context,+ )++ clear_request_context()+ set_perf_summary_context(+ None,+ channel_id="web",+ session_id="sess-rail-none",+ request_id="req-rail-none",+ mode="agent",+ )+ assert get_request_context() is not None+ assert get_perf_collector().get_accumulator("req-rail-none") is not None+ finalize_perf_summary_request("req-rail-none", status="ok")+ clear_perf_summary_context()+ assert get_request_context() is None+++def test_maybe_mark_first_byte_and_first_answer() -> None:+ from jiuwenswarm.perf.collector import get_perf_collector+ from jiuwenswarm.perf.context import clear_request_context, set_request_context+ from jiuwenswarm.perf.interface_hooks import maybe_mark_answer_first_byte++ clear_request_context()+ set_request_context(+ session_id="sess-fb",+ request_id="req-fb",+ channel_id="web",+ mode="agent",+ )+ acc = get_perf_collector().get_accumulator("req-fb")+ assert acc is not None++ maybe_mark_answer_first_byte({"event_type": "chat.tool_call", "tool_call": {}})+ assert acc.first_byte_latency_ms is not None+ assert acc.first_answer_latency_ms is None++ maybe_mark_answer_first_byte({"event_type": "chat.delta", "content": "hi"})+ assert acc.first_answer_latency_ms is not None+ clear_request_context()+++def test_load_perf_summary_config_defaults_enabled(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("PERF_SUMMARY_ENABLED", raising=False)+ monkeypatch.setattr("jiuwenswarm.common.config.get_config", lambda: {})+ from jiuwenswarm.perf import config as perf_config++ perf_config._CONFIG = None+ cfg = perf_config.load_perf_summary_config()+ assert cfg.enabled is True+++def test_request_context_survives_without_contextvar() -> None:+ """Interaction-round Tasks do not inherit stream-handler ContextVar."""+ from contextvars import Context++ from jiuwenswarm.perf.context import (+ clear_request_context,+ get_request_context,+ normalize_session_key,+ set_request_context,+ )+ from jiuwenswarm.perf.request_summary_rail import RequestSummaryRail++ clear_request_context()+ set_request_context(+ session_id="web_parent",+ request_id="req-cross-task",+ channel_id="web",+ mode="agent",+ )+ rail = RequestSummaryRail(record_only=True)+ rail.bind_request_context(get_request_context())++ class _Session:+ def get_session_id(self) -> str:+ return "web_parent_sub_explore_abcd"++ class _Cb:+ session = _Session()++ def _via_rail_bind() -> str | None:+ # Empty Context: no task-local ContextVar.+ assert get_request_context() is None+ ctx = rail._active_request_context(_Cb())+ assert ctx is not None+ return str(ctx["request_id"])++ def _via_session_registry() -> str | None:+ assert get_request_context() is None+ unbound = RequestSummaryRail(record_only=True)+ ctx = unbound._active_request_context(_Cb())+ assert ctx is not None+ assert normalize_session_key("web_parent_sub_explore_abcd") == "web_parent"+ return str(ctx["request_id"])++ assert Context().run(_via_rail_bind) == "req-cross-task"+ assert Context().run(_via_session_registry) == "req-cross-task"+ clear_request_context(session_id="web_parent", request_id="req-cross-task")+ rail.clear_bound_request_context()+ assert get_request_context(session_id="web_parent") is Nonediff --git a/tests/unit_tests/perf/test_subagent_hooks.py b/tests/unit_tests/perf/test_subagent_hooks.pynew file mode 100644index 0000000000..afd3a585e5--- /dev/null+++ b/tests/unit_tests/perf/test_subagent_hooks.py@@ -0,0 +1,124 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for create_subagent RequestSummaryRail attachment."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from jiuwenswarm.perf.config import PerfSummaryConfig+from jiuwenswarm.perf import subagent_hooks+++class RequestSummaryRail:+ """Stand-in matching the real class name for idempotency checks."""++ def __init__(self, *, record_only: bool = False) -> None:+ self.record_only = record_only+++class _FakeSubagent:+ def __init__(self, *, rails: list | None = None) -> None:+ self._rails = list(rails or [])+ self.card = SimpleNamespace(id="sub-1")+ self.add_rail_calls: list[object] = []++ def configured_rails(self) -> list:+ return list(self._rails)++ def add_rail(self, rail: object) -> None:+ self.add_rail_calls.append(rail)+ self._rails.append(rail)++[email protected](autouse=True)+def _stub_request_summary_rail(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(+ "jiuwenswarm.perf.request_summary_rail.RequestSummaryRail",+ RequestSummaryRail,+ )+++def test_attach_request_summary_rail_when_enabled(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ subagent_hooks,+ "get_perf_summary_config",+ lambda: PerfSummaryConfig(enabled=True),+ )+ sub = _FakeSubagent()+ assert subagent_hooks.attach_request_summary_rail(sub) is True+ assert len(sub.add_rail_calls) == 1+ assert getattr(sub.add_rail_calls[0], "record_only", None) is True+++def test_attach_skips_when_disabled(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ subagent_hooks,+ "get_perf_summary_config",+ lambda: PerfSummaryConfig(enabled=False),+ )+ sub = _FakeSubagent()+ assert subagent_hooks.attach_request_summary_rail(sub) is False+ assert sub.add_rail_calls == []+++def test_attach_is_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ subagent_hooks,+ "get_perf_summary_config",+ lambda: PerfSummaryConfig(enabled=True),+ )+ existing = RequestSummaryRail(record_only=True)+ sub = _FakeSubagent(rails=[existing])+ assert subagent_hooks.attach_request_summary_rail(sub) is False+ assert sub.add_rail_calls == []+++def test_apply_create_subagent_perf_patch(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(subagent_hooks, "_PATCH_APPLIED", False)+ monkeypatch.setattr(+ subagent_hooks,+ "get_perf_summary_config",+ lambda: PerfSummaryConfig(enabled=True),+ )++ class _DeepAgent:+ perf_summary_subagent_patch_applied = False++ def create_subagent(self, subagent_type: str, subsession_id: str):+ return _FakeSubagent()++ fake_mod = SimpleNamespace(DeepAgent=_DeepAgent)+ monkeypatch.setitem(+ __import__("sys").modules,+ "openjiuwen.harness.deep_agent",+ fake_mod,+ )++ subagent_hooks.apply_create_subagent_perf_patch()+ assert _DeepAgent.perf_summary_subagent_patch_applied is True++ parent = _DeepAgent()+ sub = parent.create_subagent("general-purpose", "sess_sub")+ assert len(sub.add_rail_calls) == 1+ assert getattr(sub.add_rail_calls[0], "record_only", None) is True++ # Second apply is a no-op.+ subagent_hooks.apply_create_subagent_perf_patch()+++def test_install_perf_hooks_applies_patch(monkeypatch: pytest.MonkeyPatch) -> None:+ applied = {"ok": False}+ # install_hooks binds apply_create_subagent_perf_patch at import time;+ # patch the name used by that module, not subagent_hooks.+ import jiuwenswarm.perf.install_hooks as install_hooks_mod++ monkeypatch.setattr(+ install_hooks_mod,+ "apply_create_subagent_perf_patch",+ lambda: applied.__setitem__("ok", True),+ )+ install_hooks_mod.install_perf_hooks()+ assert applied["ok"] is Truediff --git a/tests/unit_tests/perf/test_task_hooks.py b/tests/unit_tests/perf/test_task_hooks.pynew file mode 100644index 0000000000..36a4438f09--- /dev/null+++ b/tests/unit_tests/perf/test_task_hooks.py@@ -0,0 +1,34 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from jiuwenswarm.perf.collector import get_perf_collector+from jiuwenswarm.perf.config import init_perf_summary_config+from jiuwenswarm.perf.context import set_request_context+from jiuwenswarm.perf.task_hooks import notify_task_complete+++def test_notify_task_complete_records_task() -> None:+ init_perf_summary_config()+ set_request_context(+ session_id="sess-1",+ request_id="req-task",+ channel_id="web",+ mode="agent.plan",+ )++ notify_task_complete(+ task_id="todo:1",+ task_content="Do work",+ source="todo",+ started_at=1000.0,+ ended_at=1005.0,+ duration_ms=5000.0,+ status="succeeded",+ request_id="req-task",+ )++ acc = get_perf_collector().get_accumulator("req-task")+ assert acc is not None+ assert acc.task_count == 1+ assert acc.tasks[0]["task_content"] == "Do work"diff --git a/tests/unit_tests/perf/test_todo_tracker.py b/tests/unit_tests/perf/test_todo_tracker.pynew file mode 100644index 0000000000..927dfe040b--- /dev/null+++ b/tests/unit_tests/perf/test_todo_tracker.py@@ -0,0 +1,189 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from jiuwenswarm.perf.collector import get_perf_collector+from jiuwenswarm.perf.config import init_perf_summary_config+from jiuwenswarm.perf.context import clear_request_context, set_request_context+from jiuwenswarm.perf.todo_tracker import (+ clear_todo_tracker,+ sync_main_agent_todos,+ todos_from_items,+)+++def _reset(request_id: str = "req-todo") -> None:+ init_perf_summary_config()+ clear_todo_tracker(request_id)+ clear_request_context(request_id=request_id)+ set_request_context(+ session_id="sess-main",+ request_id=request_id,+ channel_id="web",+ mode="agent",+ )+++def test_sync_records_completed_main_todos_with_duration() -> None:+ _reset()++ sync_main_agent_todos(+ [+ {"id": "research", "content": "调研报告", "status": "in_progress"},+ {"id": "build", "content": "生成PPTX", "status": "pending"},+ ],+ request_id="req-todo",+ now=1000.0,+ )+ sync_main_agent_todos(+ [+ {"id": "research", "content": "调研报告", "status": "completed"},+ {"id": "build", "content": "生成PPTX", "status": "in_progress"},+ ],+ request_id="req-todo",+ now=1010.0,+ )+ sync_main_agent_todos(+ [+ {"id": "research", "content": "调研报告", "status": "completed"},+ {"id": "build", "content": "生成PPTX", "status": "completed"},+ ],+ request_id="req-todo",+ now=1025.0,+ )++ acc = get_perf_collector().get_accumulator("req-todo")+ assert acc is not None+ assert acc.task_count == 2+ assert [t["task_content"] for t in acc.tasks] == ["调研报告", "生成PPTX"]+ assert acc.tasks[0]["task_id"] == "todo:research"+ assert acc.tasks[0]["duration_s"] == 10.0+ assert acc.tasks[1]["duration_s"] == 15.0+ assert acc.tasks[0]["source"] == "todo"+++def test_sync_is_idempotent_and_handles_pending_to_completed() -> None:+ _reset("req-todo-2")++ sync_main_agent_todos(+ [{"id": "a", "content": "一步完成", "status": "pending"}],+ request_id="req-todo-2",+ now=50.0,+ )+ sync_main_agent_todos(+ [{"id": "a", "content": "一步完成", "status": "completed"}],+ request_id="req-todo-2",+ now=55.0,+ )+ # duplicate terminal snapshot must not double-count+ sync_main_agent_todos(+ [{"id": "a", "content": "一步完成", "status": "completed"}],+ request_id="req-todo-2",+ now=60.0,+ )++ acc = get_perf_collector().get_accumulator("req-todo-2")+ assert acc is not None+ assert acc.task_count == 1+ assert acc.tasks[0]["duration_s"] == 5.0+++def test_todos_from_items_normalizes_enum_like_status() -> None:+ class _Status:+ value = "IN_PROGRESS"++ class _Item:+ id = "x"+ content = "c"+ status = _Status()++ assert todos_from_items([_Item()]) == [+ {"id": "x", "content": "c", "status": "in_progress"}+ ]+++def test_prune_stale_todo_trackers() -> None:+ from jiuwenswarm.perf import todo_tracker as tracker++ _reset("req-stale")+ sync_main_agent_todos(+ [{"id": "a", "content": "x", "status": "pending"}],+ request_id="req-stale",+ now=1.0,+ )+ assert tracker.prune_stale_todo_trackers(now=1.0 + tracker._STALE_AGE_S + 1) == 1+ # After prune, completing should treat as first sight (duration ~0).+ sync_main_agent_todos(+ [{"id": "a", "content": "x", "status": "completed"}],+ request_id="req-stale",+ now=9000.0,+ )+ acc = get_perf_collector().get_accumulator("req-stale")+ assert acc is not None+ assert acc.task_count == 1+ assert acc.tasks[0]["duration_s"] == 0.0+++def test_in_progress_todo_binds_active_task_for_llm_tool_stats() -> None:+ from jiuwenswarm.perf.context import get_request_context, resolve_task_id+ from jiuwenswarm.perf.events import LlmPerfEvent, ToolPerfEvent++ _reset("req-bind")+ sync_main_agent_todos(+ [+ {"id": "research", "content": "调研", "status": "in_progress"},+ {"id": "build", "content": "生成", "status": "pending"},+ ],+ request_id="req-bind",+ session_id="sess-main",+ now=100.0,+ )+ req_ctx = get_request_context(session_id="sess-main")+ assert resolve_task_id(request_ctx=req_ctx) == "todo:research"++ collector = get_perf_collector()+ collector.record_llm(+ "req-bind",+ LlmPerfEvent(+ llm_call_id="llm-1",+ duration_ms=1500.0,+ model="m",+ iteration=1,+ input_tokens=10,+ output_tokens=5,+ status="ok",+ task_id=resolve_task_id(request_ctx=req_ctx),+ ),+ )+ collector.record_tool(+ "req-bind",+ ToolPerfEvent(+ tool_call_id="tool-1",+ name="bash",+ duration_ms=2000.0,+ status="ok",+ task_id=resolve_task_id(request_ctx=req_ctx),+ ),+ )++ sync_main_agent_todos(+ [+ {"id": "research", "content": "调研", "status": "completed"},+ {"id": "build", "content": "生成", "status": "in_progress"},+ ],+ request_id="req-bind",+ session_id="sess-main",+ now=110.0,+ )+ req_ctx = get_request_context(session_id="sess-main")+ assert resolve_task_id(request_ctx=req_ctx) == "todo:build"++ acc = collector.get_accumulator("req-bind")+ assert acc is not None+ assert acc.task_count == 1+ task = acc.tasks[0]+ assert task["task_id"] == "todo:research"+ assert task["stats"]["llm"]["count"] == 1+ assert task["stats"]["llm"]["total_s"] == 1.5+ assert task["stats"]["tool"]["count"] == 1+ assert task["stats"]["tool"]["total_s"] == 2.0diff --git a/tests/unit_tests/server/test_app_agentserver_exit_logging.py b/tests/unit_tests/server/test_app_agentserver_exit_logging.pynew file mode 100644index 0000000000..b33effa873--- /dev/null+++ b/tests/unit_tests/server/test_app_agentserver_exit_logging.py@@ -0,0 +1,22 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import jiuwenswarm.server.app_agentserver as app_agentserver+++def test_set_exit_reason_updates_module_state() -> None:+ app_agentserver._set_exit_reason("test_reason")+ assert app_agentserver._EXIT_REASON == "test_reason"+++def test_atexit_log_exit_reason_emits_critical(monkeypatch) -> None:+ messages: list[str] = []++ def _capture(msg: str, *args: object) -> None:+ messages.append(msg % args if args else msg)++ monkeypatch.setattr(app_agentserver.logger, "critical", _capture)+ app_agentserver._set_exit_reason("clean_shutdown")+ app_agentserver._atexit_log_exit_reason()+ assert any("atexit reason=clean_shutdown" in message for message in messages)