Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(providers): tolerate content-filtered LLM responses

shadowinlife022d042c6a03
diff --git a/README.md b/README.md
index 280033695..86ffa805d 100644
--- a/README.md
+++ b/README.md
@@ -569,6 +569,7 @@ Copy `agent/.env.example` to `agent/.env` and uncomment the provider block you w
| `VIBE_TRADING_ENABLE_SHELL_TOOLS` | No | Explicit opt-in for shell-capable tools in remote API/MCP-SSE style deployments |
| `VIBE_TRADING_ALLOWED_FILE_ROOTS` | No | Extra comma-separated roots for document and broker-journal imports |
| `VIBE_TRADING_ALLOWED_RUN_ROOTS` | No | Extra comma-separated roots for generated-code run directories |
+| `CONTENT_FILTER_WARNING_THRESHOLD` | No | Content-filter warning ratio threshold (default 0.05 = 5%). When the ratio of LLM responses blocked by content moderation exceeds this, the run card warns you to switch providers. |
<sub>* Ollama does not require an API key. OpenAI Codex uses ChatGPT OAuth and stores tokens via `oauth-cli-kit`, not in `agent/.env`.</sub>
diff --git a/agent/.env.example b/agent/.env.example
index a3ab5b146..d3d795d00 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -168,3 +168,7 @@ TUSHARE_TOKEN=your-tushare-token
# Frontend SSE idle timeout in seconds before showing "Execution timed out".
# Increase when using slow local models (e.g. Ollama on CPU/limited VRAM).
# VIBE_TRADING_SSE_TIMEOUT=90
+# Content filter warning threshold (default: 0.05 = 5%)
+# When the ratio of LLM responses blocked by content moderation exceeds this
+# threshold, the run card will warn you to switch providers.
+# CONTENT_FILTER_WARNING_THRESHOLD=0.05
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 58c3a3e1c..ad379838c 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -491,6 +491,7 @@ class BaseEngine(ABC):
m,
data_sources=_run_card_data_sources(config, loader),
strategy_path=run_dir / "code" / "signal_engine.py",
+ warnings=config.get("content_filter_warnings") or None,
)
# Print scalar metrics (skip nested dicts for JSON compat)
diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.py
index 133ae40e2..f9d7cf546 100644
--- a/agent/backtest/engines/options_portfolio.py
+++ b/agent/backtest/engines/options_portfolio.py
@@ -529,6 +529,7 @@ def run_options_backtest(
metrics,
data_sources=[str(getattr(loader, "name", config.get("source", "")))],
strategy_path=run_dir / "code" / "signal_engine.py",
+ warnings=config.get("content_filter_warnings") or None,
)
print(json.dumps(metrics, indent=2))
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 3730ec033..626722c16 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -37,6 +37,11 @@ from src.goal.context import (
goal_progress_tuple,
)
from src.providers.chat import ChatLLM, ProviderStreamError
+from src.providers.content_filter import (
+ CONTENT_FILTER_SKIP_MESSAGE,
+ MAX_CONSECUTIVE_CONTENT_FILTER_SKIPS,
+ compute_content_filter_warnings,
+)
from src.tools.background_tools import get_background_manager
from src.tools.redaction import redact_payload
@@ -537,6 +542,9 @@ class AgentLoop:
iteration = 0
final_content = ""
+ content_filter_count = 0
+ consecutive_content_filter_count = 0
+ content_filter_circuit_breaker = False
empty_model_response_iter: int | None = None
llm_usage_summary = _new_llm_usage_summary(self.llm)
goal_continuations = 0
@@ -735,6 +743,32 @@ class AgentLoop:
)
self._emit("thinking_done", {"iter": current_iter, "content": thinking_text[:500]})
+ # Content-filter skip: provider blocked the response — continue
+ # to the next iteration instead of finalising on empty/garbage
+ # content. Checked *before* the tool-call branch so a filtered
+ # response never executes its (likely empty) tool calls.
+ # Use getattr for duck-typed response objects from mock LLMs.
+ if getattr(response, "content_filter_triggered", False):
+ content_filter_count += 1
+ consecutive_content_filter_count += 1
+ if consecutive_content_filter_count >= MAX_CONSECUTIVE_CONTENT_FILTER_SKIPS:
+ trace.write({
+ "type": "content_filter_circuit_breaker",
+ "iter": current_iter,
+ "count": content_filter_count,
+ })
+ content_filter_circuit_breaker = True
+ break
+ trace.write({"type": "content_filter_skipped", "iter": current_iter})
+ messages.append({
+ "role": "system",
+ "content": CONTENT_FILTER_SKIP_MESSAGE,
+ })
+ continue
+
+ # Not filtered — reset the consecutive-skip counter.
+ consecutive_content_filter_count = 0
+
if not response.has_tool_calls:
final_content = response.content or ""
if not final_content:
@@ -880,6 +914,14 @@ class AgentLoop:
final_reason = "cancelled by user"
state_store.mark_failure(run_dir, final_reason)
final_status = "cancelled"
+ elif content_filter_circuit_breaker:
+ final_reason = (
+ f"content_filter_circuit_breaker: "
+ f"{MAX_CONSECUTIVE_CONTENT_FILTER_SKIPS} consecutive LLM "
+ "responses were blocked by content moderation"
+ )
+ state_store.mark_failure(run_dir, final_reason)
+ final_status = "failed"
elif (run_dir / "artifacts" / "metrics.csv").exists() or final_content:
state_store.mark_success(run_dir)
final_status = "success"
@@ -922,6 +964,13 @@ class AgentLoop:
}
if final_reason is not None:
result["reason"] = final_reason
+
+ cf_warnings = compute_content_filter_warnings(
+ content_filter_count, max(1, iteration),
+ )
+ if cf_warnings:
+ result["content_filter_warnings"] = cf_warnings
+
return result
# -- Tool execution with read/write batching --------------------------------
diff --git a/agent/src/preflight.py b/agent/src/preflight.py
index 1321921b2..32eb3bc4f 100644
--- a/agent/src/preflight.py
+++ b/agent/src/preflight.py
@@ -109,7 +109,7 @@ def _check_llm_provider() -> CheckResult:
ping_url = base_url.rstrip("/")
if ping_url.endswith("/v1"):
ping_url = ping_url[:-3]
- resp = requests.get(ping_url, timeout=10)
+ requests.get(ping_url, timeout=10)
return CheckResult(
name=f"LLM ({provider})",
status="ready",
@@ -219,6 +219,21 @@ def _check_akshare() -> CheckResult:
return CheckResult(name="akshare", status="ready", message="installed", impact="")
+def _check_content_filter_threshold() -> CheckResult:
+ """Report the configured content filter warning threshold."""
+ raw = os.getenv("CONTENT_FILTER_WARNING_THRESHOLD", "0.05")
+ try:
+ threshold = float(raw)
+ except (TypeError, ValueError):
+ threshold = 0.05
+ return CheckResult(
+ name="Content Filter Threshold",
+ status="ready",
+ message=f"{threshold:.0%} (set via CONTENT_FILTER_WARNING_THRESHOLD)",
+ impact="",
+ )
+
+
def _check_ccxt() -> CheckResult:
"""Check ccxt availability."""
try:
@@ -262,6 +277,7 @@ def run_preflight(console: Optional[Console] = None) -> List[CheckResult]:
_check_tushare,
_check_akshare,
_check_ccxt,
+ _check_content_filter_threshold,
]
results: List[CheckResult] = []
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.py
index 02535034d..da90fb5be 100644
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@ -11,6 +11,7 @@ import re
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional
+from src.providers.content_filter import is_content_filter_triggered
from src.providers.llm import build_llm
@@ -57,6 +58,9 @@ class LLMResponse:
``{"input_tokens": int, "output_tokens": int, "total_tokens": int}``.
``None`` if the provider did not return usage information; callers
should fall back to a heuristic in that case.
+ content_filter_triggered: ``True`` when the provider blocked the
+ response via content moderation (e.g. DashScope/Qwen content
+ moderation filter, ``finish_reason == "content_filter"``).
"""
content: Optional[str] = None
@@ -64,6 +68,7 @@ class LLMResponse:
reasoning_content: Optional[str] = None
finish_reason: str = "stop"
usage_metadata: Optional[Dict[str, int]] = None
+ content_filter_triggered: bool = False
@property
def has_tool_calls(self) -> bool:
@@ -366,16 +371,22 @@ class ChatLLM:
dsml_tool_calls = [] if native_tool_calls else _parse_dsml_tool_calls(ai_message.content)
tool_calls = native_tool_calls or dsml_tool_calls
+ finish_reason = (
+ "tool_calls"
+ if dsml_tool_calls
+ else _dedupe_finish_reason(
+ ai_message.response_metadata.get("finish_reason", "stop")
+ )
+ )
+ content_filter_triggered = is_content_filter_triggered(
+ ai_message.response_metadata.get("finish_reason")
+ )
+
return LLMResponse(
content="" if dsml_tool_calls else ai_message.content,
tool_calls=tool_calls,
reasoning_content=ai_message.additional_kwargs.get("reasoning_content"),
- finish_reason=(
- "tool_calls"
- if dsml_tool_calls
- else _dedupe_finish_reason(
- ai_message.response_metadata.get("finish_reason", "stop")
- )
- ),
+ finish_reason=finish_reason,
usage_metadata=usage,
+ content_filter_triggered=content_filter_triggered,
)
diff --git a/agent/src/providers/content_filter.py b/agent/src/providers/content_filter.py
new file mode 100644
index 000000000..777928376
--- /dev/null
+++ b/agent/src/providers/content_filter.py
@@ -0,0 +1,107 @@
+"""Content-filter resilience helpers shared by AgentLoop and swarm worker.
+
+When an LLM provider blocks a response via content moderation
+(``finish_reason == "content_filter"``), the caller skips that iteration
+and continues instead of breaking on empty/garbage content. These
+helpers centralise threshold parsing, the warning-string format, and the
+consecutive-skip circuit breaker so both the agent loop and the swarm
+worker stay in sync.
+"""
+
+from __future__ import annotations
+
+import os
+
+CONTENT_FILTER_WARNING_THRESHOLD_ENV = "CONTENT_FILTER_WARNING_THRESHOLD"
+DEFAULT_CONTENT_FILTER_THRESHOLD = 0.05
+
+# Circuit breaker: when this many *consecutive* LLM responses are blocked
+# by content moderation, stop skipping and end the run early instead of
+# burning the whole iteration budget on a provider that is clearly refusing
+# every request.
+MAX_CONSECUTIVE_CONTENT_FILTER_SKIPS = 10
+
+# System message injected after a content-filter hit, telling the model to
+# move on to the next item instead of retrying the blocked content.
+CONTENT_FILTER_SKIP_MESSAGE = (
+ "[SYSTEM] The previous response was blocked by content "
+ "moderation. Skip the current item and continue with the "
+ "next one. Do not retry the same content."
+)
+
+# Gemini surfaces content moderation via uppercase FinishReason enum values
+# (SAFETY, RECITATION, BLOCKLIST, ...) instead of OpenAI's lowercase
+# "content_filter". Google's OpenAI-compatible endpoint passes these through
+# unmapped, so the detector must recognise both vocabularies. See issue #307.
+GEMINI_SAFETY_FINISH_REASONS = frozenset({
+ "SAFETY",
+ "RECITATION",
+ "BLOCKLIST",
+ "PROHIBITED_CONTENT",
+ "SPII",
+ "IMAGE_SAFETY",
+ "IMAGE_PROHIBITED_CONTENT",
+ "IMAGE_RECITATION",
+})
+
+
+def is_content_filter_triggered(finish_reason: object) -> bool:
+ """Return True when ``finish_reason`` indicates content moderation blocked the response.
+
+ Recognises both OpenAI's ``"content_filter"`` and Gemini's uppercase
+ safety FinishReason enum (``"SAFETY"``, ``"RECITATION"``, ...). The
+ comparison is case-insensitive on the Gemini side so a provider that
+ lowercases the value still matches. Non-string values (None, missing)
+ return False.
+ """
+ if not isinstance(finish_reason, str):
+ return False
+ if finish_reason == "content_filter":
+ return True
+ return finish_reason.upper() in GEMINI_SAFETY_FINISH_REASONS
+
+
+def get_content_filter_threshold() -> float:
+ """Return the configured content-filter warning threshold.
+
+ Reads ``CONTENT_FILTER_WARNING_THRESHOLD`` (default 0.05 = 5%).
+ Invalid values fall back to the default instead of crashing the run.
+ """
+ raw = os.getenv(
+ CONTENT_FILTER_WARNING_THRESHOLD_ENV,
+ str(DEFAULT_CONTENT_FILTER_THRESHOLD),
+ )
+ try:
+ return float(raw)
+ except (TypeError, ValueError):
+ return DEFAULT_CONTENT_FILTER_THRESHOLD
+
+
+def compute_content_filter_warnings(
+ content_filter_count: int,
+ total_iterations: int,
+) -> list[str]:
+ """Compute content-filter warnings based on the hit ratio.
+
+ Args:
+ content_filter_count: Number of LLM responses blocked by content
+ moderation during the run.
+ total_iterations: Total number of LLM iterations executed.
+
+ Returns:
+ A list with one warning string when the ratio exceeds the
+ configured threshold, otherwise an empty list.
+ """
+ if content_filter_count == 0:
+ return []
+ denominator = max(1, total_iterations)
+ ratio = content_filter_count / denominator
+ threshold = get_content_filter_threshold()
+ if ratio > threshold:
+ return [
+ f"{content_filter_count}/{denominator} LLM responses"
+ f" ({ratio:.0%}) were blocked by content moderation."
+ " Consider switching to a provider with less aggressive"
+ " filtering for event-driven analysis."
+ ]
+ return []
diff --git a/agent/src/providers/openai_codex.py b/agent/src/providers/openai_codex.py
index 05b5690a9..8faecec8b 100644
--- a/agent/src/providers/openai_codex.py
+++ b/agent/src/providers/openai_codex.py
@@ -257,6 +257,7 @@ def _map_finish_reason(status: str | None) -> str:
"incomplete": "length",
"failed": "error",
"cancelled": "error",
+ "content_filter": "content_filter",
}.get(status or "completed", "stop")
diff --git a/agent/src/swarm/models.py b/agent/src/swarm/models.py
index 95ddc1273..f73963449 100644
--- a/agent/src/swarm/models.py
+++ b/agent/src/swarm/models.py
@@ -213,3 +213,4 @@ class WorkerResult(BaseModel):
error: str | None = None
input_tokens: int = 0
output_tokens: int = 0
+ content_filter_warnings: list[str] = Field(default_factory=list)
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index c7d60e936..e37fcb9a5 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -20,6 +20,11 @@ from src.agent.skills import SkillsLoader
from src.agent.tools import ToolRegistry
from src.config.schema import AgentConfig
from src.providers.chat import ChatLLM, LLMResponse, ProviderStreamError
+from src.providers.content_filter import (
+ CONTENT_FILTER_SKIP_MESSAGE,
+ MAX_CONSECUTIVE_CONTENT_FILTER_SKIPS,
+ compute_content_filter_warnings,
+)
from src.swarm.models import (
SwarmAgentSpec,
SwarmEvent,
@@ -392,6 +397,8 @@ def run_worker(
_KEEP_RECENT_TOOLS = 3
data_tool_calls = 0
+ content_filter_count = 0
+ consecutive_content_filter_count = 0
for iteration in range(max_iterations):
# Microcompact: clear old tool results to prevent token bloat
@@ -417,6 +424,9 @@ def run_worker(
iterations=iteration,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
+ content_filter_warnings=compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ ),
)
# Check token estimate
@@ -433,6 +443,9 @@ def run_worker(
iterations=iteration,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
+ content_filter_warnings=compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ ),
)
# Inject wrap-up nudge when approaching iteration limit
@@ -535,6 +548,9 @@ def run_worker(
error=error_msg,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
+ content_filter_warnings=compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ ),
)
# Accumulate token counts
@@ -546,6 +562,52 @@ def run_worker(
if response.content and len(response.content.strip()) > 20:
last_assistant_content = response.content
+ # Content-filter skip: provider blocked the response — continue to
+ # the next iteration instead of finalising on empty/garbage content.
+ if response.content_filter_triggered:
+ content_filter_count += 1
+ consecutive_content_filter_count += 1
+ if consecutive_content_filter_count >= MAX_CONSECUTIVE_CONTENT_FILTER_SKIPS:
+ _emit(
+ event_callback,
+ "content_filter_circuit_breaker",
+ agent_id,
+ task_id,
+ {"count": content_filter_count},
+ )
+ summary = _resolve_summary(artifact_dir, last_assistant_content or "")
+ _write_summary(artifact_dir, summary)
+ return WorkerResult(
+ status="failed",
+ summary=summary,
+ artifact_paths=_collect_artifacts(artifact_dir),
+ iterations=iteration + 1,
+ error=(
+ f"content_filter_circuit_breaker: "
+ f"{MAX_CONSECUTIVE_CONTENT_FILTER_SKIPS} consecutive "
+ "LLM responses were blocked by content moderation"
+ ),
+ input_tokens=total_input_tokens,
+ output_tokens=total_output_tokens,
+ content_filter_warnings=compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ ),
+ )
+ _emit(
+ event_callback,
+ "content_filter_skipped",
+ agent_id,
+ task_id,
+ {"iteration": iteration, "content_filter_count": content_filter_count},
+ )
+ messages.append({
+ "role": "system",
+ "content": CONTENT_FILTER_SKIP_MESSAGE,
+ })
+ continue
+
+ consecutive_content_filter_count = 0
+
# If no tool calls, this is the final response
if not response.has_tool_calls:
summary = response.content or last_assistant_content or "(no summary)"
@@ -568,6 +630,9 @@ def run_worker(
error=f"output contract not met: {reason}",
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
+ content_filter_warnings=compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ ),
)
_emit(event_callback, "worker_completed", agent_id, task_id, {"iterations": iteration + 1})
return WorkerResult(
@@ -577,6 +642,9 @@ def run_worker(
iterations=iteration + 1,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
+ content_filter_warnings=compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ ),
)
# Append assistant message with tool calls
@@ -633,6 +701,11 @@ def run_worker(
ContextBuilder.format_tool_result(tc.id, tc.name, result[:10_000])
)
+ # Content filter ratio tracking
+ content_filter_warnings = compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ )
+
# Hit iteration limit — use last meaningful content as summary
summary = _best_summary(messages, last_assistant_content) or f"Worker hit iteration limit ({max_iterations} iterations)"
summary = _resolve_summary(artifact_dir, summary)
@@ -655,6 +728,7 @@ def run_worker(
error=f"hit iteration limit without a valid deliverable: {reason}",
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
+ content_filter_warnings=content_filter_warnings,
)
_emit(event_callback, "worker_iteration_limit", agent_id, task_id)
return WorkerResult(
@@ -664,6 +738,7 @@ def run_worker(
iterations=max_iterations,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
+ content_filter_warnings=content_filter_warnings,
)
diff --git a/agent/tests/test_agent_loop_content_filter.py b/agent/tests/test_agent_loop_content_filter.py
new file mode 100644
index 000000000..6a6407c0f
--- /dev/null
+++ b/agent/tests/test_agent_loop_content_filter.py
@@ -0,0 +1,270 @@
+"""AgentLoop content-filter skip-and-continue behavior.
+
+When the LLM returns a content-filtered response (content_filter_triggered=True),
+the agent loop should skip that iteration and continue instead of breaking.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Callable
+
+import pytest
+
+from src.providers.chat import LLMResponse, ToolCallRequest
+
+
+class _ContentFilterLoopLLM:
+ """LLM stub returning scripted content_filter_triggered responses."""
+
+ def __init__(
+ self,
+ filter_count: int,
+ final_content: str = "Final answer.",
+ ) -> None:
+ self._filter_remaining = filter_count
+ self._final_content = final_content
+ self.calls = 0
+ self.messages_history: list[list[dict[str, Any]]] = []
+
+ 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,
+ should_cancel: Callable[[], bool] | None = None,
+ ) -> LLMResponse:
+ self.calls += 1
+ self.messages_history.append(list(messages))
+ if self._filter_remaining > 0:
+ self._filter_remaining -= 1
+ return LLMResponse(
+ content="",
+ content_filter_triggered=True,
+ )
+ if on_text_chunk:
+ on_text_chunk(self._final_content)
+ return LLMResponse(content=self._final_content)
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:
+ return LLMResponse(content="")
+
+
+class _EmptyResponseLoopLLM:
+ """LLM stub returning empty content with no content filter."""
+
+ def __init__(self) -> None:
+ 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,
+ should_cancel: Callable[[], bool] | None = None,
+ ) -> LLMResponse:
+ self.calls += 1
+ return LLMResponse(content="", content_filter_triggered=False)
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:
+ return LLMResponse(content="")
+
+
+def _run(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ llm: Any,
+ max_iterations: int = 5,
+) -> dict[str, Any]:
+ from src.agent.loop import AgentLoop
+ from src.memory.persistent import PersistentMemory
+ from src.tools import build_registry
+
+ pm = PersistentMemory()
+ agent = AgentLoop(
+ registry=build_registry(persistent_memory=pm, include_shell_tools=False),
+ llm=llm,
+ max_iterations=max_iterations,
+ 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")
+
+
+def _read_trace(run_dir: str) -> list[dict[str, Any]]:
+ from src.agent.trace import TraceWriter
+
+ return TraceWriter.read(Path(run_dir))
+
+
+def test_content_filter_skip_and_continue(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Content filter on first call, then normal response -> loop continues and succeeds."""
+ llm = _ContentFilterLoopLLM(filter_count=1, final_content="Final answer.")
+
+ result = _run(monkeypatch, tmp_path, llm)
+
+ assert result["status"] == "success"
+ assert result["content"] == "Final answer."
+ assert llm.calls == 2
+
+
+def test_content_filter_trace_entry(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Trace contains content_filter_skipped entry when filter is triggered."""
+ llm = _ContentFilterLoopLLM(filter_count=1, final_content="Done.")
+
+ result = _run(monkeypatch, tmp_path, llm)
+
+ trace = _read_trace(result["run_dir"])
+ filter_entries = [e for e in trace if e.get("type") == "content_filter_skipped"]
+ assert len(filter_entries) == 1
+ assert "iter" in filter_entries[0]
+
+
+def test_content_filter_injects_system_message(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """System message is injected into messages after content filter hit."""
+ llm = _ContentFilterLoopLLM(filter_count=1, final_content="Done.")
+
+ _run(monkeypatch, tmp_path, llm)
+
+ assert llm.calls == 2
+ messages_on_second_call = llm.messages_history[1]
+ system_messages = [
+ m for m in messages_on_second_call
+ if "content moderation" in str(m.get("content", ""))
+ ]
+ assert len(system_messages) == 1
+ assert "[SYSTEM]" in system_messages[0]["content"]
+
+
+def test_multiple_content_filter_hits(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Multiple content filter hits are all traced and counted."""
+ llm = _ContentFilterLoopLLM(filter_count=3, final_content="Finally.")
+
+ result = _run(monkeypatch, tmp_path, llm)
+
+ assert result["status"] == "success"
+ assert result["content"] == "Finally."
+ assert llm.calls == 4
+
+ trace = _read_trace(result["run_dir"])
+ filter_entries = [e for e in trace if e.get("type") == "content_filter_skipped"]
+ assert len(filter_entries) == 3
+
+
+def test_empty_content_no_filter_still_breaks(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Empty content with content_filter_triggered=False triggers existing break."""
+ llm = _EmptyResponseLoopLLM()
+
+ result = _run(monkeypatch, tmp_path, llm)
+
+ assert result["status"] == "failed"
+ assert "empty_model_response" in result.get("reason", "")
+ assert llm.calls == 1
+
+ trace = _read_trace(result["run_dir"])
+ empty_entries = [e for e in trace if e.get("type") == "empty_model_response"]
+ assert len(empty_entries) == 1
+ filter_entries = [e for e in trace if e.get("type") == "content_filter_skipped"]
+ assert len(filter_entries) == 0
+
+
+class _RatioFilterLoopLLM:
+ """LLM stub producing content_filter on first N calls, tool calls to keep
+ the loop going, then final content on the last call.
+
+ Call pattern (1-indexed):
+ calls 1..filter_count → content_filter_triggered
+ calls filter_count+1..total-1 → fake tool call (keeps loop alive)
+ call total → final content (breaks loop)
+ """
+
+ def __init__(
+ self,
+ filter_count: int,
+ total_iterations: int,
+ final_content: str = "Final answer.",
+ ) -> None:
+ self._filter_count = filter_count
+ self._total = total_iterations
+ 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,
+ should_cancel: Callable[[], bool] | None = None,
+ ) -> LLMResponse:
+ self.calls += 1
+ if self.calls <= self._filter_count:
+ return LLMResponse(content="", content_filter_triggered=True)
+ if self.calls < self._total:
+ return LLMResponse(
+ content="",
+ tool_calls=[
+ ToolCallRequest(
+ id=f"call_{self.calls}", name="_noop", arguments={}
+ )
+ ],
+ )
+ if on_text_chunk:
+ on_text_chunk(self._final_content)
+ return LLMResponse(content=self._final_content)
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:
+ return LLMResponse(content="")
+
+
+def test_content_filter_warning_in_result(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """5/10 iterations hit content_filter (50%) → warning surfaced in result."""
+ llm = _RatioFilterLoopLLM(filter_count=5, total_iterations=10)
+
+ result = _run(monkeypatch, tmp_path, llm, max_iterations=10)
+
+ assert "content_filter_warnings" in result
+ warnings = result["content_filter_warnings"]
+ assert len(warnings) == 1
+ assert "50%" in warnings[0]
+ assert "provider" in warnings[0].lower()
+
+
+def test_content_filter_no_warning_below_threshold(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """0/10 iterations hit content_filter → no warning key in result."""
+ llm = _ContentFilterLoopLLM(filter_count=0, final_content="Clean run.")
+
+ result = _run(monkeypatch, tmp_path, llm, max_iterations=10)
+
+ assert "content_filter_warnings" not in result
+
+
+def test_content_filter_circuit_breaker(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """10 consecutive content filters trip the circuit breaker → run fails early."""
+ llm = _ContentFilterLoopLLM(filter_count=15, final_content="Never reached.")
+
+ result = _run(monkeypatch, tmp_path, llm, max_iterations=20)
+
+ assert result["status"] == "failed"
+ assert "circuit_breaker" in result.get("reason", "")
+ assert result["iterations"] <= 11
diff --git a/agent/tests/test_chat_llm_streaming.py b/agent/tests/test_chat_llm_streaming.py
index 963e850b5..bad813d60 100644
--- a/agent/tests/test_chat_llm_streaming.py
+++ b/agent/tests/test_chat_llm_streaming.py
@@ -243,3 +243,25 @@ def test_provider_stream_error_retryable_classification(
err = ProviderStreamError(provider="kimi", model="kimi-k2.6", original=original)
assert err.status_code == status_code
assert err.retryable is expected
+
+
+def test_content_filter_triggered_flag() -> None:
+ """content_filter finish_reason sets content_filter_triggered=True."""
+ response = ChatLLM._parse_response(
+ _FakeChunk(content="", finish_reason="content_filter")
+ )
+
+ assert response.content == ""
+ assert response.finish_reason == "content_filter"
+ assert response.content_filter_triggered is True
+
+
+def test_content_filter_triggered_flag_false_on_stop() -> None:
+ """Normal stop reason leaves content_filter_triggered=False."""
+ response = ChatLLM._parse_response(
+ _FakeChunk(content="text", finish_reason="stop")
+ )
+
+ assert response.content == "text"
+ assert response.finish_reason == "stop"
+ assert response.content_filter_triggered is False
diff --git a/agent/tests/test_content_filter_e2e.py b/agent/tests/test_content_filter_e2e.py
new file mode 100644
index 000000000..44d5e7fa3
--- /dev/null
+++ b/agent/tests/test_content_filter_e2e.py
@@ -0,0 +1,220 @@
+"""E2E content-filter resilience: detection -> skip -> ratio -> warning -> trace.
+
+Simulates a full agent run where semiconductor/geopolitics news triggers
+DashScope/Qwen content moderation on some LLM calls (e.g. event-driven
+backtest on 159516.SZ). Verifies the entire pipeline:
+
+1. Run completes successfully despite content-filter hits.
+2. ``content_filter_warnings`` surfaced in result when ratio > 5 %.
+3. Trace contains exactly the expected ``content_filter_skipped`` entries.
+4. Warning message format includes ratio, "content moderation", and provider
+ recommendation.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Callable
+
+import pytest
+
+from src.providers.chat import LLMResponse, ToolCallRequest
+
+
+# ---------------------------------------------------------------------------
+# LLM stubs
+# ---------------------------------------------------------------------------
+
+
+class _InterleavedFilterLLM:
+ """Scripted LLM stub producing an interleaved content-filter pattern.
+
+ Call pattern (1-indexed):
+ call 1 -> content_filter_triggered=True
+ call 2 -> tool call (_noop) to keep the loop alive
+ call 3 -> content_filter_triggered=True
+ call 4 -> tool call (_noop) to keep the loop alive
+ call 5 -> final content (breaks the loop)
+
+ This gives 2 content-filter hits out of 5 iterations (40 %).
+ """
+
+ def __init__(self, final_content: str = "Final analysis complete.") -> None:
+ 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,
+ should_cancel: Callable[[], bool] | None = None,
+ ) -> LLMResponse:
+ self.calls += 1
+ # Calls 1 and 3: content filter triggered
+ if self.calls in (1, 3):
+ return LLMResponse(content="", content_filter_triggered=True)
+ # Calls 2 and 4: tool call to keep the loop going
+ if self.calls in (2, 4):
+ return LLMResponse(
+ content="",
+ tool_calls=[
+ ToolCallRequest(
+ id=f"call_{self.calls}", name="_noop", arguments={}
+ )
+ ],
+ )
+ # Call 5+: final answer
+ if on_text_chunk:
+ on_text_chunk(self._final_content)
+ return LLMResponse(content=self._final_content)
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:
+ return LLMResponse(content="")
+
+
+class _CleanRunLLM:
+ """Scripted LLM stub producing zero content-filter hits over 5 calls.
+
+ Call pattern:
+ calls 1-4 -> tool call (_noop) to keep the loop alive
+ call 5 -> final content
+ """
+
+ def __init__(self, final_content: str = "Clean analysis complete.") -> None:
+ 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,
+ should_cancel: Callable[[], bool] | None = None,
+ ) -> LLMResponse:
+ self.calls += 1
+ if self.calls < 5:
+ return LLMResponse(
+ content="",
+ tool_calls=[
+ ToolCallRequest(
+ id=f"call_{self.calls}", name="_noop", arguments={}
+ )
+ ],
+ )
+ if on_text_chunk:
+ on_text_chunk(self._final_content)
+ return LLMResponse(content=self._final_content)
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:
+ return LLMResponse(content="")
+
+
+# ---------------------------------------------------------------------------
+# Harness helpers
+# ---------------------------------------------------------------------------
+
+
+def _run(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ llm: Any,
+ max_iterations: int = 5,
+) -> dict[str, Any]:
+ """Build an AgentLoop, wire up a scratch run_dir, and execute."""
+ from src.agent.loop import AgentLoop
+ from src.memory.persistent import PersistentMemory
+ from src.tools import build_registry
+
+ pm = PersistentMemory()
+ agent = AgentLoop(
+ registry=build_registry(persistent_memory=pm, include_shell_tools=False),
+ llm=llm,
+ max_iterations=max_iterations,
+ 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="Analyze 159516.SZ with recent news sentiment")
+
+
+def _read_trace(run_dir: str) -> list[dict[str, Any]]:
+ """Read trace.jsonl entries from a run directory."""
+ from src.agent.trace import TraceWriter
+
+ return TraceWriter.read(Path(run_dir))
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+def test_e2e_content_filter_pipeline(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """2/5 iterations hit content_filter (40 %) -> full pipeline verified.
+
+ Asserts:
+ 1. Run completes successfully.
+ 2. ``content_filter_warnings`` present in result dict.
+ 3. Trace contains exactly 2 ``content_filter_skipped`` entries.
+ 4. Warning message contains "40%", "content moderation", and "provider".
+ """
+ llm = _InterleavedFilterLLM()
+
+ result = _run(monkeypatch, tmp_path, llm)
+
+ # 1. Run completes successfully
+ assert result["status"] == "success"
+ assert result["content"] == "Final analysis complete."
+ assert llm.calls == 5
+
+ # 2. Warning surfaced because 2/5 = 40% > 5% threshold
+ assert "content_filter_warnings" in result
+ warnings = result["content_filter_warnings"]
+ assert len(warnings) == 1
+
+ # 3. Trace contains exactly 2 content_filter_skipped entries
+ trace = _read_trace(result["run_dir"])
+ filter_entries = [e for e in trace if e.get("type") == "content_filter_skipped"]
+ assert len(filter_entries) == 2
+ # Each entry carries an iter key
+ assert all("iter" in entry for entry in filter_entries)
+
+ # 4. Warning message format
+ warning = warnings[0]
+ assert "40%" in warning
+ assert "content moderation" in warning
+ assert "provider" in warning.lower()
+
+
+def test_e2e_no_content_filter_clean_run(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """0/5 iterations hit content_filter -> no warnings, no trace entries.
+
+ Asserts:
+ 1. Run completes successfully.
+ 2. No ``content_filter_warnings`` key in result dict.
+ 3. No ``content_filter_skipped`` entries in trace.
+ """
+ llm = _CleanRunLLM()
+
+ result = _run(monkeypatch, tmp_path, llm)
+
+ # 1. Run completes successfully
+ assert result["status"] == "success"
+ assert result["content"] == "Clean analysis complete."
+ assert llm.calls == 5
+
+ # 2. No warnings
+ assert "content_filter_warnings" not in result
+
+ # 3. No content_filter_skipped trace entries
+ trace = _read_trace(result["run_dir"])
+ filter_entries = [e for e in trace if e.get("type") == "content_filter_skipped"]
+ assert len(filter_entries) == 0
diff --git a/agent/tests/test_content_filter_gemini_detection.py b/agent/tests/test_content_filter_gemini_detection.py
new file mode 100644
index 000000000..0250c4ddb
--- /dev/null
+++ b/agent/tests/test_content_filter_gemini_detection.py
@@ -0,0 +1,83 @@
+"""Gemini content-filter detection regression tests.
+
+Gemini surfaces content moderation via uppercase FinishReason enum values
+(SAFETY, RECITATION, BLOCKLIST, ...) instead of OpenAI's lowercase
+"content_filter". Google's OpenAI-compatible endpoint passes these through
+unmapped, so ``_parse_response`` must recognise both vocabularies — otherwise
+the circuit breaker / warning pipeline from issue #307 silently fails for the
+Gemini provider.
+
+Response fixtures sourced from:
+- google-gemini/deprecated-generative-ai-python tests (Apache-2.0)
+- langchain-ai/langchain-google integration tests (MIT)
+- firebase/flutterfire response parsing tests (BSD-3-Clause)
+"""
+
+from __future__ import annotations
+
+import pytest
+from langchain_core.messages import AIMessage
+
+from src.providers.chat import ChatLLM
+from src.providers.content_filter import (
+ GEMINI_SAFETY_FINISH_REASONS,
+ is_content_filter_triggered,
+)
+
+
[email protected]("reason", sorted(GEMINI_SAFETY_FINISH_REASONS))
+def test_helper_detects_each_gemini_safety_reason(reason: str) -> None:
+ assert is_content_filter_triggered(reason) is True
+
+
+def test_helper_detects_openai_content_filter() -> None:
+ assert is_content_filter_triggered("content_filter") is True
+
+
+def test_helper_case_insensitive() -> None:
+ assert is_content_filter_triggered("safety") is True
+ assert is_content_filter_triggered("Recitation") is True
+
+
+ "reason", ["stop", "length", "tool_calls", "end_turn", "max_tokens", ""]
+)
+def test_helper_rejects_non_filter_reasons(reason: str) -> None:
+ assert is_content_filter_triggered(reason) is False
+
+
[email protected]("value", [None, 123, [], {}])
+def test_helper_handles_non_string(value: object) -> None:
+ assert is_content_filter_triggered(value) is False
+
+
+def test_parse_response_detects_gemini_safety() -> None:
+ ai_msg = AIMessage(content="", response_metadata={"finish_reason": "SAFETY"})
+ resp = ChatLLM._parse_response(ai_msg)
+ assert resp.content_filter_triggered is True
+
+
+def test_parse_response_detects_gemini_recitation() -> None:
+ ai_msg = AIMessage(content="", response_metadata={"finish_reason": "RECITATION"})
+ resp = ChatLLM._parse_response(ai_msg)
+ assert resp.content_filter_triggered is True
+
+
+def test_parse_response_openai_content_filter_regression() -> None:
+ ai_msg = AIMessage(
+ content="", response_metadata={"finish_reason": "content_filter"}
+ )
+ resp = ChatLLM._parse_response(ai_msg)
+ assert resp.content_filter_triggered is True
+
+
+def test_parse_response_normal_stop_not_triggered() -> None:
+ ai_msg = AIMessage(content="hello", response_metadata={"finish_reason": "stop"})
+ resp = ChatLLM._parse_response(ai_msg)
+ assert resp.content_filter_triggered is False
+
+
+def test_parse_response_missing_finish_reason_not_triggered() -> None:
+ ai_msg = AIMessage(content="hello", response_metadata={})
+ resp = ChatLLM._parse_response(ai_msg)
+ assert resp.content_filter_triggered is False
diff --git a/agent/tests/test_preflight.py b/agent/tests/test_preflight.py
index 75b923a70..a4ac12f52 100644
--- a/agent/tests/test_preflight.py
+++ b/agent/tests/test_preflight.py
@@ -26,3 +26,26 @@ def test_akshare_check_skips_when_missing(monkeypatch) -> None:
assert result.status == "skipped"
assert result.message == "package not installed"
+
+
+def test_content_filter_threshold_check(monkeypatch) -> None:
+ """Content Filter Threshold row must appear in preflight output."""
+ monkeypatch.setenv("CONTENT_FILTER_WARNING_THRESHOLD", "0.10")
+
+ result = preflight._check_content_filter_threshold()
+
+ assert result.name == "Content Filter Threshold"
+ assert result.status == "ready"
+ assert "10%" in result.message
+ assert "CONTENT_FILTER_WARNING_THRESHOLD" in result.message
+
+
+def test_content_filter_threshold_default(monkeypatch) -> None:
+ """Default threshold is 5% when env var is unset."""
+ monkeypatch.delenv("CONTENT_FILTER_WARNING_THRESHOLD", raising=False)
+
+ result = preflight._check_content_filter_threshold()
+
+ assert result.name == "Content Filter Threshold"
+ assert result.status == "ready"
+ assert "5%" in result.message
diff --git a/agent/tests/test_run_card_content_filter.py b/agent/tests/test_run_card_content_filter.py
new file mode 100644
index 000000000..4a121d644
--- /dev/null
+++ b/agent/tests/test_run_card_content_filter.py
@@ -0,0 +1,187 @@
+"""Tests that content_filter_warnings from config flows through to run_card.json warnings."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pandas as pd
+
+from backtest.run_card import write_run_card
+
+
+def test_content_filter_warnings_surfaced_in_run_card(tmp_path: Path) -> None:
+ """When config carries content_filter_warnings, run_card.json warnings must contain them."""
+ config = {
+ "codes": ["SPY"],
+ "start_date": "2025-01-01",
+ "end_date": "2025-01-06",
+ "source": "yfinance",
+ "engine": "options",
+ "content_filter_warnings": [
+ "3/10 LLM responses (30%) were blocked by content moderation."
+ " Consider switching to a provider with less aggressive filtering"
+ " for event-driven analysis."
+ ],
+ }
+ warnings = config.get("content_filter_warnings") or None
+
+ card = write_run_card(
+ tmp_path,
+ config,
+ {"sharpe": 1.0},
+ warnings=warnings,
+ )
+
+ json_path = tmp_path / "run_card.json"
+ loaded = json.loads(json_path.read_text(encoding="utf-8"))
+
+ assert loaded["warnings"] == card["warnings"]
+ assert len(loaded["warnings"]) == 1
+ assert "30%" in loaded["warnings"][0]
+ assert "content moderation" in loaded["warnings"][0]
+
+
+def test_no_content_filter_warnings_yields_empty_warnings(tmp_path: Path) -> None:
+ """When config has no content_filter_warnings, run_card.json warnings is empty."""
+ config = {
+ "codes": ["AAPL"],
+ "start_date": "2025-01-01",
+ "end_date": "2025-02-01",
+ "source": "yfinance",
+ "engine": "daily",
+ }
+ warnings = config.get("content_filter_warnings") or None
+
+ write_run_card(
+ tmp_path,
+ config,
+ {"sharpe": 1.2},
+ warnings=warnings,
+ )
+
+ json_path = tmp_path / "run_card.json"
+ loaded = json.loads(json_path.read_text(encoding="utf-8"))
+
+ assert loaded["warnings"] == []
+
+
+def test_options_engine_surfaces_content_filter_warnings(tmp_path: Path) -> None:
+ """End-to-end: options engine passes config content_filter_warnings to run_card."""
+ from backtest.engines.options_portfolio import run_options_backtest
+
+ dates = pd.bdate_range("2025-01-01", periods=4)
+ bars = pd.DataFrame(
+ {
+ "open": [100.0, 101.0, 102.0, 103.0],
+ "high": [101.0, 102.0, 103.0, 104.0],
+ "low": [99.0, 100.0, 101.0, 102.0],
+ "close": [100.5, 101.5, 102.5, 103.5],
+ "volume": [1000, 1100, 1200, 1300],
+ },
+ index=dates,
+ )
+
+ class FakeLoader:
+ name = "yfinance"
+
+ def fetch(self, codes, start_date, end_date):
+ return {"SPY": bars.copy()}
+
+ class SignalEngine:
+ def generate(self, data_map):
+ return [
+ {
+ "date": "2025-01-01",
+ "action": "open",
+ "underlying": "SPY",
+ "legs": [{"type": "call", "strike": 101.0, "expiry": "2025-03-21", "qty": 1}],
+ },
+ {
+ "date": "2025-01-03",
+ "action": "close",
+ "underlying": "SPY",
+ "legs": [{"type": "call", "strike": 101.0, "expiry": "2025-03-21", "qty": 1}],
+ },
+ ]
+
+ run_options_backtest(
+ {
+ "codes": ["SPY"],
+ "start_date": "2025-01-01",
+ "end_date": "2025-01-06",
+ "source": "yfinance",
+ "engine": "options",
+ "initial_cash": 100_000,
+ "content_filter_warnings": [
+ "2/10 LLM responses (20%) were blocked by content moderation."
+ " Consider switching to a provider with less aggressive filtering"
+ " for event-driven analysis."
+ ],
+ },
+ FakeLoader(),
+ SignalEngine(),
+ tmp_path,
+ )
+
+ card = json.loads((tmp_path / "run_card.json").read_text(encoding="utf-8"))
+ assert len(card["warnings"]) == 1
+ assert "20%" in card["warnings"][0]
+ assert "content moderation" in card["warnings"][0]
+
+
+def test_options_engine_no_warnings_yields_empty(tmp_path: Path) -> None:
+ """End-to-end: options engine without content_filter_warnings produces empty warnings."""
+ from backtest.engines.options_portfolio import run_options_backtest
+
+ dates = pd.bdate_range("2025-01-01", periods=4)
+ bars = pd.DataFrame(
+ {
+ "open": [100.0, 101.0, 102.0, 103.0],
+ "high": [101.0, 102.0, 103.0, 104.0],
+ "low": [99.0, 100.0, 101.0, 102.0],
+ "close": [100.5, 101.5, 102.5, 103.5],
+ "volume": [1000, 1100, 1200, 1300],
+ },
+ index=dates,
+ )
+
+ class FakeLoader:
+ name = "yfinance"
+
+ def fetch(self, codes, start_date, end_date):
+ return {"SPY": bars.copy()}
+
+ class SignalEngine:
+ def generate(self, data_map):
+ return [
+ {
+ "date": "2025-01-01",
+ "action": "open",
+ "underlying": "SPY",
+ "legs": [{"type": "call", "strike": 101.0, "expiry": "2025-03-21", "qty": 1}],
+ },
+ {
+ "date": "2025-01-03",
+ "action": "close",
+ "underlying": "SPY",
+ "legs": [{"type": "call", "strike": 101.0, "expiry": "2025-03-21", "qty": 1}],
+ },
+ ]
+
+ run_options_backtest(
+ {
+ "codes": ["SPY"],
+ "start_date": "2025-01-01",
+ "end_date": "2025-01-06",
+ "source": "yfinance",
+ "engine": "options",
+ "initial_cash": 100_000,
+ },
+ FakeLoader(),
+ SignalEngine(),
+ tmp_path,
+ )
+
+ card = json.loads((tmp_path / "run_card.json").read_text(encoding="utf-8"))
+ assert card["warnings"] == []
diff --git a/agent/tests/test_swarm_worker_content_filter.py b/agent/tests/test_swarm_worker_content_filter.py
new file mode 100644
index 000000000..6718e15db
--- /dev/null
+++ b/agent/tests/test_swarm_worker_content_filter.py
@@ -0,0 +1,220 @@
+"""Tests for content-filter skip logic in run_worker.
+
+When the LLM returns ``content_filter_triggered=True``, the worker should
+skip that iteration and continue instead of finalizing on empty/garbage
+content. The worker injects a system message telling the agent to move on,
+emits a ``content_filter_skipped`` event, and increments an internal counter.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import patch
+
+from src.providers.chat import LLMResponse, ToolCallRequest
+from src.swarm.models import SwarmAgentSpec, SwarmEvent, SwarmTask, WorkerResult
+import src.swarm.worker as worker_mod
+from src.swarm.worker import run_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:
+ def get_definitions(self) -> list[dict]:
+ return []
+
+ def execute(self, name: str, args: dict) -> str:
+ return "ok"
+
+ def get(self, name: str):
+ return None
+
+
+class _ScriptedChatLLM:
+ """Scripted ChatLLM that returns queued responses in order."""
+
+ def __init__(self, responses: list[LLMResponse]) -> None:
+ self._responses = list(responses)
+ self.calls = 0
+ self.received_messages: list[list[dict]] = []
+
+ def __call__(self, *args, **kwargs) -> "_ScriptedChatLLM":
+ return self
+
+ def stream_chat(
+ self, messages, tools=None, on_text_chunk=None, timeout=None
+ ) -> LLMResponse:
+ self.calls += 1
+ self.received_messages.append(list(messages))
+ if self._responses:
+ return self._responses.pop(0)
+ return LLMResponse(content=FINAL_TEXT)
+
+
+def _run(
+ monkeypatch,
+ tmp_path: Path,
+ llm: _ScriptedChatLLM,
+ event_callback=None,
+ max_iterations: int = 5,
+) -> WorkerResult:
+ monkeypatch.setattr(worker_mod, "_STREAM_RETRY_DELAY_S", 0.0)
+ agent = SwarmAgentSpec(
+ id="analyst",
+ role="Synthesis analyst",
+ system_prompt="You synthesize upstream findings.",
+ tools=[],
+ skills=[],
+ max_iterations=max_iterations,
+ timeout_seconds=60,
+ )
+ task = 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),
+ ):
+ return run_worker(
+ agent_spec=agent,
+ task=task,
+ upstream_summaries={},
+ user_vars={},
+ run_dir=tmp_path,
+ event_callback=event_callback,
+ )
+
+
+def test_content_filter_skipped_and_worker_continues(monkeypatch, tmp_path):
+ """Content-filtered response is skipped; worker completes on next iteration."""
+ events: list[SwarmEvent] = []
+ llm = _ScriptedChatLLM([
+ LLMResponse(content="", content_filter_triggered=True),
+ LLMResponse(content=FINAL_TEXT),
+ ])
+
+ result = _run(monkeypatch, tmp_path, llm, event_callback=events.append)
+
+ assert result.status == "completed"
+ assert result.error is None
+ assert llm.calls == 2
+
+
+def test_content_filter_event_emitted(monkeypatch, tmp_path):
+ """A content_filter_skipped event is emitted with iteration and count."""
+ events: list[SwarmEvent] = []
+ llm = _ScriptedChatLLM([
+ LLMResponse(content="", content_filter_triggered=True),
+ LLMResponse(content=FINAL_TEXT),
+ ])
+
+ _run(monkeypatch, tmp_path, llm, event_callback=events.append)
+
+ cf_events = [e for e in events if e.type == "content_filter_skipped"]
+ assert len(cf_events) == 1
+ assert cf_events[0].agent_id == "analyst"
+ assert cf_events[0].task_id == "t1"
+ assert cf_events[0].data["iteration"] == 0
+ assert cf_events[0].data["content_filter_count"] == 1
+
+
+def test_content_filter_system_message_injected(monkeypatch, tmp_path):
+ """A system message is injected after content-filter skip."""
+ llm = _ScriptedChatLLM([
+ LLMResponse(content="", content_filter_triggered=True),
+ LLMResponse(content=FINAL_TEXT),
+ ])
+
+ _run(monkeypatch, tmp_path, llm)
+
+ assert llm.calls == 2
+ second_call_messages = llm.received_messages[1]
+ system_msgs = [
+ m for m in second_call_messages
+ if m.get("role") == "system" and "content moderation" in m.get("content", "")
+ ]
+ assert len(system_msgs) == 1
+
+
+def test_multiple_content_filters_increment_counter(monkeypatch, tmp_path):
+ """Multiple consecutive content filters each increment the counter."""
+ events: list[SwarmEvent] = []
+ llm = _ScriptedChatLLM([
+ LLMResponse(content="", content_filter_triggered=True),
+ LLMResponse(content="", content_filter_triggered=True),
+ LLMResponse(content=FINAL_TEXT),
+ ])
+
+ result = _run(monkeypatch, tmp_path, llm, event_callback=events.append)
+
+ assert result.status == "completed"
+ assert llm.calls == 3
+ cf_events = [e for e in events if e.type == "content_filter_skipped"]
+ assert len(cf_events) == 2
+ assert cf_events[0].data["content_filter_count"] == 1
+ assert cf_events[1].data["content_filter_count"] == 2
+
+
+def test_no_content_filter_uses_existing_finalization(monkeypatch, tmp_path):
+ """When content_filter_triggered=False with no tool calls, normal finalization runs."""
+ events: list[SwarmEvent] = []
+ llm = _ScriptedChatLLM([
+ LLMResponse(content=FINAL_TEXT, content_filter_triggered=False),
+ ])
+
+ result = _run(monkeypatch, tmp_path, llm, event_callback=events.append)
+
+ assert result.status == "completed"
+ assert llm.calls == 1
+ cf_events = [e for e in events if e.type == "content_filter_skipped"]
+ assert len(cf_events) == 0
+
+
+def _tool_response(idx: int) -> LLMResponse:
+ return LLMResponse(
+ content="searching...",
+ tool_calls=[ToolCallRequest(id=f"tc{idx}", name="web_search", arguments={"q": "test"})],
+ )
+
+
+def test_content_filter_warning_in_result(monkeypatch, tmp_path):
+ """4/10 iterations content-filtered (40%) -> WorkerResult.content_filter_warnings contains warning."""
+ responses = [
+ LLMResponse(content="", content_filter_triggered=True) if i < 4 else _tool_response(i)
+ for i in range(10)
+ ]
+ llm = _ScriptedChatLLM(responses)
+
+ result = _run(monkeypatch, tmp_path, llm, max_iterations=10)
+
+ assert len(result.content_filter_warnings) == 1
+ assert "4/10" in result.content_filter_warnings[0]
+ assert "40%" in result.content_filter_warnings[0]
+
+
+def test_content_filter_no_warning_below_threshold(monkeypatch, tmp_path):
+ """0/10 iterations content-filtered -> WorkerResult.content_filter_warnings is empty."""
+ responses = [_tool_response(i) for i in range(10)]
+ llm = _ScriptedChatLLM(responses)
+
+ result = _run(monkeypatch, tmp_path, llm, max_iterations=10)
+
+ assert result.content_filter_warnings == []
+
+
+def test_content_filter_circuit_breaker(monkeypatch, tmp_path):
+ """10 consecutive content filters trip the circuit breaker → worker fails early."""
+ responses = [LLMResponse(content="", content_filter_triggered=True) for _ in range(15)]
+ llm = _ScriptedChatLLM(responses)
+
+ result = _run(monkeypatch, tmp_path, llm, max_iterations=20)
+
+ assert result.status == "failed"
+ assert "circuit_breaker" in (result.error or "")
+ assert result.iterations <= 11