Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(rail): 退避序列改为条件生成并增加按次请求抖动

d30029696b7b437d72836
diff --git a/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py b/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py
index e75e9a3644..23942a2f2c 100644
--- a/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import inspect
+import random
from typing import Any
from openjiuwen.core.common.logging import logger
@@ -38,6 +39,10 @@ _COUNT_ATTRS: dict[str, str] = {
_INITIAL_BACKOFF = 5.0
_MAX_BACKOFF = 60.0
_BACKOFF_FACTOR = 2.0
+# Jitter is sampled per retry request, not baked into the generated sequence:
+# concurrent callers share one rail instance (SkillTurbo PPT page gather), so a
+# constructor-time sample would keep them synchronized and defeat the purpose.
+_BACKOFF_JITTER_RANGE = (0.5, 1.5)
def _exponential_backoff(attempt: int) -> float:
@@ -67,11 +72,19 @@ class NotifyingLLMRetryRail(LLMRetryRail):
parent_kwargs = dict(kwargs)
if _parent_accepts_retry_transient_invoke_errors():
parent_kwargs["retry_transient_invoke_errors"] = retry_transient_invoke_errors
- parent_kwargs["backoff_seconds"] = [
- _exponential_backoff(i) for i in range(kwargs.get("max_retries", 2))
- ]
super().__init__(**parent_kwargs)
+ # Generate the exponential schedule only when the caller did not supply
+ # one; build it from the parent-resolved self.max_retries so the parent
+ # default is never duplicated here.
+ if kwargs.get("backoff_seconds") is None:
+ self.backoff_seconds = [
+ _exponential_backoff(i) for i in range(self.max_retries)
+ ]
+ self._backoff_generated = True
+ else:
+ self._backoff_generated = False
+
if not hasattr(self, "transient_invoke_retry_count"):
self.transient_invoke_retry_count = 0
@@ -131,14 +144,26 @@ class NotifyingLLMRetryRail(LLMRetryRail):
elif not will_retry and self.notify_user_on_exhausted:
await self._emit_retry_exhausted(ctx, reason, ctx.exception)
- self._request_retry_or_reset(ctx, reason)
+ self._request_retry_or_reset(ctx, reason, delay=delay)
+
+ def _apply_backoff_jitter(self, delay: float) -> float:
+ """Jitter only the auto-generated schedule; explicit caller values stay exact."""
+ if self._backoff_generated and delay > 0:
+ return delay * random.uniform(*_BACKOFF_JITTER_RANGE)
+ return delay
- def _request_retry_or_reset(self, ctx: AgentCallbackContext, reason: str) -> None:
+ def _request_retry_or_reset(
+ self,
+ ctx: AgentCallbackContext,
+ reason: str,
+ delay: float | None = None,
+ ) -> None:
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)
+ if delay is None:
+ delay = self._apply_backoff_jitter(self.backoff_delay(count))
counts[reason] = count + 1
if attr is not None:
setattr(self, attr, counts[reason])
@@ -164,7 +189,8 @@ class NotifyingLLMRetryRail(LLMRetryRail):
"""Return ``(will_retry, attempt_number, max_attempts, delay_seconds)``."""
count = self._retry_counts(ctx).get(reason, 0)
if count < self.max_retries:
- return True, count + 1, self.max_retries, self.backoff_delay(count)
+ delay = self._apply_backoff_jitter(self.backoff_delay(count))
+ return True, count + 1, self.max_retries, delay
return False, count, self.max_retries, 0.0
@staticmethod
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.py
index 13fbc6723c..19e752e2bd 100644
--- 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.py
@@ -1,12 +1,18 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Per-ctx retry budgets for NotifyingLLMRetryRail under concurrent callers."""
+"""Per-ctx retry budgets for NotifyingLLMRetryRail under concurrent callers.
+
+Also covers the backoff contract: the exponential schedule is generated only
+when the caller does not pass ``backoff_seconds``, and only the generated
+schedule gets per-request jitter.
+"""
from __future__ import annotations
import pytest
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ModelCallInputs
+from jiuwenswarm.agents.harness.common.rails import llm_retry_notify_rail
from jiuwenswarm.agents.harness.common.rails.llm_retry_notify_rail import (
NotifyingLLMRetryRail,
)
@@ -88,3 +94,86 @@ async def test_before_invoke_does_not_reset_sibling_ctx_budget():
ctx_a.exception = _repeat_exc()
await rail.on_model_exception(ctx_a)
assert ctx_a.consume_retry_request() is None
+
+
+def test_generated_backoff_sequence_when_not_provided():
+ rail = NotifyingLLMRetryRail(
+ max_retries=2,
+ notify_user_on_retry=False,
+ notify_user_on_exhausted=False,
+ )
+ assert rail.backoff_seconds == [5.0, 10.0]
+
+
+def test_explicit_none_backoff_still_uses_generated_sequence():
+ """Config-driven callers pass backoff_seconds=None when the key is absent."""
+ rail = NotifyingLLMRetryRail(
+ max_retries=2,
+ backoff_seconds=None,
+ notify_user_on_retry=False,
+ notify_user_on_exhausted=False,
+ )
+ assert rail.backoff_seconds == [5.0, 10.0]
+
+
+def test_generated_backoff_sequence_caps_at_max():
+ rail = NotifyingLLMRetryRail(
+ max_retries=6,
+ notify_user_on_retry=False,
+ notify_user_on_exhausted=False,
+ )
+ assert rail.backoff_seconds == [5.0, 10.0, 20.0, 40.0, 60.0, 60.0]
+
+
+def test_explicit_backoff_sequence_is_respected():
+ rail = NotifyingLLMRetryRail(
+ max_retries=2,
+ backoff_seconds=[0.0, 0.0],
+ notify_user_on_retry=False,
+ notify_user_on_exhausted=False,
+ )
+ assert rail.backoff_seconds == [0.0, 0.0]
+
+
+async def test_generated_backoff_applies_per_request_jitter(monkeypatch):
+ monkeypatch.setattr(
+ llm_retry_notify_rail.random, "uniform", lambda low, high: 1.5
+ )
+ rail = NotifyingLLMRetryRail(
+ max_retries=2,
+ notify_user_on_retry=False,
+ notify_user_on_exhausted=False,
+ )
+ ctx = _ctx()
+ await rail.before_invoke(ctx)
+
+ ctx.exception = _repeat_exc()
+ await rail.on_model_exception(ctx)
+
+ request = ctx.consume_retry_request()
+ assert request is not None
+ assert request.delay_seconds == 7.5
+
+
+async def test_explicit_backoff_has_no_jitter(monkeypatch):
+ def _no_jitter_expected(low, high):
+ raise AssertionError("jitter must not apply to explicit backoff_seconds")
+
+ monkeypatch.setattr(llm_retry_notify_rail.random, "uniform", _no_jitter_expected)
+ rail = NotifyingLLMRetryRail(
+ max_retries=1,
+ backoff_seconds=[0.0],
+ notify_user_on_retry=False,
+ notify_user_on_exhausted=False,
+ )
+ ctx = _ctx()
+ await rail.before_invoke(ctx)
+
+ ctx.exception = _repeat_exc()
+ await rail.on_model_exception(ctx)
+
+ request = ctx.consume_retry_request()
+ assert request is not None
+ assert request.delay_seconds == 0.0