"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): escalate stream retry delays and honor Retry-After
lorenzozanee6a3b0b590ec9
diff --git a/agent/.env.example b/agent/.env.exampleindex dce57aa55..da99396df 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -300,6 +300,7 @@ TUSHARE_TOKEN=your-tushare-token# SWARM_TIMEOUT=1800# SWARM_WORKER_RETRY_BASE_DELAY_S=1.0# SWARM_WORKER_RETRY_MAX_DELAY_S=30.0+# SWARM_STREAM_RETRY_MAX_DELAY_S=30.0# SUBAGENT_TIMEOUT=300# SUBAGENT_MAX_ITER=25# TOKEN_THRESHOLD=40000diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 3a96477e2..2d0f7ec0d 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -111,6 +111,37 @@ def _stream_retry_delay_s() -> float:return get_env_config().agent_tuning.vt_stream_retry_delay_s+def _stream_retry_max_delay_s() -> float:+ ov = _override("STREAM_RETRY_MAX_DELAY_S")+ if ov is not None:+ return ov+ from src.config.accessor import get_env_config+ return get_env_config().agent_tuning.vt_stream_retry_max_delay_s+++def _stream_retry_backoff_s(streak: int) -> float:+ """Return the capped exponential delay for the one-based failure streak.++ Doubles per consecutive retryable stream failure (1.0s, 2.0s, 4.0s, ...)+ so a sustained provider outage backs off instead of burning the retry+ budget at a constant cadence. The exponent is clamped at 62 (mirroring+ ``src/swarm/runtime.py``'s worker-level backoff) and the result is capped+ at ``_stream_retry_max_delay_s()``.++ Args:+ streak: Number of consecutive retryable stream failures including the+ current one; values below 1 are treated as 1.++ Returns:+ Seconds to sleep before the stream retry, never negative.+ """+ ceiling = min(+ _stream_retry_delay_s() * (2 ** min(max(streak, 1) - 1, 62)),+ _stream_retry_max_delay_s(),+ )+ return max(ceiling, 0.0)++def _tool_timeout_seconds() -> float:ov = _override("TOOL_TIMEOUT_SECONDS")if ov is not None:@@ -1100,6 +1131,7 @@ class AgentLoop:)watchdog.start()+ stream_failure_streak = 0try:while iteration < self.max_iterations:if self._cancel_event.is_set():@@ -1255,12 +1287,23 @@ class AgentLoop:# reset, relay hiccup) — mirrors the swarm worker policy.# Deterministic 4xx errors fail immediately. Deltas from# the failed attempt are dropped so the trace does not- # contain duplicated thinking text.+ # contain duplicated thinking text. The delay escalates+ # across consecutive retryable failures, honoring the+ # provider's Retry-After header (bounded by the configured+ # cap) when present. A successful retry does not reset the+ # streak — only a clean first-attempt success does.if not exc.retryable:raise+ stream_failure_streak += 1+ retry_delay_s = (+ min(exc.retry_after_s, _stream_retry_max_delay_s())+ if exc.retry_after_s is not None+ else _stream_retry_backoff_s(stream_failure_streak)+ )logger.warning(- "Provider stream failed (iter %s), retrying once: %s",+ "Provider stream failed (iter %s), retrying once in %.2fs: %s",current_iter,+ retry_delay_s,exc,)self._emit(@@ -1270,12 +1313,13 @@ class AgentLoop:"reason": "provider_stream_retry","provider": exc.provider,"model": exc.model,+ "retry_delay_s": retry_delay_s,},)thinking_chunks.clear()reasoning_chars = 0last_reasoning_emit = None- _time.sleep(_stream_retry_delay_s())+ _time.sleep(retry_delay_s)response = self.llm.stream_chat(messages,tools=tool_defs,@@ -1285,6 +1329,8 @@ class AgentLoop:idle_timeout_s=llm_timeout,should_cancel=self._cancel_event.is_set,)+ else:+ stream_failure_streak = 0# Cancelled mid-stream: discard this turn's partial response and# end the run now, without executing any of its tool calls.@@ -2764,6 +2810,7 @@ _LEGACY_LAZY = {"HEARTBEAT_INTERVAL_S": _heartbeat_interval_s,"REASONING_DELTA_MIN_INTERVAL_S": _reasoning_delta_min_interval_s,"STREAM_RETRY_DELAY_S": _stream_retry_delay_s,+ "STREAM_RETRY_MAX_DELAY_S": _stream_retry_max_delay_s,"TOOL_TIMEOUT_SECONDS": _tool_timeout_seconds,"GOAL_MAX_CONTINUATIONS": _goal_max_continuations,"STALL_TIMEOUT_SECONDS": _stall_timeout_seconds,diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex 2665a43cd..3e9496524 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -345,6 +345,9 @@ class SwarmConfig(_EnvBase):swarm_timeout: int = Field(alias="SWARM_TIMEOUT", default=1800)swarm_heartbeat_interval_s: float = Field(alias="SWARM_HEARTBEAT_INTERVAL_S", default=3.0)swarm_stream_retry_delay_s: float = Field(alias="SWARM_STREAM_RETRY_DELAY_S", default=1.0)+ swarm_stream_retry_max_delay_s: float = Field(+ alias="SWARM_STREAM_RETRY_MAX_DELAY_S", default=30.0, ge=0+ )swarm_worker_retry_base_delay_s: float = Field(alias="SWARM_WORKER_RETRY_BASE_DELAY_S", default=1.0, ge=0)@@ -354,12 +357,17 @@ class SwarmConfig(_EnvBase):swarm_grounding_max_symbols: int = Field(alias="SWARM_GROUNDING_MAX_SYMBOLS", default=8)@model_validator(mode="after")- def _validate_worker_retry_delays(self) -> SwarmConfig:+ def _validate_retry_delays(self) -> SwarmConfig:if self.swarm_worker_retry_max_delay_s < self.swarm_worker_retry_base_delay_s:raise ValueError("SWARM_WORKER_RETRY_MAX_DELAY_S must be greater than or equal to ""SWARM_WORKER_RETRY_BASE_DELAY_S")+ if self.swarm_stream_retry_max_delay_s < self.swarm_stream_retry_delay_s:+ raise ValueError(+ "SWARM_STREAM_RETRY_MAX_DELAY_S must be greater than or equal to "+ "SWARM_STREAM_RETRY_DELAY_S"+ )return self@@ -383,6 +391,9 @@ class AgentTuningConfig(_EnvBase):alias="VT_REASONING_DELTA_MIN_INTERVAL_S", default=1.0,)vt_stream_retry_delay_s: float = Field(alias="VT_STREAM_RETRY_DELAY_S", default=1.0)+ vt_stream_retry_max_delay_s: float = Field(+ alias="VT_STREAM_RETRY_MAX_DELAY_S", default=30.0, ge=0+ )vibe_trading_tool_timeout_seconds: float = Field(alias="VIBE_TRADING_TOOL_TIMEOUT_SECONDS", default=1800.0,)@@ -430,6 +441,15 @@ class AgentTuningConfig(_EnvBase):alias="VIBE_LIVE_AUTHORIZE_TIMEOUT_SECONDS", default=300,)+ @model_validator(mode="after")+ def _validate_stream_retry_delays(self) -> AgentTuningConfig:+ if self.vt_stream_retry_max_delay_s < self.vt_stream_retry_delay_s:+ raise ValueError(+ "VT_STREAM_RETRY_MAX_DELAY_S must be greater than or equal to "+ "VT_STREAM_RETRY_DELAY_S"+ )+ return self+# ---------------------------------------------------------------------------# Pathsdiff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex 4f3759634..c10b658f9 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -117,6 +117,22 @@ class LLMResponse:return len(self.tool_calls) > 0+def _extract_retry_after_s(original: Exception) -> Optional[float]:+ """Return the provider-suggested Retry-After delay in seconds, if any."""+ response = getattr(original, "response", None)+ headers = getattr(response, "headers", None)+ if headers is None:+ return None+ raw = headers.get("Retry-After")+ if raw is None:+ return None+ try:+ value = float(raw)+ except (TypeError, ValueError):+ return None+ return value if value >= 0.0 else None++class ProviderStreamError(RuntimeError):"""Raised when provider streaming fails before a complete response."""@@ -127,11 +143,17 @@ class ProviderStreamError(RuntimeError):provider: Effective provider name.model: Effective model name.original: Original exception from the stream path.++ Attributes:+ retry_after_s: Provider-suggested Retry-After delay in seconds,+ extracted from the original exception's response headers when+ present and parseable as a non-negative number; otherwise None."""self.provider = providerself.model = modelself.original = originalself.status_code: Optional[int] = getattr(original, "status_code", None)+ self.retry_after_s: Optional[float] = _extract_retry_after_s(original)safe_message = _redact_provider_error(str(original))hint = ""lowered = safe_message.lower()diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex 59329d8de..4bcb43084 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -74,8 +74,47 @@ def _stream_retry_delay_s() -> float:return get_env_config().swarm.swarm_stream_retry_delay_s+def _stream_retry_max_delay_s() -> float:+ """Resolve the cap for the escalating stream-retry delay, robust to garbage.++ Returns:+ Upper bound in seconds for both the escalated exponential delay and a+ provider-suggested ``Retry-After``. Configurable via+ ``SWARM_STREAM_RETRY_MAX_DELAY_S``; a non-numeric value fails config+ validation, mirroring the other swarm delay knobs.+ """+ from src.config.accessor import get_env_config++ return get_env_config().swarm.swarm_stream_retry_max_delay_s+++def _escalated_stream_retry_delay_s(streak: int) -> float:+ """Return the capped exponential delay for the one-based failure streak.++ Doubles per consecutive retryable failure (1.0s, 2.0s, 4.0s, ...) so a+ sustained provider outage backs off instead of burning the retry budget+ at a constant cadence. The exponent is clamped at 62 (mirroring+ ``src/swarm/runtime.py``'s worker-level backoff) and the result is capped+ at ``_STREAM_RETRY_MAX_DELAY_S`` so a long outage never exceeds the+ configured ceiling.++ Args:+ streak: Number of consecutive retryable stream failures including the+ current one; values below 1 are treated as 1.++ Returns:+ Seconds to sleep before the stream retry, never negative.+ """+ ceiling = min(+ _STREAM_RETRY_DELAY_S * (2 ** min(max(streak, 1) - 1, 62)),+ _STREAM_RETRY_MAX_DELAY_S,+ )+ return max(ceiling, 0.0)++_HEARTBEAT_INTERVAL_S = _heartbeat_interval_s()_STREAM_RETRY_DELAY_S = _stream_retry_delay_s()+_STREAM_RETRY_MAX_DELAY_S = _stream_retry_max_delay_s()_MAX_TOKEN_ESTIMATE = 60_000@@ -590,6 +629,7 @@ def _run_worker_impl(data_tool_calls = 0content_filter_count = 0consecutive_content_filter_count = 0+ stream_failure_streak = 0for iteration in range(max_iterations):# Microcompact: clear old tool results to prevent token bloat@@ -744,24 +784,37 @@ def _run_worker_impl(# absorbed by ChatLLM's silent non-streaming fallback; it now# surfaces as ProviderStreamError, so retry the stream exactly# once before taking the existing failure path. Deterministic- # 4xx errors skip the retry and fail immediately.+ # 4xx errors skip the retry and fail immediately. The delay+ # escalates across consecutive retryable failures, honoring the+ # provider's Retry-After header (bounded by the configured cap)+ # when present. A successful retry does not reset the streak —+ # only a clean first-attempt success does.try:response = _stream_once()except ProviderStreamError as stream_exc:if not stream_exc.retryable:raise+ stream_failure_streak += 1+ retry_delay_s = (+ min(stream_exc.retry_after_s, _STREAM_RETRY_MAX_DELAY_S)+ if stream_exc.retry_after_s is not None+ else _escalated_stream_retry_delay_s(stream_failure_streak)+ )logger.warning("Provider stream failed for agent=%s task=%s iteration=%d "- "(provider=%s model=%s); retrying once: %s",+ "(provider=%s model=%s); retrying once in %.2fs: %s",agent_id,task_id,iteration,stream_exc.provider,stream_exc.model,+ retry_delay_s,stream_exc,)- time.sleep(_STREAM_RETRY_DELAY_S)+ time.sleep(retry_delay_s)response = _stream_once()+ else:+ stream_failure_streak = 0# Cancelled mid-stream: discard this turn's partial response and# stop now, without executing any of its tool calls — mirrorsdiff --git a/agent/tests/test_stream_retry_escalation.py b/agent/tests/test_stream_retry_escalation.pynew file mode 100644index 000000000..2187f8afd--- /dev/null+++ b/agent/tests/test_stream_retry_escalation.py@@ -0,0 +1,461 @@+"""Tests for escalating stream-retry delays and Retry-After honoring.++Issue #1208: both LLM stream-retry sites (``AgentLoop.run`` and the swarm+worker) used a constant one-shot delay, so a sustained provider outage burned+the patience budget in seconds. The delay now escalates across consecutive+retryable failures (capped exponential) and honors the provider's+``Retry-After`` header on 429/529, bounded by the configured maximum.+"""++from __future__ import annotations++import types+from pathlib import Path+from typing import Any, Callable+from unittest.mock import patch++import pytest+from pydantic import ValidationError++import src.agent.loop as loop_mod+import src.swarm.worker as worker_mod+from src.config.env_schema import AgentTuningConfig, SwarmConfig+from src.providers.chat import LLMResponse, ProviderStreamError, ToolCallRequest++# Substantive prose so _classify_deliverable accepts the tool-less worker.+FINAL_TEXT = (+ "# BTC-USDT — Short-Term View\n\n"+ "Spot 81,704.6 (2026-05-05). 7d range 77,750-82,842.\n\n"+ "**Recommendation: accumulate on dips to 79k; invalidation below 77.5k.**\n"+ "Position 3% NAV, stop 76,900, target 86,000. Funding 0.035%/8h elevated\n"+ "but not extreme; exchange reserves declining (bullish)."+)+++class _EmptyRegistry:+ """Minimal stand-in for the swarm ToolRegistry (execute returns ok)."""++ def get_definitions(self) -> list[dict]:+ """Return an empty tool-definition list."""+ return []++ def execute(self, name: str, args: dict) -> str:+ """Execute nothing; return a canned tool result."""+ return "ok"++ def get(self, name: str):+ """Return no tool metadata."""+ return None+++class _ScriptedWorkerLLM:+ """Scripted ChatLLM playing a per-call script of errors and responses."""++ def __init__(self, script: list) -> None:+ """Initialize the scripted stub.++ Args:+ script: One entry per ``stream_chat`` call, consumed in order:+ an Exception to raise or an ``LLMResponse`` to return. The+ last response repeats once the script is exhausted.+ """+ self._script = list(script)+ self.calls = 0++ def __call__(self, *args, **kwargs) -> "_ScriptedWorkerLLM":+ """Support ``ChatLLM(model_name=...)`` constructor-style patching."""+ return self++ def close(self) -> None:+ """No-op: the stub owns no HTTP client."""+ return None++ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None):+ """Play the next scripted entry, or repeat the final response."""+ self.calls += 1+ if self._script:+ outcome = self._script.pop(0)+ if isinstance(outcome, Exception):+ raise outcome+ return outcome+ return LLMResponse(content=FINAL_TEXT)+++def _transient_error() -> ProviderStreamError:+ """Build a ProviderStreamError mimicking a transient mid-stream reset."""+ return ProviderStreamError(+ provider="openrouter",+ model="test-model",+ original=ConnectionResetError("connection reset by peer"),+ )+++def _rate_limit_error(retry_after: str) -> ProviderStreamError:+ """Build a retryable 429-style error carrying a Retry-After header."""+ original = Exception("rate limited: too many requests")+ original.status_code = 429 # type: ignore[attr-defined]+ original.response = types.SimpleNamespace( # type: ignore[attr-defined]+ headers={"Retry-After": retry_after}+ )+ return ProviderStreamError(provider="openrouter", model="test-model", original=original)+++def _bad_request_error() -> ProviderStreamError:+ """Build a ProviderStreamError mimicking a deterministic 400 rejection."""+ original = Exception("invalid temperature: only 1 is allowed for this model")+ original.status_code = 400 # type: ignore[attr-defined]+ return ProviderStreamError(+ provider="moonshot", model="kimi-k2.6", original=original+ )+++def _tool_response(idx: int) -> LLMResponse:+ """Build a tool-call response that keeps the worker loop iterating."""+ return LLMResponse(+ content="searching...",+ tool_calls=[+ ToolCallRequest(id=f"tc{idx}", name="web_search", arguments={"q": "test"})+ ],+ )+++def _run_worker(+ monkeypatch,+ tmp_path: Path,+ llm: _ScriptedWorkerLLM,+ max_iterations: int = 4,+) -> tuple[Any, list[float]]:+ """Run a swarm worker against the scripted LLM, recording sleep durations.++ Args:+ monkeypatch: pytest monkeypatch fixture (patches sleep + delay knobs).+ tmp_path: Scratch run directory.+ llm: The scripted ChatLLM stub.+ max_iterations: Worker iteration budget.++ Returns:+ Tuple of ``(WorkerResult, sleeps)`` where sleeps lists every+ ``time.sleep`` duration observed inside the worker.+ """+ sleeps: list[float] = []+ monkeypatch.setattr(worker_mod.time, "sleep", lambda s: sleeps.append(s))+ monkeypatch.setattr(worker_mod, "_STREAM_RETRY_DELAY_S", 1.0)+ monkeypatch.setattr(worker_mod, "_STREAM_RETRY_MAX_DELAY_S", 8.0)+ agent_spec = worker_mod.SwarmAgentSpec(+ id="analyst",+ role="Synthesis analyst",+ system_prompt="You synthesize upstream findings.",+ tools=[],+ skills=[],+ max_iterations=max_iterations,+ timeout_seconds=60,+ )+ task = worker_mod.SwarmTask(id="t1", agent_id="analyst", prompt_template="Summarize.")+ with (+ patch.object(worker_mod, "build_swarm_registry", lambda *a, **k: _EmptyRegistry()),+ patch.object(worker_mod, "ChatLLM", llm),+ ):+ result = worker_mod.run_worker(+ agent_spec=agent_spec,+ task=task,+ upstream_summaries={},+ user_vars={},+ run_dir=tmp_path,+ )+ return result, sleeps+++def test_first_failure_sleeps_configured_base(monkeypatch, tmp_path):+ """One retryable failure → exactly one sleep of the configured base (1.0)."""+ llm = _ScriptedWorkerLLM([_transient_error(), LLMResponse(content=FINAL_TEXT)])++ result, sleeps = _run_worker(monkeypatch, tmp_path, llm)++ assert result.status == "completed"+ assert sleeps == [1.0]+++def test_existing_single_failure_still_retried_once(monkeypatch, tmp_path):+ """One retryable failure → exactly two stream_chat calls (no multi-retry)."""+ llm = _ScriptedWorkerLLM([_transient_error(), LLMResponse(content=FINAL_TEXT)])++ result, _ = _run_worker(monkeypatch, tmp_path, llm)++ assert result.status == "completed"+ assert llm.calls == 2+++def test_delay_escalates_across_consecutive_iterations(monkeypatch, tmp_path):+ """Consecutive failing iterations escalate 1.0 → 2.0 → 4.0 despite retries.++ A successful retry must NOT reset the streak; only a clean first-attempt+ success does. Iterations 0-2 each fail and retry — the first two retries+ return tool calls so the loop continues, the final retry returns the+ final text — pinning sleeps [1.0, 2.0, 4.0].+ """+ llm = _ScriptedWorkerLLM([+ _transient_error(), _tool_response(0),+ _transient_error(), _tool_response(1),+ _transient_error(), LLMResponse(content=FINAL_TEXT),+ ])++ result, sleeps = _run_worker(monkeypatch, tmp_path, llm, max_iterations=4)++ assert result.status == "completed"+ assert sleeps == [1.0, 2.0, 4.0]+++def test_streak_resets_after_clean_iteration(monkeypatch, tmp_path):+ """A clean first-attempt iteration resets the streak to the base delay."""+ llm = _ScriptedWorkerLLM([_tool_response(0), _transient_error()])++ result, sleeps = _run_worker(monkeypatch, tmp_path, llm, max_iterations=3)++ assert result.status == "completed"+ assert sleeps == [1.0]+++def test_non_retryable_error_no_sleep_no_escalation(monkeypatch, tmp_path):+ """A deterministic 4xx fails the worker with no sleep recorded."""+ llm = _ScriptedWorkerLLM([_bad_request_error()])++ result, sleeps = _run_worker(monkeypatch, tmp_path, llm, max_iterations=3)++ assert result.status == "failed"+ assert sleeps == []+++def test_retry_after_honored(monkeypatch, tmp_path):+ """A 429 with Retry-After: 7 sleeps exactly 7 seconds."""+ llm = _ScriptedWorkerLLM([_rate_limit_error("7")])++ result, sleeps = _run_worker(monkeypatch, tmp_path, llm)++ assert result.status == "completed"+ assert sleeps == [7.0]+++def test_retry_after_clamped_to_max(monkeypatch, tmp_path):+ """A Retry-After larger than the configured cap is clamped to the cap."""+ llm = _ScriptedWorkerLLM([_rate_limit_error("500")])++ result, sleeps = _run_worker(monkeypatch, tmp_path, llm)++ assert result.status == "completed"+ assert sleeps == [8.0]+++def test_garbage_retry_after_falls_back_to_backoff(monkeypatch, tmp_path):+ """A non-numeric Retry-After header falls back to the exponential delay."""+ llm = _ScriptedWorkerLLM([_rate_limit_error("soon")])++ result, sleeps = _run_worker(monkeypatch, tmp_path, llm)++ assert result.status == "completed"+ assert sleeps == [1.0]+++# ---------------------------------------------------------------------------+# Provider layer: Retry-After extraction on ProviderStreamError+# ---------------------------------------------------------------------------+++def test_retry_after_s_none_for_connection_reset():+ """A header-less transport error (connection reset) yields retry_after_s=None."""+ err = ProviderStreamError(+ provider="openrouter",+ model="test-model",+ original=ConnectionResetError("connection reset by peer"),+ )++ assert err.retry_after_s is None+++ ("response", "expected"),+ [+ (None, None),+ (types.SimpleNamespace(headers={}), None),+ (types.SimpleNamespace(headers={"Retry-After": "7"}), 7.0),+ (types.SimpleNamespace(headers={"Retry-After": "0"}), 0.0),+ (types.SimpleNamespace(headers={"Retry-After": "soon"}), None),+ (types.SimpleNamespace(headers={"Retry-After": "-3"}), None),+ ],+)+def test_retry_after_s_extraction(response, expected):+ """retry_after_s is the parsed non-negative float, or None when unusable."""+ original = Exception("boom")+ if response is not None:+ original.response = response # type: ignore[attr-defined]++ err = ProviderStreamError(provider="openrouter", model="test-model", original=original)++ assert err.retry_after_s == expected+++# ---------------------------------------------------------------------------+# AgentLoop site+# ---------------------------------------------------------------------------+++class _FlakyLoopLLM:+ """LLM stub raising queued errors from stream_chat before succeeding."""++ def __init__(self, errors: list[Exception], final_content: str) -> None:+ """Initialize the flaky stub.++ Args:+ errors: Exceptions raised by successive ``stream_chat`` calls,+ consumed in order before any success.+ final_content: Content of the response returned once the error+ queue is drained.+ """+ self._errors = list(errors)+ self._final_content = final_content+ self.calls = 0++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,+ timeout: int | None = None,+ idle_timeout_s: float | None = None,+ should_cancel: Callable[[], bool] | None = None,+ ) -> LLMResponse:+ """Raise the next queued error or return the final response."""+ self.calls += 1+ if self._errors:+ raise self._errors.pop(0)+ return LLMResponse(content=self._final_content)++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:+ """Return an empty non-streaming response (unused)."""+ return LLMResponse(content="")+++def _run_loop(+ monkeypatch,+ tmp_path: Path,+ llm: _FlakyLoopLLM,+ events: list[tuple[str, dict[str, Any]]] | None = None,+) -> tuple[dict[str, Any], list[float]]:+ """Run an AgentLoop turn, recording sleep durations.++ Args:+ monkeypatch: pytest monkeypatch fixture (patches sleep + delay knobs).+ tmp_path: Scratch run directory.+ llm: The scripted LLM stub.+ events: Optional event sink collecting ``(event_type, data)`` tuples.++ Returns:+ Tuple of ``(result, sleeps)``.+ """+ from src.agent.loop import AgentLoop+ from src.memory.persistent import PersistentMemory+ from src.tools import build_registry++ sleeps: list[float] = []+ monkeypatch.setattr(loop_mod._time, "sleep", lambda s: sleeps.append(s))+ monkeypatch.setattr(loop_mod, "STREAM_RETRY_DELAY_S", 1.0)+ monkeypatch.setattr(loop_mod, "STREAM_RETRY_MAX_DELAY_S", 8.0)+ pm = PersistentMemory()+ agent = AgentLoop(+ registry=build_registry(persistent_memory=pm, include_shell_tools=False),+ llm=llm,+ event_callback=(+ (lambda event_type, data: events.append((event_type, data)))+ if events is not None+ else None+ ),+ max_iterations=3,+ persistent_memory=pm,+ )+ run_dir = tmp_path / "run"+ run_dir.mkdir(parents=True, exist_ok=True)+ agent.memory.run_dir = str(run_dir)+ return agent.run(user_message="hello"), sleeps+++def test_loop_first_failure_sleeps_base(monkeypatch, tmp_path: Path) -> None:+ """One transient failure in AgentLoop → exactly one sleep of base (1.0)."""+ llm = _FlakyLoopLLM([_transient_error()], "Final answer.")++ result, sleeps = _run_loop(monkeypatch, tmp_path, llm)++ assert result["status"] == "success"+ assert llm.calls == 2+ assert sleeps == [1.0]+++def test_loop_retry_after_honored_and_emitted(monkeypatch, tmp_path: Path) -> None:+ """A 429 with Retry-After: 7 sleeps 7s and emits retry_delay_s=7.0."""+ llm = _FlakyLoopLLM([_rate_limit_error("7")], "Final answer.")+ events: list[tuple[str, dict[str, Any]]] = []++ result, sleeps = _run_loop(monkeypatch, tmp_path, llm, events)++ assert result["status"] == "success"+ assert sleeps == [7.0]+ reset = next(data for event_type, data in events if event_type == "stream_reset")+ assert reset["retry_delay_s"] == 7.0+++def test_loop_non_retryable_error_no_sleep(monkeypatch, tmp_path: Path) -> None:+ """A deterministic 4xx fails the loop with no sleep recorded."""+ llm = _FlakyLoopLLM([_bad_request_error()], "Final answer.")++ result, sleeps = _run_loop(monkeypatch, tmp_path, llm)++ assert result["status"] == "failed"+ assert result["error_code"] == "provider_stream_error"+ assert sleeps == []+++def test_loop_backoff_helper_escalates_and_caps(monkeypatch) -> None:+ """The loop's capped-exponential helper escalates 1→2→4 and caps at max."""+ monkeypatch.setattr(loop_mod, "STREAM_RETRY_DELAY_S", 1.0)+ monkeypatch.setattr(loop_mod, "STREAM_RETRY_MAX_DELAY_S", 8.0)++ assert loop_mod._stream_retry_backoff_s(1) == 1.0+ assert loop_mod._stream_retry_backoff_s(2) == 2.0+ assert loop_mod._stream_retry_backoff_s(3) == 4.0+ assert loop_mod._stream_retry_backoff_s(7) == 8.0+++# ---------------------------------------------------------------------------+# Config knobs and validation+# ---------------------------------------------------------------------------+++def test_retry_delay_knob_defaults(monkeypatch: pytest.MonkeyPatch) -> None:+ """Both new max-delay knobs default to 30.0 seconds."""+ for alias in (+ "SWARM_STREAM_RETRY_DELAY_S",+ "SWARM_STREAM_RETRY_MAX_DELAY_S",+ "VT_STREAM_RETRY_DELAY_S",+ "VT_STREAM_RETRY_MAX_DELAY_S",+ ):+ monkeypatch.delenv(alias, raising=False)++ assert SwarmConfig().swarm_stream_retry_max_delay_s == 30.0+ assert AgentTuningConfig().vt_stream_retry_max_delay_s == 30.0+++def test_swarm_stream_retry_max_below_base_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ """SWARM_STREAM_RETRY_MAX_DELAY_S < SWARM_STREAM_RETRY_DELAY_S is rejected."""+ with pytest.raises(ValidationError):+ SwarmConfig(swarm_stream_retry_delay_s=5.0, swarm_stream_retry_max_delay_s=2.0)+++def test_swarm_worker_retry_pair_still_validated(monkeypatch: pytest.MonkeyPatch) -> None:+ """The pre-existing worker retry max>=base validation is preserved."""+ with pytest.raises(ValidationError):+ SwarmConfig(swarm_worker_retry_base_delay_s=40.0)+++def test_vt_stream_retry_max_below_base_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ """VT_STREAM_RETRY_MAX_DELAY_S < VT_STREAM_RETRY_DELAY_S is rejected."""+ with pytest.raises(ValidationError):+ AgentTuningConfig(vt_stream_retry_delay_s=5.0, vt_stream_retry_max_delay_s=2.0)