Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): thread grounding data safely

Haozhe Wu9e70dca97cd1
diff --git a/agent/src/swarm/grounding.py b/agent/src/swarm/grounding.py
index 632fedf28..e3ab1191b 100644
--- a/agent/src/swarm/grounding.py
+++ b/agent/src/swarm/grounding.py
@@ -25,7 +25,7 @@ What this module **does not** do
to false-positive on common English words. Users supply suffixed
symbols already in every shipped preset.
* It does not refresh data mid-run. The block is a snapshot taken once
- at ``start_run`` time; long-running swarms will see stale data after
+ when the background run starts; long-running swarms will see stale data after
many minutes, but that is still strictly better than training-data
prices from a year ago.
"""
@@ -33,6 +33,7 @@ What this module **does not** do
from __future__ import annotations
import logging
+import os
import re
from datetime import date, timedelta
from typing import Iterable
@@ -44,6 +45,8 @@ logger = logging.getLogger(__name__)
# roughly 21 US trading days — enough for a "recent" view without
# bloating the worker prompt.
DEFAULT_WINDOW_DAYS = 30
+DEFAULT_MAX_SYMBOLS = 8
+MAX_SYMBOLS_ENV = "SWARM_GROUNDING_MAX_SYMBOLS"
# How many of the most-recent rows to render in the worker prompt.
# The full window is still used to compute the min/max line; the table
@@ -76,6 +79,22 @@ def extract_symbols_from_user_vars(user_vars: dict[str, str]) -> list[str]:
return list(seen.keys())
+def max_grounding_symbols() -> int:
+ """Return the configured cap for symbols fetched into worker prompts."""
+ raw = os.getenv(MAX_SYMBOLS_ENV, "").strip()
+ if not raw:
+ return DEFAULT_MAX_SYMBOLS
+ try:
+ value = int(raw)
+ except ValueError:
+ logger.warning(
+ "grounding: invalid %s=%r, using default %d",
+ MAX_SYMBOLS_ENV, raw, DEFAULT_MAX_SYMBOLS,
+ )
+ return DEFAULT_MAX_SYMBOLS
+ return max(1, value)
+
+
def fetch_grounding_data(
symbols: Iterable[str],
*,
diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.py
index 309408271..2f2aa8f33 100644
--- a/agent/src/swarm/runtime.py
+++ b/agent/src/swarm/runtime.py
@@ -103,24 +103,6 @@ class SwarmRuntime:
run.provider = (os.getenv("LANGCHAIN_PROVIDER") or "").strip().lower() or None
run.model = (os.getenv("LANGCHAIN_MODEL_NAME") or "").strip() or None
- # Pre-fetch market data for any suffixed stock / crypto symbols
- # mentioned in user_vars and pin it on the run. Workers read these
- # bars off run.grounding_data instead of hallucinating prices from
- # their training cutoff. Failures are non-fatal — the run still
- # proceeds, just without the grounding block.
- symbols = grounding.extract_symbols_from_user_vars(user_vars)
- if symbols:
- try:
- fetched = grounding.fetch_grounding_data(symbols)
- except Exception:
- logger.warning(
- "grounding: pre-fetch failed for run %s symbols=%s",
- run.id, symbols, exc_info=True,
- )
- fetched = {}
- if fetched:
- run.grounding_data = fetched
-
self._store.create_run(run)
cancel_event = threading.Event()
@@ -231,6 +213,8 @@ class SwarmRuntime:
self._store.update_run(run)
self._emit_event(run_id, self._make_event("run_started"))
+ self._prefetch_grounding_data(run)
+
# Initialize task store
task_store = TaskStore(run_dir)
for task in run.tasks:
@@ -276,6 +260,7 @@ class SwarmRuntime:
run_dir=run_dir,
cancel_event=cancel_event,
include_shell_tools=include_shell_tools,
+ grounding_block=grounding_block,
)
# Process results
@@ -355,6 +340,33 @@ class SwarmRuntime:
self._cancel_events.pop(run_id, None)
self._live_callbacks.pop(run_id, None)
+ def _prefetch_grounding_data(self, run: SwarmRun) -> None:
+ """Fetch run-level grounding data without blocking ``start_run``."""
+ symbols = grounding.extract_symbols_from_user_vars(run.user_vars)
+ if not symbols:
+ return
+
+ symbol_limit = grounding.max_grounding_symbols()
+ if len(symbols) > symbol_limit:
+ logger.warning(
+ "grounding: limiting run %s symbols from %d to %d",
+ run.id, len(symbols), symbol_limit,
+ )
+ symbols = symbols[:symbol_limit]
+
+ try:
+ fetched = grounding.fetch_grounding_data(symbols)
+ except Exception:
+ logger.warning(
+ "grounding: pre-fetch failed for run %s symbols=%s",
+ run.id, symbols, exc_info=True,
+ )
+ return
+
+ if fetched:
+ run.grounding_data = fetched
+ self._store.update_run(run)
+
def _execute_layer(
self,
run: SwarmRun,
@@ -365,6 +377,7 @@ class SwarmRuntime:
run_dir: Path,
cancel_event: threading.Event,
include_shell_tools: bool = False,
+ grounding_block: str = "",
) -> dict[str, WorkerResult]:
"""Execute all tasks in a single layer in parallel, with retry on failure.
@@ -380,6 +393,7 @@ class SwarmRuntime:
run_dir: Run directory path.
cancel_event: Cancellation event.
include_shell_tools: Whether workers may register shell tools.
+ grounding_block: Pre-rendered "Ground Truth" markdown for workers.
Returns:
Mapping of task_id -> WorkerResult for all tasks in this layer.
diff --git a/agent/tests/test_swarm_grounding.py b/agent/tests/test_swarm_grounding.py
index ae339aece..b8ac6eba2 100644
--- a/agent/tests/test_swarm_grounding.py
+++ b/agent/tests/test_swarm_grounding.py
@@ -7,14 +7,18 @@ markdown formatter are pure-function tests.
from __future__ import annotations
+import threading
from datetime import date
+from unittest.mock import MagicMock
import pandas as pd
import pytest
from src.swarm import grounding
+from src.swarm.models import SwarmAgentSpec, SwarmRun, SwarmTask, WorkerResult
+from src.swarm.runtime import SwarmRuntime
+from src.swarm.task_store import TaskStore
from src.swarm.worker import build_worker_prompt
-from src.swarm.models import SwarmAgentSpec
# --------------------------------------------------------------------------- #
@@ -139,6 +143,16 @@ def test_fetch_returns_empty_for_empty_input() -> None:
assert grounding.fetch_grounding_data([]) == {}
+def test_max_grounding_symbols_uses_env(monkeypatch) -> None:
+ monkeypatch.setenv("SWARM_GROUNDING_MAX_SYMBOLS", "3")
+ assert grounding.max_grounding_symbols() == 3
+
+
+def test_max_grounding_symbols_falls_back_on_invalid_env(monkeypatch) -> None:
+ monkeypatch.setenv("SWARM_GROUNDING_MAX_SYMBOLS", "nope")
+ assert grounding.max_grounding_symbols() == grounding.DEFAULT_MAX_SYMBOLS
+
+
# --------------------------------------------------------------------------- #
# format_grounding_block
# --------------------------------------------------------------------------- #
@@ -192,3 +206,42 @@ def test_worker_prompt_includes_grounding_block_when_provided() -> None:
def test_worker_prompt_omits_grounding_section_when_block_empty() -> None:
prompt = build_worker_prompt(_spec(), {}, "(no matching skills)")
assert "Ground Truth" not in prompt
+
+
+def test_runtime_threads_grounding_block_into_layer_workers(tmp_path, monkeypatch) -> None:
+ """Regression: _execute_layer must receive the run-level grounding block."""
+ store = MagicMock()
+ runtime = SwarmRuntime(store=store, max_workers=1)
+ run_dir = tmp_path / "run"
+ task_store = TaskStore(run_dir)
+ agent = _spec()
+ task = SwarmTask(id="task1", agent_id=agent.id, prompt_template="Analyze.")
+ task_store.save_task(task)
+ run = SwarmRun(
+ id="run1",
+ preset_name="dummy",
+ created_at="2026-05-13T00:00:00+00:00",
+ agents=[agent],
+ tasks=[task],
+ )
+ seen: list[str] = []
+
+ def _fake_worker(**kwargs):
+ seen.append(kwargs["grounding_block"])
+ return WorkerResult(status="completed", summary="done")
+
+ monkeypatch.setattr(runtime, "_run_worker_with_retries", _fake_worker)
+
+ results = runtime._execute_layer(
+ run=run,
+ task_store=task_store,
+ agent_map={agent.id: agent},
+ layer_task_ids=[task.id],
+ task_summaries={},
+ run_dir=run_dir,
+ cancel_event=threading.Event(),
+ grounding_block="GROUNDING",
+ )
+
+ assert results[task.id].summary == "done"
+ assert seen == ["GROUNDING"]