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(runtime): keep circuit-breaker streaks contiguous and lock history

n9935770289033caf01c0f
diff --git a/jiuwenswarm/agents/harness/common/rails/browser_task_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/browser_task_prompt_rail.py
index ba7014e4cd..2e28c3415f 100644
--- a/jiuwenswarm/agents/harness/common/rails/browser_task_prompt_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/browser_task_prompt_rail.py
@@ -15,6 +15,30 @@ from jiuwenswarm.agents.harness.common.prompt.browser_task_prompt import (
)
+def _card_name(card: object) -> str | None:
+ """Return a public ``name`` from a card object or dict."""
+ if card is None:
+ return None
+ if isinstance(card, dict):
+ name = card.get("name")
+ return name if isinstance(name, str) else None
+ name = getattr(card, "name", None)
+ return name if isinstance(name, str) else None
+
+
+def _spec_name(spec: object) -> str | None:
+ """Read a subagent name from public card fields.
+
+ ``SubAgentConfig`` exposes ``agent_card``. A live DeepAgent exposes
+ ``card``. Neither path calls ``SubagentRail._extract_agent_meta``.
+ """
+ for attr in ("agent_card", "card"):
+ name = _card_name(getattr(spec, attr, None))
+ if name is not None:
+ return name
+ return _card_name(spec)
+
+
def _subagent_rail_init_kwargs(
*,
enable_async_subagent: bool,
@@ -64,13 +88,14 @@ class BrowserTaskPromptRail(SubagentRail):
return None
return build_browser_task_prompt(language)
- def _has_browser_agent(self, agent: object) -> bool:
+ @staticmethod
+ def _has_browser_agent(agent: object) -> bool:
deep_config = getattr(agent, "deep_config", None)
subagents = getattr(deep_config, "subagents", None) or []
- return any(
- self._extract_agent_meta(spec)[0] == "browser_agent"
- for spec in subagents
- )
+ for spec in subagents:
+ if _spec_name(spec) == "browser_agent":
+ return True
+ return False
__all__ = ["BrowserTaskPromptRail"]
diff --git a/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py b/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py
index 71b588da7d..0f5dd01b42 100644
--- a/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py
@@ -11,11 +11,11 @@
from __future__ import annotations
-import asyncio
import contextvars
import hashlib
import json
import re
+import threading
import time
from dataclasses import dataclass
from typing import Any
@@ -314,7 +314,7 @@ class CircuitBreakerRail(DeepAgentRail):
super().__init__()
self._config = config or CircuitBreakerConfig()
self._histories: dict[str, list[ToolCallRecord]] = {}
- self._locks: dict[str, asyncio.Lock] = {}
+ self._locks: dict[str, threading.Lock] = {}
self._language = _normalize_language(language)
def set_language(self, language: str) -> None:
@@ -322,10 +322,15 @@ class CircuitBreakerRail(DeepAgentRail):
self._language = _normalize_language(language)
def cleanup_session(self, session_id: str = "") -> None:
- """Remove per-session history and lock for *session_id*."""
+ """Remove per-session history and lock for *session_id*.
+
+ Adapter teardown calls this synchronously, so the guard is a
+ ``threading.Lock``. The critical section does not await.
+ """
sid = session_id or "default"
- self._histories.pop(sid, None)
- self._locks.pop(sid, None)
+ with self._get_lock(sid):
+ self._histories.pop(sid, None)
+ self._locks.pop(sid, None)
def _resolve_sid(self, ctx: AgentCallbackContext) -> str:
invoke_sid = _invoke_sid.get()
@@ -351,10 +356,10 @@ class CircuitBreakerRail(DeepAgentRail):
self._histories[sid] = history
return history
- def _get_lock(self, sid: str) -> asyncio.Lock:
+ def _get_lock(self, sid: str) -> threading.Lock:
lock = self._locks.get(sid)
if lock is None:
- lock = asyncio.Lock()
+ lock = threading.Lock()
self._locks[sid] = lock
return lock
@@ -380,7 +385,8 @@ class CircuitBreakerRail(DeepAgentRail):
sid = raw_conv_id or "default"
ctx.extra[self._SID_KEY] = sid
_invoke_sid.set(sid)
- self._histories[sid] = []
+ with self._get_lock(sid):
+ self._histories[sid] = []
async def after_invoke(self, ctx: AgentCallbackContext) -> None:
sid = _invoke_sid.get()
@@ -411,7 +417,7 @@ class CircuitBreakerRail(DeepAgentRail):
tool_result, ctx,
)
- async with self._get_lock(sid):
+ with self._get_lock(sid):
history = self._get_history(sid)
history.append(ToolCallRecord(
tool_name=tool_name,
@@ -536,9 +542,9 @@ class CircuitBreakerRail(DeepAgentRail):
latest_hash = None
for record in reversed(history):
if record.tool_name != tool_name or record.args_hash != args_hash:
- continue
+ break
if record.result_hash is None:
- continue
+ break
if latest_hash is None:
latest_hash = record.result_hash
streak = 1
diff --git a/tests/unit_tests/agentserver/rails/test_browser_task_prompt_rail.py b/tests/unit_tests/agentserver/rails/test_browser_task_prompt_rail.py
new file mode 100644
index 0000000000..4a7a54e353
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_browser_task_prompt_rail.py
@@ -0,0 +1,41 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Browser rail identifies browser_agent from public card fields."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jiuwenswarm.agents.harness.common.rails.browser_task_prompt_rail import (
+ BrowserTaskPromptRail,
+)
+
+
+def test_has_browser_agent_reads_agent_card_or_card() -> None:
+ agent = SimpleNamespace(
+ deep_config=SimpleNamespace(
+ subagents=[
+ SimpleNamespace(agent_card=SimpleNamespace(name="general")),
+ SimpleNamespace(card=SimpleNamespace(name="browser_agent")),
+ ]
+ )
+ )
+ assert BrowserTaskPromptRail._has_browser_agent(agent) is True
+
+
+def test_has_browser_agent_reads_dict_card() -> None:
+ agent = SimpleNamespace(
+ deep_config=SimpleNamespace(
+ subagents=[SimpleNamespace(agent_card={"name": "browser_agent"})]
+ )
+ )
+ assert BrowserTaskPromptRail._has_browser_agent(agent) is True
+
+
+def test_has_browser_agent_false_without_browser() -> None:
+ agent = SimpleNamespace(
+ deep_config=SimpleNamespace(
+ subagents=[SimpleNamespace(agent_card=SimpleNamespace(name="code"))]
+ )
+ )
+ assert BrowserTaskPromptRail._has_browser_agent(agent) is False
diff --git a/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
index 4d9f98764e..20fa1e37d3 100644
--- a/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
+++ b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
@@ -13,6 +13,7 @@ from types import SimpleNamespace
from openjiuwen.core.single_agent.rail.base import (
AgentCallbackContext,
+ InvokeInputs,
ToolCallInputs,
)
@@ -66,6 +67,33 @@ def test_generic_repeat_warns_without_force_finish() -> None:
assert result.detector == "generic_repeat"
+def test_no_progress_streak_stops_at_a_different_call() -> None:
+ """Intervening tools must not be skipped when counting a no-progress streak."""
+ rail = _rail(global_breaker_threshold=3, warning_threshold=10)
+ history = [
+ _record("read_file", "a", "same"),
+ _record("bash", "b", "other"),
+ _record("read_file", "a", "same"),
+ _record("read_file", "a", "same"),
+ ]
+ assert rail._get_no_progress_streak(history, "read_file", "a") == 2
+ result = rail._detect(history, "read_file", "a")
+ assert result.stuck is False
+
+
+def test_no_progress_streak_stops_when_result_hash_is_missing() -> None:
+ """A missing result hash cannot continue a no-progress streak."""
+ rail = _rail(global_breaker_threshold=2, warning_threshold=10)
+ history = [
+ _record("bash", "cmd", "same"),
+ _record("bash", "cmd", None),
+ _record("bash", "cmd", "same"),
+ ]
+ assert rail._get_no_progress_streak(history, "bash", "cmd") == 1
+ result = rail._detect(history, "bash", "cmd")
+ assert result.stuck is False
+
+
def test_global_breaker_interrupts_no_progress() -> None:
rail = _rail(global_breaker_threshold=5)
history = [_record("bash", "cmd", "same") for _ in range(5)]
@@ -99,6 +127,17 @@ def test_ping_pong_critical_when_both_sides_stall() -> None:
assert result.detector == "ping_pong"
+async def test_before_invoke_clears_history_for_conversation() -> None:
+ rail = _rail()
+ rail._histories["conv"] = [_record("bash", "a")]
+ ctx = AgentCallbackContext(
+ agent=object(),
+ inputs=InvokeInputs(query="hello", conversation_id="conv"),
+ )
+ await rail.before_invoke(ctx)
+ assert rail._histories["conv"] == []
+
+
def test_cleanup_session_drops_history() -> None:
rail = _rail()
rail._histories["s1"] = [_record("bash", "a")]