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
fix: skill_turbo增加重试机制、挂载思考循环检测rail
renquanjiaeab9d45a620a
diff --git a/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py b/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.pyindex 3d5d1bfca7..08001c79aa 100644--- a/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py@@ -25,6 +25,15 @@ _TRANSIENT_MESSAGE_MARKERS = ("read timeout","connect timeout",)+# Per-call budget lives on ctx.extra so concurrent call_llm/stream_llm that+# share one rail instance (SkillTurbo PPT page gather) cannot steal or reset+# each other's retry counts. Instance attrs are mirrored for observability only.+_RETRY_COUNTS_KEY = "_llm_retry_counts"+_COUNT_ATTRS: dict[str, str] = {+ "repeat": "repeat_retry_count",+ "stream_timeout": "stream_timeout_retry_count",+ "transient_invoke": "transient_invoke_retry_count",+}def _parent_accepts_retry_transient_invoke_errors() -> bool:@@ -45,10 +54,9 @@ class NotifyingLLMRetryRail(LLMRetryRail):self.notify_user_on_retry = notify_user_on_retryself.notify_user_on_exhausted = notify_user_on_exhaustedself.retry_transient_invoke_errors = retry_transient_invoke_errors- self._parent_supports_transient_invoke = _parent_accepts_retry_transient_invoke_errors()parent_kwargs = dict(kwargs)- if self._parent_supports_transient_invoke:+ if _parent_accepts_retry_transient_invoke_errors():parent_kwargs["retry_transient_invoke_errors"] = retry_transient_invoke_errorssuper().__init__(**parent_kwargs)@@ -66,6 +74,32 @@ class NotifyingLLMRetryRail(LLMRetryRail):return Truereturn False+ async def before_invoke(self, ctx: AgentCallbackContext) -> None:+ """Reset per-ctx retry budgets at the start of each call/invoke."""+ ctx.extra[_RETRY_COUNTS_KEY] = {+ "repeat": 0,+ "stream_timeout": 0,+ "transient_invoke": 0,+ }+ await super().before_invoke(ctx)++ def _retry_counts(self, ctx: AgentCallbackContext) -> dict[str, int]:+ counts = ctx.extra.get(_RETRY_COUNTS_KEY)+ if not isinstance(counts, dict):+ counts = {+ "repeat": 0,+ "stream_timeout": 0,+ "transient_invoke": 0,+ }+ ctx.extra[_RETRY_COUNTS_KEY] = counts+ for key in _COUNT_ATTRS:+ raw = counts.get(key, 0)+ try:+ counts[key] = int(raw or 0)+ except (TypeError, ValueError):+ counts[key] = 0+ return counts+async def on_model_exception(self, ctx: AgentCallbackContext) -> None:reason: str | None = Noneif self._is_repeat_exception(ctx.exception):@@ -79,7 +113,7 @@ class NotifyingLLMRetryRail(LLMRetryRail):if reason is None:return- will_retry, attempt, max_attempts, delay = self._peek_retry(reason)+ will_retry, attempt, max_attempts, delay = self._peek_retry(ctx, reason)if will_retry and self.notify_user_on_retry:await self._emit_retry_notification(ctx, reason, attempt, max_attempts, delay)elif not will_retry and self.notify_user_on_exhausted:@@ -88,36 +122,35 @@ class NotifyingLLMRetryRail(LLMRetryRail):self._request_retry_or_reset(ctx, reason)def _request_retry_or_reset(self, ctx: AgentCallbackContext, reason: str) -> None:- if reason == "transient_invoke" and not self._parent_supports_transient_invoke:- if self.transient_invoke_retry_count < self.max_retries:- delay = self.backoff_delay(self.transient_invoke_retry_count)- self.transient_invoke_retry_count += 1- logger.warning(- "[NotifyingLLMRetryRail] retrying model call after transient invoke error "- f"({self.transient_invoke_retry_count}/{self.max_retries}) after {delay:.2f}s backoff: "- f"{ctx.exception!r}"- )- ctx.request_retry(delay_seconds=delay)- else:- self.transient_invoke_retry_count = 0+ counts = self._retry_counts(ctx)+ count = counts.get(reason, 0)+ attr = _COUNT_ATTRS.get(reason)+ if count < self.max_retries:+ delay = self.backoff_delay(count)+ counts[reason] = count + 1+ if attr is not None:+ setattr(self, attr, counts[reason])+ logger.warning(+ "[NotifyingLLMRetryRail] retrying model call after %s "+ "(%d/%d) after %.2fs backoff: %r",+ reason,+ counts[reason],+ self.max_retries,+ delay,+ ctx.exception,+ )+ ctx.request_retry(delay_seconds=delay)return- super()._request_retry_or_reset(ctx, reason)- def _peek_retry(self, reason: str) -> tuple[bool, int, int, float]:+ counts[reason] = 0+ if attr is not None:+ setattr(self, attr, 0)++ def _peek_retry(+ self, ctx: AgentCallbackContext, reason: str+ ) -> tuple[bool, int, int, float]:"""Return ``(will_retry, attempt_number, max_attempts, delay_seconds)``."""- if reason == "repeat":- count = self.repeat_retry_count- if count < self.max_retries:- return True, count + 1, self.max_retries, self.backoff_delay(count)- return False, count, self.max_retries, 0.0-- if reason == "transient_invoke":- count = self.transient_invoke_retry_count- if count < self.max_retries:- return True, count + 1, self.max_retries, self.backoff_delay(count)- return False, count, self.max_retries, 0.0-- count = self.stream_timeout_retry_count+ count = self._retry_counts(ctx).get(reason, 0)if count < self.max_retries:return True, count + 1, self.max_retries, self.backoff_delay(count)return False, count, self.max_retries, 0.0diff --git a/jiuwenswarm/server/runtime/skill_turbo/executor.py b/jiuwenswarm/server/runtime/skill_turbo/executor.pyindex 54ffa4b8dc..ba774ff684 100644--- a/jiuwenswarm/server/runtime/skill_turbo/executor.py+++ b/jiuwenswarm/server/runtime/skill_turbo/executor.py@@ -20,6 +20,7 @@ from contextlib import AbstractAsyncContextManagerfrom contextvars import ContextVarfrom dataclasses import dataclass, fieldfrom pathlib import Path+from types import SimpleNamespacefrom typing import TYPE_CHECKING, Any, AsyncIteratorfrom openjiuwen.core.single_agent import create_agent_session@@ -31,6 +32,7 @@ from openjiuwen.core.single_agent.rail.base import (ToolCallInputs,)+from jiuwenswarm.agents.harness.common.rails.llm_retry_notify_rail import NotifyingLLMRetryRailfrom jiuwenswarm.agents.harness.common.rails.stream_event_rail import JiuSwarmStreamEventRailfrom jiuwenswarm.server.runtime.agent_adapter.llm_io_trace import (begin_tool_trace_event,@@ -475,12 +477,18 @@ class SkillTurboExecutor:# resume 时把用户作答按前端 answers 结构回填给 skill_code。self._ask_user_rail = self._build_ask_user_rail()+ # LLM 重复输出 / 流超时 / 瞬时错误重试(与 DeepAgent 共用 config.yaml execution_guard)。+ # 检测算法在 openjiuwen LLMRetryRail;此处只负责挂载、消费 inspector、以及重试循环。+ self._llm_retry_rail = self._build_llm_retry_rail()+# Rail列表(按优先级排序)self._rails = [self._stream_event_rail]if self._ask_user_rail is not None:self._rails.append(self._ask_user_rail)if permission_rail is not None:self._rails.append(permission_rail)+ if self._llm_retry_rail is not None:+ self._rails.append(self._llm_retry_rail)self._rails.append(self._artifact_rail)# 按优先级排序(priority越小越先执行)@@ -975,6 +983,85 @@ class SkillTurboExecutor:)return None+ @staticmethod+ def _build_llm_retry_rail() -> NotifyingLLMRetryRail | None:+ """构建 NotifyingLLMRetryRail;关闭或构建失败时返回 None。++ 配置与 DeepAgent 一致:``execution_guard.llm_retry_rail``(get_config)。+ """+ try:+ from jiuwenswarm.common.config import get_config++ config_base = get_config()+ guard_cfg = (+ config_base.get("execution_guard", {})+ if isinstance(config_base, dict)+ else {}+ )+ retry_cfg = (+ guard_cfg.get("llm_retry_rail", {})+ if isinstance(guard_cfg, dict)+ else {}+ )+ if retry_cfg.get("enabled", False) is not True:+ logger.info(+ "[SkillTurboExecutor] LLMRetryRail disabled by config"+ )+ return None+ rail = NotifyingLLMRetryRail(+ max_retries=retry_cfg.get("max_retries", 2),+ repeat_min_pattern_chars=retry_cfg.get(+ "repeat_min_pattern_chars", 2+ ),+ repeat_max_pattern_chars=retry_cfg.get(+ "repeat_max_pattern_chars", 64+ ),+ repeat_min_count=retry_cfg.get("repeat_min_count", 6),+ repeat_min_total_chars=retry_cfg.get(+ "repeat_min_total_chars", 160+ ),+ repeat_window_chars=retry_cfg.get("repeat_window_chars", 1024),+ single_char_repeat_count=retry_cfg.get(+ "single_char_repeat_count", 100+ ),+ retry_transient_invoke_errors=retry_cfg.get(+ "retry_transient_invoke_errors", True+ ),+ notify_user_on_retry=retry_cfg.get("notify_user_on_retry", True),+ notify_user_on_exhausted=retry_cfg.get(+ "notify_user_on_exhausted", True+ ),+ )+ logger.info(+ "[SkillTurboExecutor] NotifyingLLMRetryRail create success"+ )+ return rail+ except Exception as exc:+ logger.warning(+ "[SkillTurboExecutor] LLMRetryRail create failed: %s", exc+ )+ return None++ @staticmethod+ async def _run_stream_chunk_inspectors(+ ctx: AgentCallbackContext,+ chunk: Any,+ ) -> None:+ """直接调用 ``ctx.extra['_stream_chunk_inspectors']``(不可走 ``_run_rail_hook``)。++ ``_run_rail_hook`` 会吞掉非 AbortError;inspector 抛出的重复输出异常必须向上传播,+ 才能由 call_llm / stream_llm 的重试循环消费 ``request_retry``。+ """+ inspectors = ctx.extra.get("_stream_chunk_inspectors") or []+ if isinstance(inspectors, dict):+ inspectors = list(inspectors.values())+ for inspector in list(inspectors):+ if not callable(inspector):+ continue+ inspect_result = inspector(ctx, chunk)+ if asyncio.iscoroutine(inspect_result):+ await inspect_result+async def _run_rail_hook(self,hook_name: str,@@ -1878,95 +1965,129 @@ class SkillTurboExecutor:thinking_kwargs = resolve_skill_turbo_thinking_kwargs(thinking, client)+ # 每次 call_llm 独立重置重试计数,避免整份 plan 共享 2 次额度。+ await self._run_rail_hook("before_invoke", ctx)+trace_session_token = self._set_llm_interface_log_session()try:- await self._run_rail_hook('before_model_call', ctx)-- # 使用 Model.invoke() 调用 LLM(受实例级 Semaphore 限流保护)- logger.debug("[SkillTurboExecutor] call_llm max_tokens=%s node=%s", _DEFAULT_LLM_MAX_TOKENS, node_name)- async with self._llm_concurrency_guard():+ while True:+ ctx.consume_retry_request()+ ctx.exception = Nonetry:- response = await client.invoke(- messages,- max_tokens=_DEFAULT_LLM_MAX_TOKENS,- **thinking_kwargs,- )- except Exception as inv_exc:- if thinking_kwargs and is_skill_turbo_thinking_param_error(inv_exc):- logger.warning(- "[SkillTurboExecutor] thinking params rejected, bare retry once: %s",- inv_exc,- )- response = await client.invoke(- messages,- max_tokens=_DEFAULT_LLM_MAX_TOKENS,- )- else:- raise-- # llm_usage 事件注入 source_id- await self._emit_llm_usage(- session,- getattr(response, "usage_metadata", None),- node_name=node_name,- stream_source_id=source_id,- )+ await self._run_rail_hook("before_model_call", ctx)- # AssistantMessage 有两个属性:- # - content: 普通文本内容- # - reasoning_content: 推理过程内容(与 DeepAgent 保持一致)-- # 处理 reasoning_content(推理过程)并注入 source_id- reasoning_content = getattr(response, "reasoning_content", None)- if reasoning_content and session:- payload: dict[str, Any] = {- "content": str(reasoning_content),- "plan_name": self._display_name(node_name),- }- if source_id is not None:- payload[STREAM_SOURCE_ID_FIELD] = source_id- try:- await session.write_stream(- OutputSchema(type="llm_reasoning", index=0, payload=payload)- )- except Exception as e:- logger.warning(- "[SkillTurboExecutor] Failed to send llm_reasoning event: %s",- e,+ # 使用 Model.invoke() 调用 LLM(受实例级 Semaphore 限流保护)+ logger.debug(+ "[SkillTurboExecutor] call_llm max_tokens=%s node=%s",+ _DEFAULT_LLM_MAX_TOKENS,+ node_name,)+ async with self._llm_concurrency_guard():+ try:+ response = await client.invoke(+ messages,+ max_tokens=_DEFAULT_LLM_MAX_TOKENS,+ **thinking_kwargs,+ )+ except Exception as inv_exc:+ if thinking_kwargs and is_skill_turbo_thinking_param_error(+ inv_exc+ ):+ logger.warning(+ "[SkillTurboExecutor] thinking params rejected, "+ "bare retry once: %s",+ inv_exc,+ )+ response = await client.invoke(+ messages,+ max_tokens=_DEFAULT_LLM_MAX_TOKENS,+ )+ else:+ raise- # AssistantMessage.content 是响应文本- result = response.content-- # 处理正文内容并注入 source_id(与 reasoning 保持一致)- if result and session:- output_payload: dict[str, Any] = {- "content": str(result),- "plan_name": self._display_name(node_name),- }- if source_id is not None:- output_payload[STREAM_SOURCE_ID_FIELD] = source_id- try:- await session.write_stream(- OutputSchema(type="llm_output", index=0, payload=output_payload)+ # AssistantMessage 有两个属性:+ # - content: 普通文本内容+ # - reasoning_content: 推理过程内容(与 DeepAgent 保持一致)+ reasoning_content = getattr(response, "reasoning_content", None)+ result = response.content++ # 非流式路径无 chunk 循环:用合成 chunk 跑同一套 inspector(写前端 / 发 usage 之前)。+ # 顺序与 stream_llm 一致:先 inspector,通过后再发 usage,避免失败轮重复用量。+ await self._run_stream_chunk_inspectors(+ ctx,+ SimpleNamespace(+ content=result or "",+ reasoning_content=reasoning_content or "",+ ),)- except Exception as e:- logger.warning(- "[SkillTurboExecutor] Failed to send llm_output event: %s",- e,++ # llm_usage 事件注入 source_id(仅成功通过 inspector 后发送)+ await self._emit_llm_usage(+ session,+ getattr(response, "usage_metadata", None),+ node_name=node_name,+ stream_source_id=source_id,)- # 设置response(供after回调使用)- ctx.inputs.response = result+ # 处理 reasoning_content(推理过程)并注入 source_id+ if reasoning_content and session:+ payload: dict[str, Any] = {+ "content": str(reasoning_content),+ "plan_name": self._display_name(node_name),+ }+ if source_id is not None:+ payload[STREAM_SOURCE_ID_FIELD] = source_id+ try:+ await session.write_stream(+ OutputSchema(+ type="llm_reasoning", index=0, payload=payload+ )+ )+ except Exception as e:+ logger.warning(+ "[SkillTurboExecutor] Failed to send llm_reasoning event: %s",+ e,+ )- return result- except Exception as e:- ctx.exception = e- await self._run_rail_hook('on_model_exception', ctx)- raise+ # 处理正文内容并注入 source_id(与 reasoning 保持一致)+ if result and session:+ output_payload: dict[str, Any] = {+ "content": str(result),+ "plan_name": self._display_name(node_name),+ }+ if source_id is not None:+ output_payload[STREAM_SOURCE_ID_FIELD] = source_id+ try:+ await session.write_stream(+ OutputSchema(+ type="llm_output",+ index=0,+ payload=output_payload,+ )+ )+ except Exception as e:+ logger.warning(+ "[SkillTurboExecutor] Failed to send llm_output event: %s",+ e,+ )++ # 设置response(供after回调使用)+ ctx.inputs.response = result+ return result+ except AbortError:+ raise+ except Exception as e:+ ctx.exception = e+ await self._run_rail_hook("on_model_exception", ctx)+ retry_request = ctx.consume_retry_request()+ if not retry_request:+ raise+ if retry_request.delay_seconds > 0:+ await asyncio.sleep(retry_request.delay_seconds)+ finally:+ await self._run_rail_hook("after_model_call", ctx)finally:self._reset_llm_interface_log_session(trace_session_token)- await self._run_rail_hook('after_model_call', ctx)async def stream_llm(self,@@ -1994,8 +2115,12 @@ class SkillTurboExecutor:str: 流式文本片段(普通文本内容)内部机制:- - reasoning 事件会通过 session stream 实时发送+ - reasoning / 正文事件经 session stream **实时**刷出(与 DeepAgent 对齐;+ 失败轮前端可能留下脏前缀,随后由重试通知 / 成功轮覆盖)- 业务代码只看到普通文本,无需关心 reasoning+ - 重复输出等可重试失败时,本轮已缓冲的业务正文会丢弃并整轮重试;+ 成功轮结束后再向业务 yield,避免 stream_llm_collect 拼到脏前缀+ - llm_usage 仅在成功轮发送,避免失败轮中途 usage 泄漏后成功轮再计一次"""ctx = self._build_model_call_context()session = ctx.session@@ -2027,117 +2152,143 @@ class SkillTurboExecutor:thinking_kwargs = resolve_skill_turbo_thinking_kwargs(thinking, client)- accumulated_message = ""+ # 每次 stream_llm 独立重置重试计数。+ await self._run_rail_hook("before_invoke", ctx)+trace_session_token = self._set_llm_interface_log_session()try:- await self._run_rail_hook('before_model_call', ctx)-- # 使用 Model.stream() 流式调用 LLM- # 流式调用整个生命周期都占用一个 LLM "槽位",因此用 Semaphore 包裹整个流。- async with self._llm_concurrency_guard():- async def _iter_chunks():- try:- async for chunk in client.stream(- messages,- max_tokens=_DEFAULT_LLM_MAX_TOKENS,- **thinking_kwargs,- ):- yield chunk- except Exception as stream_exc:- if thinking_kwargs and is_skill_turbo_thinking_param_error(stream_exc):- logger.warning(- "[SkillTurboExecutor] thinking params rejected, "- "bare retry once: %s",- stream_exc,- )- async for chunk in client.stream(- messages,- max_tokens=_DEFAULT_LLM_MAX_TOKENS,- ):- yield chunk- else:- raise-- async for chunk in _iter_chunks():- # usage_metadata 通常只在最后一个 chunk 有值,避免对每个 chunk 都调用- chunk_usage = getattr(chunk, "usage_metadata", None)- if chunk_usage:- await self._emit_llm_usage(- session,- chunk_usage,- node_name=node_name,- stream_source_id=source_id,- )- # AssistantMessageChunk 有两个属性:- # - content: 普通文本内容- # - reasoning_content: 推理过程内容-- # ──────────────────────── 自动处理 reasoning_content ────────────────────────- # 框架层面自动发送 reasoning 事件,业务代码无需关心- reasoning_content = getattr(chunk, "reasoning_content", None)- if reasoning_content:- if session:- reasoning_payload: dict[str, Any] = {- "content": str(reasoning_content),- "plan_name": self._display_name(node_name),- }- if source_id is not None:- reasoning_payload[STREAM_SOURCE_ID_FIELD] = source_id+ while True:+ ctx.consume_retry_request()+ ctx.exception = None+ accumulated_message = ""+ # 业务侧缓冲:失败轮丢弃,成功轮再 yield,避免 collect 拼到脏前缀。+ buffered_chunks: list[str] = []+ # usage 成功轮才发(与 call_llm 对齐);中途 chunk 可能已带 usage。+ pending_usage: Any = None+ try:+ await self._run_rail_hook("before_model_call", ctx)++ # 使用 Model.stream() 流式调用 LLM+ # 流式调用整个生命周期都占用一个 LLM "槽位",因此用 Semaphore 包裹整个流。+ async with self._llm_concurrency_guard():+ async def _iter_chunks():try:- await session.write_stream(- OutputSchema(- type="llm_reasoning",- index=0,- payload=reasoning_payload,+ async for chunk in client.stream(+ messages,+ max_tokens=_DEFAULT_LLM_MAX_TOKENS,+ **thinking_kwargs,+ ):+ yield chunk+ except Exception as stream_exc:+ if thinking_kwargs and is_skill_turbo_thinking_param_error(+ stream_exc+ ):+ logger.warning(+ "[SkillTurboExecutor] thinking params rejected, "+ "bare retry once: %s",+ stream_exc,)- )- except Exception as e:- logger.warning(- "[SkillTurboExecutor] Failed to send stream llm_reasoning event: %s",- e,- )-- # ──────────────────────── 处理普通文本内容 ────────────────────────- text_chunk = chunk.content- if text_chunk:- # 累积消息(供after回调使用)- accumulated_message += text_chunk-- # 通过 session stream 发送正文 delta(与 reasoning 保持一致)- if session:- output_payload: dict[str, Any] = {- "content": str(text_chunk),- "plan_name": self._display_name(node_name),- }- if source_id is not None:- output_payload[STREAM_SOURCE_ID_FIELD] = source_id- try:- await session.write_stream(- OutputSchema(- type="llm_output",- index=0,- payload=output_payload,+ async for chunk in client.stream(+ messages,+ max_tokens=_DEFAULT_LLM_MAX_TOKENS,+ ):+ yield chunk+ else:+ raise++ async for chunk in _iter_chunks():+ # 先跑 inspector,再刷前端 / 缓冲业务正文。+ await self._run_stream_chunk_inspectors(ctx, chunk)++ # 记下 usage,成功轮再发;避免失败轮中途泄漏后成功轮重复计费。+ chunk_usage = getattr(chunk, "usage_metadata", None)+ if chunk_usage:+ pending_usage = chunk_usage+ # AssistantMessageChunk 有两个属性:+ # - content: 普通文本内容+ # - reasoning_content: 推理过程内容++ # ──────────────────────── 实时刷 reasoning_content ────────────────────────+ reasoning_content = getattr(chunk, "reasoning_content", None)+ if reasoning_content and session:+ reasoning_payload: dict[str, Any] = {+ "content": str(reasoning_content),+ "plan_name": self._display_name(node_name),+ }+ if source_id is not None:+ reasoning_payload[STREAM_SOURCE_ID_FIELD] = source_id+ try:+ await session.write_stream(+ OutputSchema(+ type="llm_reasoning",+ index=0,+ payload=reasoning_payload,+ )+ )+ except Exception as e:+ logger.warning(+ "[SkillTurboExecutor] Failed to send stream "+ "llm_reasoning event: %s",+ e,)- )- except Exception as e:- logger.warning(- "[SkillTurboExecutor] Failed to send stream llm_output event: %s",- e,- )- # 返回普通文本(业务代码只看到普通文本)+ # ──────────────────────── 实时刷前端 + 缓冲业务正文 ────────────────────────+ text_chunk = chunk.content+ if text_chunk:+ # 累积消息(供after回调使用)+ accumulated_message += text_chunk+ # 先缓冲;整轮成功后再 yield,保证重试时业务侧看不到脏前缀+ buffered_chunks.append(str(text_chunk))++ if session:+ output_payload: dict[str, Any] = {+ "content": str(text_chunk),+ "plan_name": self._display_name(node_name),+ }+ if source_id is not None:+ output_payload[STREAM_SOURCE_ID_FIELD] = source_id+ try:+ await session.write_stream(+ OutputSchema(+ type="llm_output",+ index=0,+ payload=output_payload,+ )+ )+ except Exception as e:+ logger.warning(+ "[SkillTurboExecutor] Failed to send stream "+ "llm_output event: %s",+ e,+ )++ # 成功轮:发 usage,再向业务 yield。+ await self._emit_llm_usage(+ session,+ pending_usage,+ node_name=node_name,+ stream_source_id=source_id,+ )++ # 设置response(供after回调使用)+ ctx.inputs.response = accumulated_message+ for text_chunk in buffered_chunks:yield text_chunk-- # 设置response(供after回调使用)- ctx.inputs.response = accumulated_message-- except Exception as e:- ctx.exception = e- await self._run_rail_hook('on_model_exception', ctx)- raise+ return+ except AbortError:+ raise+ except Exception as e:+ ctx.exception = e+ await self._run_rail_hook("on_model_exception", ctx)+ retry_request = ctx.consume_retry_request()+ if not retry_request:+ raise+ if retry_request.delay_seconds > 0:+ await asyncio.sleep(retry_request.delay_seconds)+ finally:+ await self._run_rail_hook("after_model_call", ctx)finally:self._reset_llm_interface_log_session(trace_session_token)- await self._run_rail_hook('after_model_call', ctx)async def fallback(self,diff --git a/jiuwenswarm/server/runtime/skill_turbo/planner.py b/jiuwenswarm/server/runtime/skill_turbo/planner.pyindex 5cd7e3f8f0..a014d8a354 100644--- a/jiuwenswarm/server/runtime/skill_turbo/planner.py+++ b/jiuwenswarm/server/runtime/skill_turbo/planner.py@@ -18,6 +18,7 @@ logger = logging.getLogger(__name__)_SKILL_CODES_PACKAGE = "jiuwenswarm.server.runtime.skill_turbo.skill_codes"_MIN_ROUTE_CONFIDENCE = 0.6+_ROUTE_MAX_ATTEMPTS = 2class PlanGenerationError(Exception):@@ -104,21 +105,33 @@ class SkillTurboPlanner:logger.info("[SkillTurboPlanner] route skills detail: %s", skills_payload)messages = self._build_route_messages(task, context, skills_payload)- try:- # 使用流式调用,避免部分 MaaS 模型(如 maas-glm-5.1-zhipu)- # 非流式路由未注册导致 429 Route missed+ # 路由输出偶发不可解析(推理模型空 content / 非 JSON 文本)属瞬态失败:+ # 重试一次再降级,避免单次采样异常直接放弃整条加速通道。+ # 注意:confidence 不足 / skill_name=null 是模型正常判定,不在此重试范围内。+ route: dict[str, Any] | None = None+ for attempt in range(1, _ROUTE_MAX_ATTEMPTS + 1):collected: list[str] = []- async for chunk in client.stream(messages):- content = getattr(chunk, "content", None)- if content:- collected.append(content)- raw_content = "".join(collected)- route = extract_llm_json(raw_content, expected_type=dict)- except Exception as e:- logger.warning(- "[SkillTurboPlanner] LLM route failed error_type=%s",- type(e).__name__,- )+ try:+ # 使用流式调用:部分模型服务对非流式调用存在路由注册限制,+ # 可能触发 429 Route missed,流式调用可规避+ async for chunk in client.stream(messages):+ content = getattr(chunk, "content", None)+ if content:+ collected.append(content)+ raw_content = "".join(collected)+ route = extract_llm_json(raw_content, expected_type=dict)+ break+ except Exception as e:+ # 记录原始返回前缀,便于区分空 content / 非 JSON 文本两类失败+ logger.warning(+ "[SkillTurboPlanner] LLM route failed attempt=%d/%d error=%s: %s raw_content=%r",+ attempt,+ _ROUTE_MAX_ATTEMPTS,+ type(e).__name__,+ e,+ "".join(collected)[:300],+ )+ if route is None:return Noneskill_name = route.get("skill_name")diff --git a/tests/unit_tests/agents/harness/common/rails/test_llm_retry_notify_rail_ctx.py b/tests/unit_tests/agents/harness/common/rails/test_llm_retry_notify_rail_ctx.pynew file mode 100644index 0000000000..13fbc6723c--- /dev/null+++ b/tests/unit_tests/agents/harness/common/rails/test_llm_retry_notify_rail_ctx.py@@ -0,0 +1,90 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Per-ctx retry budgets for NotifyingLLMRetryRail under concurrent callers."""++from __future__ import annotations++import pytest+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ModelCallInputs++from jiuwenswarm.agents.harness.common.rails.llm_retry_notify_rail import (+ NotifyingLLMRetryRail,+)+++def _ctx() -> AgentCallbackContext:+ return AgentCallbackContext(+ agent=None,+ inputs=ModelCallInputs(messages=[], tools=None, model_context=None),+ context=None,+ extra={},+ )+++def _repeat_exc() -> Exception:+ return Exception("LLM repeated stream output detected: field=content, unit='ab'")+++async def test_concurrent_ctx_keep_independent_retry_budgets():+ """Two concurrent call contexts must not steal each other's max_retries."""+ rail = NotifyingLLMRetryRail(+ max_retries=1,+ backoff_seconds=[0.0],+ notify_user_on_retry=False,+ notify_user_on_exhausted=False,+ )+ ctx_a = _ctx()+ ctx_b = _ctx()+ await rail.before_invoke(ctx_a)+ await rail.before_invoke(ctx_b)++ # A uses its single retry grant.+ ctx_a.exception = _repeat_exc()+ await rail.on_model_exception(ctx_a)+ assert ctx_a.consume_retry_request() is not None++ # A exhausts.+ ctx_a.exception = _repeat_exc()+ await rail.on_model_exception(ctx_a)+ assert ctx_a.consume_retry_request() is None++ # B still has a full independent budget.+ ctx_b.exception = _repeat_exc()+ await rail.on_model_exception(ctx_b)+ assert ctx_b.consume_retry_request() is not None++ ctx_b.exception = _repeat_exc()+ await rail.on_model_exception(ctx_b)+ assert ctx_b.consume_retry_request() is None+++async def test_before_invoke_does_not_reset_sibling_ctx_budget():+ """A later before_invoke on ctx_b must not wipe ctx_a's in-flight count."""+ rail = NotifyingLLMRetryRail(+ max_retries=2,+ backoff_seconds=[0.0, 0.0],+ notify_user_on_retry=False,+ notify_user_on_exhausted=False,+ )+ ctx_a = _ctx()+ await rail.before_invoke(ctx_a)++ ctx_a.exception = _repeat_exc()+ await rail.on_model_exception(ctx_a)+ assert ctx_a.consume_retry_request() is not None++ # Sibling call starts and resets *its own* counters only.+ ctx_b = _ctx()+ await rail.before_invoke(ctx_b)++ # A should still be on attempt budget 1/2 used → one grant left.+ ctx_a.exception = _repeat_exc()+ await rail.on_model_exception(ctx_a)+ assert ctx_a.consume_retry_request() is not None++ # A now exhausted.+ ctx_a.exception = _repeat_exc()+ await rail.on_model_exception(ctx_a)+ assert ctx_a.consume_retry_request() is Nonediff --git a/tests/unit_tests/server/runtime/skill_turbo/test_llm_retry_rail_mount.py b/tests/unit_tests/server/runtime/skill_turbo/test_llm_retry_rail_mount.pynew file mode 100644index 0000000000..925098c970--- /dev/null+++ b/tests/unit_tests/server/runtime/skill_turbo/test_llm_retry_rail_mount.py@@ -0,0 +1,449 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""SkillTurboExecutor mounts NotifyingLLMRetryRail and retries stream/call LLM."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from jiuwenswarm.agents.harness.common.rails.llm_retry_notify_rail import (+ NotifyingLLMRetryRail,+)+from jiuwenswarm.server.runtime.skill_turbo import executor as executor_mod+from jiuwenswarm.server.runtime.skill_turbo.executor import (+ ExecutorConfig,+ SkillTurboExecutor,+)+++def _exact_repeat_text(*, unit: str = "abcdef", times: int = 40) -> str:+ """Adjacent exact repeats that the stock LLMRetryRail algorithm detects."""+ return unit * times+++def _chunk(+ content: str = "",+ reasoning: str = "",+ usage_metadata: object | None = None,+) -> SimpleNamespace:+ return SimpleNamespace(+ content=content,+ reasoning_content=reasoning,+ usage_metadata=usage_metadata,+ )+++def _client_with_stream_outputs(outputs: list[list[str]]) -> tuple[MagicMock, list[int]]:+ """Fake model_client.stream that yields content pieces per call index."""+ call_count = [0]++ async def stream(messages, max_tokens=0, **kwargs):+ idx = call_count[0]+ call_count[0] += 1+ pieces = outputs[min(idx, len(outputs) - 1)]+ for piece in pieces:+ yield _chunk(content=piece)++ client = MagicMock()+ client.stream = stream+ client.invoke = MagicMock(side_effect=AssertionError("invoke not expected"))+ return client, call_count+++def _client_with_stream_chunk_outputs(+ outputs: list[list[SimpleNamespace]],+) -> tuple[MagicMock, list[int]]:+ """Fake model_client.stream that yields full chunk objects per call index."""+ call_count = [0]++ async def stream(messages, max_tokens=0, **kwargs):+ idx = call_count[0]+ call_count[0] += 1+ chunks = outputs[min(idx, len(outputs) - 1)]+ for chunk in chunks:+ yield chunk++ client = MagicMock()+ client.stream = stream+ client.invoke = MagicMock(side_effect=AssertionError("invoke not expected"))+ return client, call_count+++def _client_with_invoke_outputs(outputs: list[SimpleNamespace]) -> tuple[MagicMock, list[int]]:+ call_count = [0]++ async def invoke(messages, max_tokens=0, **kwargs):+ idx = call_count[0]+ call_count[0] += 1+ return outputs[min(idx, len(outputs) - 1)]++ client = MagicMock()+ client.invoke = invoke+ client.stream = MagicMock(side_effect=AssertionError("stream not expected"))+ return client, call_count+++def _env(client: MagicMock) -> MagicMock:+ env = MagicMock()+ env.skill_code_import_prefixes = ("skill_codes",)+ env.config = {}+ env.model_client = client+ env.card = None+ return env+++def _retry_rail(*, max_retries: int = 2) -> NotifyingLLMRetryRail:+ return NotifyingLLMRetryRail(+ max_retries=max_retries,+ backoff_seconds=[0.0, 0.0, 0.0],+ notify_user_on_retry=False,+ notify_user_on_exhausted=False,+ )+++def _make_executor(+ client: MagicMock,+ *,+ rail: NotifyingLLMRetryRail | None,+) -> SkillTurboExecutor:+ with (+ patch.object(SkillTurboExecutor, "_build_permission_rail", return_value=None),+ patch.object(SkillTurboExecutor, "_build_ask_user_rail", return_value=None),+ patch.object(SkillTurboExecutor, "_build_llm_retry_rail", return_value=rail),+ ):+ return SkillTurboExecutor(_env(client), config=ExecutorConfig())+++class TestLlmRetryRailMount:+ def test_rail_appended_when_built(self):+ client, _ = _client_with_stream_outputs([["ok"]])+ rail = _retry_rail()+ ex = _make_executor(client, rail=rail)+ assert rail in ex._rails+ assert ex._llm_retry_rail is rail++ def test_rail_absent_when_build_returns_none(self):+ client, _ = _client_with_stream_outputs([["ok"]])+ ex = _make_executor(client, rail=None)+ assert ex._llm_retry_rail is None+ assert not any(isinstance(r, NotifyingLLMRetryRail) for r in ex._rails)++ def test_build_respects_config_disabled(self):+ client, _ = _client_with_stream_outputs([["ok"]])+ with (+ patch.object(SkillTurboExecutor, "_build_permission_rail", return_value=None),+ patch.object(SkillTurboExecutor, "_build_ask_user_rail", return_value=None),+ patch(+ "jiuwenswarm.common.config.get_config",+ return_value={+ "execution_guard": {"llm_retry_rail": {"enabled": False}},+ },+ ),+ ):+ ex = SkillTurboExecutor(_env(client), config=ExecutorConfig())+ assert ex._llm_retry_rail is None+++class TestStreamLlmRetry:+ @pytest.mark.asyncio+ async def test_retries_exact_repeat_then_returns_clean_body(self):+ dirty = _exact_repeat_text()+ # Stream dirty in small pieces so inspector sees growing window.+ dirty_pieces = [dirty[i : i + 12] for i in range(0, len(dirty), 12)]+ client, calls = _client_with_stream_outputs(+ [dirty_pieces, ["hello world final"]]+ )+ ex = _make_executor(client, rail=_retry_rail())++ parts: list[str] = []+ async for piece in ex.stream_llm("prompt", node_name="t"):+ parts.append(piece)++ assert "".join(parts) == "hello world final"+ assert calls[0] == 2++ @pytest.mark.asyncio+ async def test_failed_attempt_not_yielded_to_caller(self):+ """Failed repeat round must not leak into stream_llm_collect buffer."""+ dirty = _exact_repeat_text()+ dirty_pieces = [dirty[i : i + 16] for i in range(0, len(dirty), 16)]+ client, calls = _client_with_stream_outputs(+ [dirty_pieces, ["only-clean"]]+ )+ ex = _make_executor(client, rail=_retry_rail())++ parts: list[str] = []+ async for piece in ex.stream_llm("prompt", node_name="t"):+ parts.append(piece)++ joined = "".join(parts)+ assert "abcdef" not in joined+ assert joined == "only-clean"+ assert calls[0] == 2++ @pytest.mark.asyncio+ async def test_retry_exhausted_raises(self):+ dirty = _exact_repeat_text()+ dirty_pieces = [dirty[i : i + 12] for i in range(0, len(dirty), 12)]+ # First attempt + 2 retries = 3 identical dirty streams.+ client, calls = _client_with_stream_outputs(+ [dirty_pieces, dirty_pieces, dirty_pieces]+ )+ ex = _make_executor(client, rail=_retry_rail(max_retries=2))++ with pytest.raises(Exception) as ei:+ async for _ in ex.stream_llm("prompt", node_name="t"):+ pass++ assert "LLM repeated stream output detected" in str(ei.value)+ assert calls[0] == 3++ @pytest.mark.asyncio+ async def test_clean_stream_no_retry(self):+ client, calls = _client_with_stream_outputs([["a", "b", "c"]])+ ex = _make_executor(client, rail=_retry_rail())++ parts: list[str] = []+ async for piece in ex.stream_llm("prompt", node_name="t"):+ parts.append(piece)++ assert "".join(parts) == "abc"+ assert calls[0] == 1+++class TestCallLlmRetry:+ @pytest.mark.asyncio+ async def test_retries_exact_repeat_on_invoke(self):+ dirty = _exact_repeat_text()+ client, calls = _client_with_invoke_outputs(+ [+ SimpleNamespace(content=dirty, reasoning_content="", usage_metadata=None),+ SimpleNamespace(+ content="clean-invoke",+ reasoning_content="",+ usage_metadata=None,+ ),+ ]+ )+ ex = _make_executor(client, rail=_retry_rail())++ result = await ex.call_llm("prompt", node_name="t")++ assert result == "clean-invoke"+ assert calls[0] == 2++ @pytest.mark.asyncio+ async def test_failed_attempt_does_not_emit_usage(self):+ """usage must run after inspector so a dirty invoke does not leak usage."""+ dirty = _exact_repeat_text()+ dirty_usage = {"prompt_token_count": 1, "candidates_token_count": 9}+ clean_usage = {"prompt_token_count": 2, "candidates_token_count": 3}+ client, calls = _client_with_invoke_outputs(+ [+ SimpleNamespace(+ content=dirty,+ reasoning_content="",+ usage_metadata=dirty_usage,+ ),+ SimpleNamespace(+ content="clean-invoke",+ reasoning_content="",+ usage_metadata=clean_usage,+ ),+ ]+ )+ ex = _make_executor(client, rail=_retry_rail())++ usage_events: list[object] = []+ session = MagicMock()++ async def write_stream(schema):+ usage_events.append(schema)++ session.write_stream = write_stream+ token = executor_mod._session_var.set(session)+ try:+ with patch.object(+ SkillTurboExecutor,+ "_emit_llm_usage",+ autospec=True,+ ) as emit_usage:+ result = await ex.call_llm("prompt", node_name="t")+ finally:+ executor_mod._session_var.reset(token)++ assert result == "clean-invoke"+ assert calls[0] == 2+ assert emit_usage.await_count == 1+ emitted_usage = emit_usage.await_args.args[2]+ assert emitted_usage == clean_usage++ @pytest.mark.asyncio+ async def test_incrementing_number_pattern_not_detected_by_stock_algo(self):+ """Document known gap: screenshot-style '短句+递增数字' is not exact-suffix.++ Mounting the rail does not change openjiuwen detection; this case must+ still complete without retry so we do not pretend coverage we lack.+ """+ # Mimic UI: 句研究重点方向2142 & 1~3 句研究重点方向2143 & 1~3 ...+ pieces = [+ f"句研究重点方向{n} & 1~3 "+ for n in range(2142, 2142 + 80)+ ]+ text = "".join(pieces)+ client, calls = _client_with_invoke_outputs(+ [+ SimpleNamespace(+ content=text,+ reasoning_content="",+ usage_metadata=None,+ ),+ ]+ )+ ex = _make_executor(client, rail=_retry_rail())++ result = await ex.call_llm("prompt", node_name="t")++ assert result == text+ assert calls[0] == 1+++class TestStreamLlmSplitChannel:+ @pytest.mark.asyncio+ async def test_frontend_realtime_keeps_failed_prefix_business_stays_clean(self):+ """Frontend is realtime (may keep dirty prefix); business yield stays clean."""+ dirty = _exact_repeat_text()+ dirty_pieces = [dirty[i : i + 16] for i in range(0, len(dirty), 16)]+ client, calls = _client_with_stream_outputs(+ [dirty_pieces, ["only-clean"]]+ )+ ex = _make_executor(client, rail=_retry_rail())++ written: list[object] = []+ session = MagicMock()++ async def write_stream(schema):+ written.append(schema)++ session.write_stream = write_stream+ token = executor_mod._session_var.set(session)+ try:+ parts: list[str] = []+ async for piece in ex.stream_llm("prompt", node_name="t"):+ parts.append(piece)+ finally:+ executor_mod._session_var.reset(token)++ # Business channel: only successful round.+ assert "".join(parts) == "only-clean"+ assert calls[0] == 2++ output_text = "".join(+ str(getattr(schema, "payload", {}).get("content", ""))+ for schema in written+ if getattr(schema, "type", None) == "llm_output"+ )+ # Frontend channel: dirty prefix already flushed before retry, then clean.+ assert "abcdef" in output_text+ assert output_text.endswith("only-clean")++ @pytest.mark.asyncio+ async def test_failed_attempt_does_not_emit_usage(self):+ """Mid-stream usage on a dirty round must not leak; only success emits."""+ dirty = _exact_repeat_text()+ dirty_pieces = [dirty[i : i + 16] for i in range(0, len(dirty), 16)]+ dirty_usage = {"prompt_token_count": 1, "candidates_token_count": 9}+ clean_usage = {"prompt_token_count": 2, "candidates_token_count": 3}++ # Attach usage on an early dirty chunk (before inspector trips on later ones).+ dirty_chunks = [+ _chunk(content=piece, usage_metadata=dirty_usage if i == 0 else None)+ for i, piece in enumerate(dirty_pieces)+ ]+ clean_chunks = [_chunk(content="only-clean", usage_metadata=clean_usage)]+ client, calls = _client_with_stream_chunk_outputs(+ [dirty_chunks, clean_chunks]+ )+ ex = _make_executor(client, rail=_retry_rail())++ session = MagicMock()++ async def write_stream(schema):+ return None++ session.write_stream = write_stream+ token = executor_mod._session_var.set(session)+ try:+ with patch.object(+ SkillTurboExecutor,+ "_emit_llm_usage",+ autospec=True,+ ) as emit_usage:+ parts: list[str] = []+ async for piece in ex.stream_llm("prompt", node_name="t"):+ parts.append(piece)+ finally:+ executor_mod._session_var.reset(token)++ assert "".join(parts) == "only-clean"+ assert calls[0] == 2+ assert emit_usage.await_count == 1+ emitted_usage = emit_usage.await_args.args[2]+ assert emitted_usage == clean_usage+++class TestConcurrentStreamLlmRetry:+ @pytest.mark.asyncio+ async def test_shared_rail_two_streams_each_get_full_budget(self):+ """asyncio.gather of two stream_llm must not share instance retry counts."""+ dirty = _exact_repeat_text()+ dirty_pieces = [dirty[i : i + 12] for i in range(0, len(dirty), 12)]++ # Per-call queues: each concurrent stream needs dirty → clean (2 attempts).+ queues: dict[str, list[list[str]]] = {+ "a": [dirty_pieces, ["clean-a"]],+ "b": [dirty_pieces, ["clean-b"]],+ }+ locks = {key: asyncio.Lock() for key in queues}+ call_counts = {"a": 0, "b": 0, "other": 0}++ async def stream(messages, max_tokens=0, **kwargs):+ # Identify caller by last user prompt tag.+ tag = "other"+ for msg in reversed(messages or []):+ content = msg.get("content", "") if isinstance(msg, dict) else ""+ if content.endswith("|a"):+ tag = "a"+ break+ if content.endswith("|b"):+ tag = "b"+ break+ async with locks[tag] if tag in locks else asyncio.Lock():+ idx = call_counts[tag]+ call_counts[tag] = idx + 1+ pieces = queues[tag][min(idx, len(queues[tag]) - 1)]+ for piece in pieces:+ yield _chunk(content=piece)++ client = MagicMock()+ client.stream = stream+ client.invoke = MagicMock(side_effect=AssertionError("invoke not expected"))+ # max_retries=1 → each call can attempt twice. Shared instance counters+ # would let the second stream exhaust after the first used the grant.+ ex = _make_executor(client, rail=_retry_rail(max_retries=1))++ async def run(tag: str) -> str:+ parts: list[str] = []+ async for piece in ex.stream_llm(f"prompt|{tag}", node_name=tag):+ parts.append(piece)+ return "".join(parts)++ out_a, out_b = await asyncio.gather(run("a"), run("b"))+ assert out_a == "clean-a"+ assert out_b == "clean-b"+ assert call_counts["a"] == 2+ assert call_counts["b"] == 2diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_planner_route_retry.py b/tests/unit_tests/server/runtime/skill_turbo/test_planner_route_retry.pynew file mode 100644index 0000000000..399676eb25--- /dev/null+++ b/tests/unit_tests/server/runtime/skill_turbo/test_planner_route_retry.py@@ -0,0 +1,113 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Planner route retry: unparseable LLM output retries once, then degrades to None."""++from __future__ import annotations++import json+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++from jiuwenswarm.server.runtime.skill_turbo.planner import SkillTurboPlanner++_ROUTE_OK = json.dumps({"skill_name": "ppt", "confidence": 0.95, "reason": "PPT 任务"})+_ROUTE_NULL = json.dumps({"skill_name": None, "confidence": 0.0, "reason": "无适配技能"})+++def _client_with_outputs(outputs: list[list[str]]) -> tuple[MagicMock, list[dict]]:+ """构建按调用次序返回 outputs 的 fake model client,并记录每次收到的 messages。"""+ calls: list[dict] = []++ async def stream(messages):+ idx = len(calls)+ calls.append(messages)+ for piece in outputs[min(idx, len(outputs) - 1)]:+ yield SimpleNamespace(content=piece)++ client = MagicMock()+ client.stream = stream+ return client, calls+++def _env(client: MagicMock) -> MagicMock:+ skill = SimpleNamespace(+ name="ppt", description="ppt 任务流", match_keywords=["ppt"], plan_code="code"+ )+ env = MagicMock()+ env.skills = {"ppt": skill}+ env.model_client = client+ return env+++class TestMatchSkillRouteRetry:+ @pytest.mark.asyncio+ async def test_retry_succeeds_after_unparseable_output(self):+ """首次输出不可解析(如空 content),重试后返回合法 JSON → 路由成功。"""+ client, calls = _client_with_outputs([[""], [_ROUTE_OK]])+ planner = SkillTurboPlanner(_env(client))++ skill = await planner.match_skill("生成一份PPT")++ assert skill is not None and skill.name == "ppt"+ assert len(calls) == 2++ @pytest.mark.asyncio+ async def test_retry_exhausted_returns_none(self):+ """两次输出均不可解析 → 返回 None 降级,且恰好重试到上限。"""+ client, calls = _client_with_outputs([["垃圾输出"], ["还是不行 {"]])+ planner = SkillTurboPlanner(_env(client))++ assert await planner.match_skill("生成一份PPT") is None+ assert len(calls) == 2++ @pytest.mark.asyncio+ async def test_valid_first_output_no_retry(self):+ """首次即返回合法 JSON → 不发起多余重试。"""+ client, calls = _client_with_outputs([[_ROUTE_OK]])+ planner = SkillTurboPlanner(_env(client))++ skill = await planner.match_skill("生成一份PPT")++ assert skill is not None and skill.name == "ppt"+ assert len(calls) == 1++ @pytest.mark.asyncio+ async def test_null_skill_name_not_retried(self):+ """skill_name=null 是模型正常判定,不属于瞬态失败,不触发重试。"""+ client, calls = _client_with_outputs([[_ROUTE_NULL]])+ planner = SkillTurboPlanner(_env(client))++ assert await planner.match_skill("你好") is None+ assert len(calls) == 1++ @pytest.mark.asyncio+ async def test_low_confidence_not_retried(self):+ """confidence 低于阈值是正常判定,不触发重试。"""+ low = json.dumps({"skill_name": "ppt", "confidence": 0.3, "reason": "弱匹配"})+ client, calls = _client_with_outputs([[low]])+ planner = SkillTurboPlanner(_env(client))++ assert await planner.match_skill("生成一份PPT") is None+ assert len(calls) == 1++ @pytest.mark.asyncio+ async def test_stream_error_then_success(self):+ """首次流调用抛异常(如网络抖动),重试成功 → 路由成功。"""+ calls: list[dict] = []++ async def flaky_stream(messages):+ calls.append(messages)+ if len(calls) == 1:+ raise ConnectionError("network blip")+ yield SimpleNamespace(content=_ROUTE_OK)++ client = MagicMock()+ client.stream = flaky_stream+ planner = SkillTurboPlanner(_env(client))++ skill = await planner.match_skill("生成一份PPT")++ assert skill is not None and skill.name == "ppt"+ assert len(calls) == 2