Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(scheduler): retry transient scheduled research failures

Haozhe Wu757e8ba9f703
diff --git a/agent/.env.example b/agent/.env.example
index bd5d6c390..c5b2a16ff 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -212,6 +212,11 @@ TUSHARE_TOKEN=your-tushare-token
# When enabled, the API server runs a background poller that fires due
# interval/cron scheduled-research jobs through the session runtime.
# VIBE_TRADING_ENABLE_SCHEDULER=1
+# A dispatch failure stays retryable until this many consecutive failures.
+# Retry timing is max(next scheduled time, exponential delay), capped below.
+# VIBE_TRADING_SCHEDULER_MAX_CONSECUTIVE_FAILURES=3
+# VIBE_TRADING_SCHEDULER_RETRY_BASE_DELAY_MS=60000
+# VIBE_TRADING_SCHEDULER_RETRY_MAX_DELAY_MS=3600000
# ============================================================================
# API Server (APIConfig, optional)
diff --git a/agent/src/api/scheduled_routes.py b/agent/src/api/scheduled_routes.py
index 55b04f3b4..39bb5ce4d 100644
--- a/agent/src/api/scheduled_routes.py
+++ b/agent/src/api/scheduled_routes.py
@@ -6,7 +6,6 @@ Mounted by ``agent/api_server.py`` via ``register_scheduled_routes(app, ...)``.
from __future__ import annotations
import logging
-import os
import sys as _sys
import time
import uuid
@@ -137,6 +136,10 @@ class ScheduledRunResponse(BaseModel):
next_run_at: int
status: str
created_at: int
+ last_run_at: Optional[int] = None
+ consecutive_failures: int = 0
+ last_error: Optional[str] = None
+ failure_kind: Optional[str] = None
config: Dict[str, Any] = Field(default_factory=dict)
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index 29de6e2e4..c138b9627 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -327,6 +327,15 @@ class AgentTuningConfig(_EnvBase):
vibe_trading_enable_scheduler: EnvBool = Field(
alias="VIBE_TRADING_ENABLE_SCHEDULER", default=False,
)
+ vibe_trading_scheduler_max_consecutive_failures: int = Field(
+ alias="VIBE_TRADING_SCHEDULER_MAX_CONSECUTIVE_FAILURES", default=3,
+ )
+ vibe_trading_scheduler_retry_base_delay_ms: int = Field(
+ alias="VIBE_TRADING_SCHEDULER_RETRY_BASE_DELAY_MS", default=60_000,
+ )
+ vibe_trading_scheduler_retry_max_delay_ms: int = Field(
+ alias="VIBE_TRADING_SCHEDULER_RETRY_MAX_DELAY_MS", default=3_600_000,
+ )
vibe_trading_channels_auto_start: EnvBool = Field(
alias="VIBE_TRADING_CHANNELS_AUTO_START", default=False,
)
diff --git a/agent/src/scheduled_research/executor.py b/agent/src/scheduled_research/executor.py
index 32e049abb..51b0bd4c3 100644
--- a/agent/src/scheduled_research/executor.py
+++ b/agent/src/scheduled_research/executor.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import asyncio
import logging
-import os
import time
from datetime import datetime, timedelta, timezone
from typing import Awaitable, Callable
@@ -18,11 +17,13 @@ from typing import Awaitable, Callable
from src.config.accessor import get_env_config
from src.scheduled_research.models import JobStatus, ScheduledResearchJob, validate_schedule
from src.scheduled_research.store import ScheduledResearchJobStore
+from src.tools.redaction import redact_internal_paths, redact_text
logger = logging.getLogger(__name__)
DEFAULT_TICK_INTERVAL_MS = 60 * 1000
SCHEDULER_ENABLED_ENV = "VIBE_TRADING_ENABLE_SCHEDULER"
+_MAX_PERSISTED_ERROR_CHARS = 1000
NowFn = Callable[[], int]
DispatchCallback = Callable[[ScheduledResearchJob], Awaitable[None]]
@@ -65,6 +66,15 @@ def is_due(job: ScheduledResearchJob, now_ms: int) -> bool:
return job.next_run_at <= now_ms
+def _persisted_error(exc: Exception) -> str:
+ """Return a bounded, redaction-safe error for durable job state."""
+ message = f"{type(exc).__name__}: {exc}"
+ safe = redact_text(redact_internal_paths(message)).replace("\x00", "")
+ if len(safe) <= _MAX_PERSISTED_ERROR_CHARS:
+ return safe
+ return f"{safe[: _MAX_PERSISTED_ERROR_CHARS - 3]}..."
+
+
def next_due(schedule: str, after_ms: int) -> int:
"""Return the first due epoch-ms strictly after ``after_ms``.
@@ -137,6 +147,9 @@ class ScheduledResearchExecutor:
tick_interval_ms: int = DEFAULT_TICK_INTERVAL_MS,
now_fn: NowFn = _now_ms,
enabled: bool = True,
+ max_consecutive_failures: int | None = None,
+ retry_base_delay_ms: int | None = None,
+ retry_max_delay_ms: int | None = None,
) -> None:
"""Initialize the executor.
@@ -146,12 +159,43 @@ class ScheduledResearchExecutor:
tick_interval_ms: Poll interval for the background loop.
now_fn: Injectable wall-clock source returning epoch milliseconds.
enabled: When false, :meth:`start` and :meth:`stop` are no-ops.
+ max_consecutive_failures: Dispatch failures allowed before a job
+ becomes terminal. Defaults to environment configuration.
+ retry_base_delay_ms: Base delay for exponential retry backoff.
+ retry_max_delay_ms: Upper bound for exponential retry backoff.
+
+ Raises:
+ ValueError: If the retry policy is invalid.
"""
+ tuning = None
+ if None in (max_consecutive_failures, retry_base_delay_ms, retry_max_delay_ms):
+ tuning = get_env_config().agent_tuning
self._store = store
self._dispatch = dispatch
self._tick_interval_ms = tick_interval_ms
self._now_fn = now_fn
self._enabled = enabled
+ self._max_consecutive_failures = (
+ max_consecutive_failures
+ if max_consecutive_failures is not None
+ else tuning.vibe_trading_scheduler_max_consecutive_failures
+ )
+ self._retry_base_delay_ms = (
+ retry_base_delay_ms
+ if retry_base_delay_ms is not None
+ else tuning.vibe_trading_scheduler_retry_base_delay_ms
+ )
+ self._retry_max_delay_ms = (
+ retry_max_delay_ms
+ if retry_max_delay_ms is not None
+ else tuning.vibe_trading_scheduler_retry_max_delay_ms
+ )
+ if self._max_consecutive_failures < 1:
+ raise ValueError("max_consecutive_failures must be at least 1")
+ if self._retry_base_delay_ms < 0:
+ raise ValueError("retry_base_delay_ms must be non-negative")
+ if self._retry_max_delay_ms < self._retry_base_delay_ms:
+ raise ValueError("retry_max_delay_ms must be at least retry_base_delay_ms")
self._task: asyncio.Task | None = None
self._wakeup: asyncio.Event | None = None
self._stopping = False
@@ -278,28 +322,60 @@ class ScheduledResearchExecutor:
job.status = JobStatus.RUNNING
self._store.upsert(job)
+ dispatch_error: Exception | None = None
try:
await self._dispatch(job)
except asyncio.CancelledError:
raise
- except Exception:
+ except Exception as exc:
logger.error("scheduled research dispatch failed for job %s", job.id, exc_info=True)
- final_status = JobStatus.FAILED
+ dispatch_error = exc
+ job.consecutive_failures += 1
else:
- final_status = JobStatus.COMPLETED
+ job.consecutive_failures = 0
job.last_run_at = now_ms
try:
- job.next_run_at = next_due(job.schedule, now_ms)
- except Exception:
+ scheduled_next_run = next_due(job.schedule, now_ms)
+ except Exception as exc:
logger.error("scheduled research schedule advancement failed for job %s", job.id, exc_info=True)
job.status = JobStatus.FAILED
+ job.failure_kind = "schedule"
+ job.last_error = _persisted_error(exc)
self._persist_completion(job)
return
- job.status = final_status
+ job.next_run_at = scheduled_next_run
+ if dispatch_error is None:
+ job.status = JobStatus.COMPLETED
+ job.failure_kind = None
+ job.last_error = None
+ else:
+ job.failure_kind = "dispatch"
+ job.last_error = _persisted_error(dispatch_error)
+ if job.consecutive_failures >= self._max_consecutive_failures:
+ job.status = JobStatus.FAILED
+ else:
+ job.status = JobStatus.PENDING
+ retry_delay = self._retry_delay_ms(job.consecutive_failures)
+ job.next_run_at = max(scheduled_next_run, now_ms + retry_delay)
+ logger.warning(
+ "scheduled research job %s will retry after failure %d/%d at %d",
+ job.id,
+ job.consecutive_failures,
+ self._max_consecutive_failures,
+ job.next_run_at,
+ )
self._persist_completion(job)
+ def _retry_delay_ms(self, consecutive_failures: int) -> int:
+ """Return bounded exponential backoff for a dispatch failure count."""
+ exponent = max(0, consecutive_failures - 1)
+ if self._retry_base_delay_ms == 0:
+ return 0
+ delay = self._retry_base_delay_ms * (2 ** min(exponent, 62))
+ return min(delay, self._retry_max_delay_ms)
+
@staticmethod
def _same_record(current: ScheduledResearchJob, job: ScheduledResearchJob) -> bool:
"""Return whether *current* is the same scheduled run we started.
diff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.py
index ce746fa78..c1b105784 100644
--- a/agent/src/scheduled_research/models.py
+++ b/agent/src/scheduled_research/models.py
@@ -83,7 +83,7 @@ class JobStatus(str, Enum):
@dataclass
class ScheduledResearchJob:
- """Immutable record describing a scheduled research / backtest job.
+ """Mutable persisted state for a scheduled research / backtest job.
Attributes:
id: Unique job identifier (caller-supplied UUID or slug).
@@ -95,6 +95,11 @@ class ScheduledResearchJob:
created_at: Epoch-millisecond timestamp of job creation.
last_run_at: Epoch-millisecond timestamp of the most recent executor
attempt, or ``None`` when the job has not fired yet.
+ consecutive_failures: Number of consecutive dispatch failures. A
+ successful dispatch resets it to zero.
+ last_error: Redaction-safe diagnostic from the latest failed attempt.
+ failure_kind: ``"dispatch"`` for provider/session failures or
+ ``"schedule"`` when the schedule cannot be advanced.
config: Opaque dict for future backtest parameters.
"""
@@ -105,6 +110,9 @@ class ScheduledResearchJob:
status: JobStatus = JobStatus.PENDING
created_at: int = field(default_factory=lambda: int(time.time() * 1000))
last_run_at: Optional[int] = None
+ consecutive_failures: int = 0
+ last_error: Optional[str] = None
+ failure_kind: Optional[str] = None
config: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
@@ -122,6 +130,9 @@ class ScheduledResearchJob:
"status": self.status.value,
"created_at": self.created_at,
"last_run_at": self.last_run_at,
+ "consecutive_failures": self.consecutive_failures,
+ "last_error": self.last_error,
+ "failure_kind": self.failure_kind,
"config": self.config,
}
@@ -152,6 +163,19 @@ class ScheduledResearchJob:
last_run_at = data.get("last_run_at")
if last_run_at is not None and not isinstance(last_run_at, int):
raise TypeError("'last_run_at' must be an integer (epoch ms) or null")
+ consecutive_failures = data.get("consecutive_failures", 0)
+ if (
+ isinstance(consecutive_failures, bool)
+ or not isinstance(consecutive_failures, int)
+ or consecutive_failures < 0
+ ):
+ raise TypeError("'consecutive_failures' must be a non-negative integer")
+ last_error = data.get("last_error")
+ failure_kind = data.get("failure_kind")
+ if last_error is not None and not isinstance(last_error, str):
+ raise TypeError("'last_error' must be a string or null")
+ if failure_kind is not None and failure_kind not in {"dispatch", "schedule"}:
+ raise ValueError("'failure_kind' must be 'dispatch', 'schedule', or null")
status = JobStatus(data["status"])
raw_config = data.get("config")
config: Dict[str, Any] = raw_config if isinstance(raw_config, dict) else {}
@@ -163,5 +187,8 @@ class ScheduledResearchJob:
status=status,
created_at=created_at,
last_run_at=last_run_at,
+ consecutive_failures=consecutive_failures,
+ last_error=last_error,
+ failure_kind=failure_kind,
config=config,
)
diff --git a/agent/tests/test_env_schema.py b/agent/tests/test_env_schema.py
index fd2596d18..0d65991a4 100644
--- a/agent/tests/test_env_schema.py
+++ b/agent/tests/test_env_schema.py
@@ -136,6 +136,9 @@ class TestEnvConfigDefaults:
assert c.agent_tuning.content_filter_warning_threshold == 0.05
assert c.agent_tuning.vibe_trading_enable_advisory is False
assert c.agent_tuning.vibe_trading_enable_scheduler is False
+ assert c.agent_tuning.vibe_trading_scheduler_max_consecutive_failures == 3
+ assert c.agent_tuning.vibe_trading_scheduler_retry_base_delay_ms == 60_000
+ assert c.agent_tuning.vibe_trading_scheduler_retry_max_delay_ms == 3_600_000
assert c.agent_tuning.vibe_trading_channels_auto_start is False
assert c.agent_tuning.vibe_trading_disable_bottleneck is False
assert c.agent_tuning.vibe_trading_bench_workers == 0
@@ -195,6 +198,17 @@ class TestEnvConfigTypeCoercion:
c = EnvConfig()
assert c.swarm.swarm_heartbeat_interval_s == 5.5
+ def test_scheduler_retry_int_coercion(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_SCHEDULER_MAX_CONSECUTIVE_FAILURES", "5")
+ monkeypatch.setenv("VIBE_TRADING_SCHEDULER_RETRY_BASE_DELAY_MS", "2500")
+ monkeypatch.setenv("VIBE_TRADING_SCHEDULER_RETRY_MAX_DELAY_MS", "10000")
+
+ tuning = EnvConfig().agent_tuning
+
+ assert tuning.vibe_trading_scheduler_max_consecutive_failures == 5
+ assert tuning.vibe_trading_scheduler_retry_base_delay_ms == 2500
+ assert tuning.vibe_trading_scheduler_retry_max_delay_ms == 10000
+
# ===================================================================
# TestEnvConfigOverride
diff --git a/agent/tests/test_scheduled_research_executor.py b/agent/tests/test_scheduled_research_executor.py
index b0eed3020..33fc1d3b5 100644
--- a/agent/tests/test_scheduled_research_executor.py
+++ b/agent/tests/test_scheduled_research_executor.py
@@ -114,7 +114,7 @@ def test_cron_wildcard_day_field_leaves_other_day_field_authoritative() -> None:
assert next_due("0 0 * * 5", thursday) == _ms(2026, 6, 12, 0, 0)
-def test_dispatch_failure_marks_failed_and_tick_continues(tmp_path: Path) -> None:
+def test_dispatch_failure_stays_retryable_and_tick_continues(tmp_path: Path) -> None:
store = _store(tmp_path)
store.upsert(_job("bad", next_run_at=10))
store.upsert(_job("good", next_run_at=20))
@@ -126,7 +126,13 @@ def test_dispatch_failure_marks_failed_and_tick_continues(tmp_path: Path) -> Non
raise RuntimeError("boom")
async def scenario() -> None:
- executor = ScheduledResearchExecutor(store, dispatch)
+ executor = ScheduledResearchExecutor(
+ store,
+ dispatch,
+ max_consecutive_failures=3,
+ retry_base_delay_ms=1000,
+ retry_max_delay_ms=4000,
+ )
await executor.tick(100)
asyncio.run(scenario())
@@ -136,10 +142,117 @@ def test_dispatch_failure_marks_failed_and_tick_continues(tmp_path: Path) -> Non
assert bad is not None
assert good is not None
assert calls == ["bad", "good"]
- assert bad.status == JobStatus.FAILED
+ assert bad.status == JobStatus.PENDING
+ assert bad.consecutive_failures == 1
+ assert bad.failure_kind == "dispatch"
+ assert bad.last_error == "RuntimeError: boom"
+ assert bad.next_run_at == 1100
assert good.status == JobStatus.COMPLETED
+def test_transient_dispatch_failure_retries_then_success_resets_state(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job(schedule="1000", next_run_at=0))
+ calls = 0
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ raise TimeoutError("provider timed out")
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(
+ store,
+ dispatch,
+ max_consecutive_failures=3,
+ retry_base_delay_ms=1000,
+ retry_max_delay_ms=4000,
+ )
+ await executor.tick(100)
+ await executor.tick(1099)
+ assert calls == 1
+ await executor.tick(1100)
+
+ asyncio.run(scenario())
+
+ saved = store.get("job-001")
+ assert saved is not None
+ assert calls == 2
+ assert saved.status == JobStatus.COMPLETED
+ assert saved.consecutive_failures == 0
+ assert saved.failure_kind is None
+ assert saved.last_error is None
+ assert saved.last_run_at == 1100
+ assert saved.next_run_at == 2100
+
+
+def test_repeated_dispatch_failures_become_terminal_at_threshold(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job(schedule="1000", next_run_at=0))
+ calls = 0
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ nonlocal calls
+ calls += 1
+ raise ConnectionError("provider unavailable")
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(
+ store,
+ dispatch,
+ max_consecutive_failures=2,
+ retry_base_delay_ms=0,
+ retry_max_delay_ms=0,
+ )
+ await executor.tick(100)
+ await executor.tick(1100)
+ await executor.tick(10_000)
+
+ asyncio.run(scenario())
+
+ saved = store.get("job-001")
+ assert saved is not None
+ assert calls == 2
+ assert saved.status == JobStatus.FAILED
+ assert saved.consecutive_failures == 2
+ assert saved.failure_kind == "dispatch"
+ assert saved.last_error == "ConnectionError: provider unavailable"
+ assert saved.next_run_at == 2100
+
+
+def test_persisted_dispatch_error_is_redacted_and_bounded(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job(next_run_at=0))
+ secret = "scheduler-secret-value"
+ raw_error = f"api_key={secret} path={Path.home()}/private/trace " + ("x" * 2000)
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ raise RuntimeError(raw_error)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(
+ store,
+ dispatch,
+ max_consecutive_failures=1,
+ retry_base_delay_ms=0,
+ retry_max_delay_ms=0,
+ )
+ await executor.tick(100)
+
+ asyncio.run(scenario())
+
+ saved = store.get("job-001")
+ assert saved is not None
+ assert saved.last_error is not None
+ assert secret not in saved.last_error
+ assert str(Path.home()) not in saved.last_error
+ assert "[redacted]" in saved.last_error
+ assert "<redacted>/private/trace" in saved.last_error
+ assert len(saved.last_error) == 1000
+ assert saved.last_error.endswith("...")
+
+
def test_stale_running_job_recovers_to_pending_and_fires_on_next_tick(tmp_path: Path) -> None:
store = _store(tmp_path)
store.upsert(_job("stale", schedule="1000", next_run_at=10, status=JobStatus.RUNNING))
@@ -193,6 +306,8 @@ def test_impossible_cron_marks_failed_and_tick_continues(tmp_path: Path) -> None
assert bad.status == JobStatus.FAILED
assert bad.last_run_at == now
assert bad.next_run_at == 10
+ assert bad.failure_kind == "schedule"
+ assert "cron schedule has no matching time" in (bad.last_error or "")
assert good.status == JobStatus.COMPLETED
@@ -242,6 +357,56 @@ def test_failed_job_is_not_redispatched(tmp_path: Path) -> None:
assert store.get("failed").status == JobStatus.FAILED # type: ignore[union-attr]
+def test_retry_backoff_is_exponential_and_capped(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job(schedule="100", next_run_at=0))
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ raise TimeoutError("outage")
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(
+ store,
+ dispatch,
+ max_consecutive_failures=4,
+ retry_base_delay_ms=1000,
+ retry_max_delay_ms=1500,
+ )
+ await executor.tick(0)
+ first = store.get("job-001")
+ assert first is not None
+ assert first.next_run_at == 1000
+ await executor.tick(1000)
+
+ asyncio.run(scenario())
+
+ saved = store.get("job-001")
+ assert saved is not None
+ assert saved.consecutive_failures == 2
+ assert saved.next_run_at == 2500
+
+
+ ("kwargs", "message"),
+ [
+ ({"max_consecutive_failures": 0}, "max_consecutive_failures"),
+ ({"retry_base_delay_ms": -1}, "retry_base_delay_ms"),
+ (
+ {"retry_base_delay_ms": 100, "retry_max_delay_ms": 99},
+ "retry_max_delay_ms",
+ ),
+ ],
+)
+def test_invalid_retry_policy_is_rejected(
+ tmp_path: Path, kwargs: dict[str, int], message: str
+) -> None:
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ return None
+
+ with pytest.raises(ValueError, match=message):
+ ScheduledResearchExecutor(_store(tmp_path), dispatch, **kwargs)
+
+
def test_job_deleted_during_dispatch_is_not_resurrected(tmp_path: Path) -> None:
store = _store(tmp_path)
store.upsert(_job("job-001", schedule="1000", next_run_at=0))
diff --git a/agent/tests/test_scheduled_research_store.py b/agent/tests/test_scheduled_research_store.py
index 7cac6b976..3a82950b9 100644
--- a/agent/tests/test_scheduled_research_store.py
+++ b/agent/tests/test_scheduled_research_store.py
@@ -6,6 +6,7 @@ idempotent upsert, and empty-store behaviour.
from __future__ import annotations
+import json
import time
from pathlib import Path
@@ -224,6 +225,35 @@ class TestScheduledResearchJobStore:
assert fetched.prompt == job.prompt
assert fetched.schedule == "0 */4 * * *"
+ def test_retry_state_round_trips_and_legacy_jobs_get_defaults(self, tmp_path: Path) -> None:
+ store_path = tmp_path / "jobs.json"
+ store = ScheduledResearchJobStore(path=store_path)
+ job = _make_job("retrying")
+ job.consecutive_failures = 2
+ job.last_error = "TimeoutError: provider timed out"
+ job.failure_kind = "dispatch"
+ store.upsert(job)
+
+ fetched = ScheduledResearchJobStore(path=store_path).get("retrying")
+ assert fetched is not None
+ assert fetched.consecutive_failures == 2
+ assert fetched.last_error == "TimeoutError: provider timed out"
+ assert fetched.failure_kind == "dispatch"
+
+ legacy = _make_job("legacy").to_dict()
+ for field in ("consecutive_failures", "last_error", "failure_kind"):
+ legacy.pop(field)
+ store_path.write_text(
+ json.dumps({"schema_version": 1, "jobs": [legacy]}),
+ encoding="utf-8",
+ )
+
+ migrated = ScheduledResearchJobStore(path=store_path).get("legacy")
+ assert migrated is not None
+ assert migrated.consecutive_failures == 0
+ assert migrated.last_error is None
+ assert migrated.failure_kind is None
+
def test_cron_schedule_accepted(self, tmp_path: Path) -> None:
store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")
cron_job = _make_job("cron-1", schedule="*/30 * * * *")
diff --git a/agent/tests/test_scheduled_routes.py b/agent/tests/test_scheduled_routes.py
index 1e32a9748..7ced39e4f 100644
--- a/agent/tests/test_scheduled_routes.py
+++ b/agent/tests/test_scheduled_routes.py
@@ -72,6 +72,10 @@ def test_create_persists_job_and_returns_201(
body = response.json()
assert body["id"] == "daily-scan"
assert body["status"] == "pending"
+ assert body["last_run_at"] is None
+ assert body["consecutive_failures"] == 0
+ assert body["last_error"] is None
+ assert body["failure_kind"] is None
assert body["config"] == {"universe": "sp500"}
stored = store.get("daily-scan")
@@ -133,6 +137,29 @@ def test_list_filters_by_status(
assert [job["id"] for job in body] == ["done-one"]
+def test_list_surfaces_retry_diagnostics(
+ client: TestClient, store: ScheduledResearchJobStore
+):
+ _seed(
+ store,
+ id="retrying",
+ status=JobStatus.PENDING,
+ last_run_at=1_700_000_100_000,
+ consecutive_failures=2,
+ last_error="TimeoutError: provider timed out",
+ failure_kind="dispatch",
+ )
+
+ response = client.get("/scheduled-runs")
+
+ assert response.status_code == 200
+ body = response.json()[0]
+ assert body["last_run_at"] == 1_700_000_100_000
+ assert body["consecutive_failures"] == 2
+ assert body["last_error"] == "TimeoutError: provider timed out"
+ assert body["failure_kind"] == "dispatch"
+
+
def test_list_rejects_out_of_range_limit(client: TestClient):
assert client.get("/scheduled-runs", params={"limit": 0}).status_code == 422
assert client.get("/scheduled-runs", params={"limit": 500}).status_code == 422