"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(scheduled-research): deliver a finished briefing through an outbox
Haozhe Wufd7e6e0e2ac6
diff --git a/agent/src/scheduled_research/executor.py b/agent/src/scheduled_research/executor.pyindex e4094d258..216856c3f 100644--- a/agent/src/scheduled_research/executor.py+++ b/agent/src/scheduled_research/executor.py@@ -12,12 +12,14 @@ import asyncioimport loggingimport timefrom datetime import date, datetime, timedelta, timezone, tzinfo-from typing import Awaitable, Callable+from typing import Awaitable, Callable, Optionalfrom zoneinfo import ZoneInfofrom src.config.accessor import get_env_configfrom src.scheduled_research.models import (CRON_BOUNDS,+ DeliveryRecord,+ DeliveryStatus,JobStatus,ScheduledResearchJob,parse_cron_field,@@ -34,7 +36,13 @@ SCHEDULER_ENABLED_ENV = "VIBE_TRADING_ENABLE_SCHEDULER"_MAX_PERSISTED_ERROR_CHARS = 1000NowFn = Callable[[], int]-DispatchCallback = Callable[[ScheduledResearchJob], Awaitable[None]]+# A dispatcher may return the session id it enqueued into. Returning None keeps+# the pre-delivery contract working unchanged.+DispatchCallback = Callable[[ScheduledResearchJob], Awaitable[Optional[str]]]+#: session_id -> (terminal status, briefing text), or None while in flight.+BriefingReader = Callable[[str], Optional[tuple[str, str]]]+#: (channel, target, text) -> delivered.+ChannelSender = Callable[[str, Optional[str], str], Awaitable[None]]_TRUE_VALUES = {"1", "true", "yes", "on"}# Search by day, not by minute, so an impossible date (e.g. Feb 31) fails fast@@ -171,6 +179,8 @@ class ScheduledResearchExecutor:max_consecutive_failures: int | None = None,retry_base_delay_ms: int | None = None,retry_max_delay_ms: int | None = None,+ briefing_reader: "BriefingReader | None" = None,+ channel_sender: "ChannelSender | None" = None,) -> None:"""Initialize the executor.@@ -184,6 +194,11 @@ class ScheduledResearchExecutor: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.+ briefing_reader: Callable returning ``(terminal_status, text)`` for+ a session, or ``None`` while its run is still in flight. Both+ collaborators are injected rather than imported so the outbox+ can be driven in a test without a session runtime or a network.+ channel_sender: Async callable delivering one briefing.Raises:ValueError: If the retry policy is invalid.@@ -193,6 +208,8 @@ class ScheduledResearchExecutor:tuning = get_env_config().agent_tuningself._store = storeself._dispatch = dispatch+ self._briefing_reader = briefing_reader+ self._channel_sender = channel_senderself._tick_interval_ms = tick_interval_msself._now_fn = now_fnself._enabled = enabled@@ -285,6 +302,12 @@ class ScheduledResearchExecutor:except Exception:logger.error("scheduled research job %s failed its run cycle", job.id, exc_info=True)+ # The sweep is what makes delivery correct; the event hook only makes+ # it prompt. A briefing whose hook was lost to a restart, a crash+ # between "run finished" and "message sent", or a transient send error+ # is picked up here on the next tick.+ await self.sweep_deliveries()+def recover_stale_running(self) -> int:"""Reset jobs left ``RUNNING`` by a previous executor process.@@ -370,7 +393,18 @@ class ScheduledResearchExecutor:dispatch_error: Exception | None = Nonetry:- await self._dispatch(job)+ session_id = await self._dispatch(job)+ if job.delivery_channel and isinstance(session_id, str) and session_id:+ # Arm the outbox in the same write that records the firing.+ # The row exists before anything can be sent, so a crash can+ # only ever lose the *speed* of delivery, never the fact that+ # one is owed.+ job.delivery = DeliveryRecord(+ status=DeliveryStatus.PENDING,+ session_id=session_id,+ key=f"{job.id}:{session_id}:{job.delivery_channel}",+ updated_at=now_ms,+ )except asyncio.CancelledError:raiseexcept Exception as exc:@@ -414,6 +448,94 @@ class ScheduledResearchExecutor:)self._persist_completion(job)+ async def sweep_deliveries(self) -> int:+ """Deliver every briefing whose run has reached a terminal state.++ Idempotent and restart-safe: the outbox row is the only source of+ truth, a row already ``SENT`` is never re-sent, and a row whose run is+ still in flight is left for a later sweep.++ Returns:+ The number of rows whose state changed.+ """+ if self._briefing_reader is None or self._channel_sender is None:+ return 0++ changed = 0+ for job in list(self._store.load().values()):+ if job.delivery.status is not DeliveryStatus.PENDING:+ continue+ if not job.delivery.session_id or not job.delivery_channel:+ continue+ try:+ outcome = self._briefing_reader(job.delivery.session_id)+ except Exception as exc:+ logger.error("briefing read failed for job %s", job.id, exc_info=True)+ self._mark_delivery_failed(job, exc, retryable=True)+ changed += 1+ continue+ if outcome is None:+ continue # still running; a later sweep will find it++ status, text = outcome+ if status != "completed":+ # A failed or cancelled run has no briefing to deliver. Record+ # why rather than leaving the row pending forever.+ self._mark_delivery_failed(+ job, RuntimeError(f"run {status}"), retryable=False+ )+ changed += 1+ continue++ # Re-read immediately before sending: a concurrent sweep or the+ # event hook may already have delivered this row.+ current = self._store.get(job.id)+ if current is None or current.delivery.key != job.delivery.key:+ continue+ if current.delivery.status is not DeliveryStatus.PENDING:+ continue++ try:+ await self._channel_sender(job.delivery_channel, job.delivery_target, text)+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ logger.error("briefing delivery failed for job %s", job.id, exc_info=True)+ self._mark_delivery_failed(current, exc, retryable=True)+ changed += 1+ continue++ current.delivery.status = DeliveryStatus.SENT+ current.delivery.error = None+ current.delivery.updated_at = self._now_fn()+ self._store.upsert(current, validate=False)+ changed += 1+ return changed++ def _mark_delivery_failed(+ self, job: ScheduledResearchJob, exc: Exception, *, retryable: bool+ ) -> None:+ """Record a delivery failure without losing which firing it belonged to.++ Args:+ job: The job whose outbox row failed.+ exc: The failure, persisted through the same redaction the dispatch+ path uses.+ retryable: Whether a later sweep could still succeed. A channel+ outage is; a run that finished FAILED or CANCELLED is not,+ because no briefing will ever exist for it.+ """+ job.delivery.error = _persisted_error(exc)+ job.delivery.updated_at = self._now_fn()+ if retryable:+ job.delivery.attempts += 1+ if job.delivery.attempts < self._max_consecutive_failures:+ job.delivery.status = DeliveryStatus.PENDING+ self._store.upsert(job, validate=False)+ return+ job.delivery.status = DeliveryStatus.FAILED+ self._store.upsert(job, validate=False)+def _retry_delay_ms(self, consecutive_failures: int) -> int:"""Return bounded exponential backoff for a dispatch failure count."""exponent = max(0, consecutive_failures - 1)diff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.pyindex 81e9384b0..e1e21f4e3 100644--- a/agent/src/scheduled_research/models.py+++ b/agent/src/scheduled_research/models.py@@ -189,6 +189,102 @@ class JobStatus(str, Enum):CANCELLED = "cancelled"+class DeliveryStatus(str, Enum):+ """Outbox state for one job firing's briefing.++ The dispatch path returns once the agent attempt is *accepted*, not when it+ finishes, so "the run completed" and "the briefing was delivered" are two+ different facts and each needs its own record. PENDING means a run was+ dispatched and its result has not been delivered yet; it is the only state+ a sweep needs to look at.+ """++ NONE = "none"+ PENDING = "pending"+ SENT = "sent"+ FAILED = "failed"+++@dataclass+class DeliveryRecord:+ """What happened to the briefing produced by one firing.++ Attributes:+ status: Outbox state for this firing.+ session_id: The session whose terminal result is to be delivered.+ key: Idempotency key. A send is refused when a record with the same+ key is already ``SENT``, so a restarted poller, a retried sweep and+ an event arriving twice cannot produce a second message.+ error: Redaction-safe diagnostic from the last failed delivery.+ attempts: Failed send attempts for this firing. A channel outage is+ transient, so a failed send stays PENDING and is retried; only the+ attempt threshold, or a run that produced no briefing at all,+ makes the row terminal.+ updated_at: Epoch-millisecond timestamp of the last state change.+ """++ status: DeliveryStatus = DeliveryStatus.NONE+ session_id: Optional[str] = None+ key: Optional[str] = None+ error: Optional[str] = None+ attempts: int = 0+ updated_at: Optional[int] = None++ def to_dict(self) -> Dict[str, Any]:+ """Serialize to a plain JSON-serializable dict."""+ return {+ "status": self.status.value,+ "session_id": self.session_id,+ "key": self.key,+ "error": self.error,+ "attempts": self.attempts,+ "updated_at": self.updated_at,+ }++ @classmethod+ def from_dict(cls, data: Optional[Dict[str, Any]]) -> "DeliveryRecord":+ """Reconstruct from a raw dict, treating absence as "never delivered".++ Args:+ data: A raw dict as produced by :meth:`to_dict`, or ``None`` for a+ record written before delivery existed.++ Returns:+ The reconstructed :class:`DeliveryRecord`.++ Raises:+ TypeError: If a present field has the wrong type.+ ValueError: If ``status`` is not a recognized value.+ """+ if not data:+ return cls()+ if not isinstance(data, dict):+ raise TypeError("'delivery' must be an object or null")+ raw_status = data.get("status", DeliveryStatus.NONE.value)+ try:+ status = DeliveryStatus(raw_status)+ except ValueError as exc:+ raise ValueError(f"unknown delivery status {raw_status!r}") from exc+ for name in ("session_id", "key", "error"):+ value = data.get(name)+ if value is not None and not isinstance(value, str):+ raise TypeError(f"'delivery.{name}' must be a string or null")+ updated_at = data.get("updated_at")+ if updated_at is not None and not isinstance(updated_at, int):+ raise TypeError("'delivery.updated_at' must be an integer (epoch ms) or null")+ attempts = data.get("attempts", 0)+ if isinstance(attempts, bool) or not isinstance(attempts, int) or attempts < 0:+ raise TypeError("'delivery.attempts' must be a non-negative integer")+ return cls(+ status=status,+ session_id=data.get("session_id"),+ key=data.get("key"),+ error=data.get("error"),+ attempts=attempts,+ updated_at=updated_at,+ )++# ---------------------------------------------------------------------------# Data model# ---------------------------------------------------------------------------@@ -217,6 +313,13 @@ class ScheduledResearchJob:timezone: IANA timezone key the cron schedule is evaluated in, or``None`` for UTC (the semantics every job had before this fieldexisted). Interval schedules ignore it.+ delivery_channel: Channel id a finished briefing is pushed to, or+ ``None`` to keep the job's results in the app only. Delivery is+ opt-in per job: absent this, nothing is ever sent anywhere.+ delivery_target: Address within that channel (chat / group / user id).+ delivery: Outbox state for the most recent firing. Separate from+ ``status`` because dispatch returns at enqueue: a job can be+ COMPLETED (accepted) while its briefing is still PENDING delivery."""id: str@@ -231,6 +334,9 @@ class ScheduledResearchJob:failure_kind: Optional[str] = Noneconfig: Dict[str, Any] = field(default_factory=dict)timezone: Optional[str] = None+ delivery_channel: Optional[str] = None+ delivery_target: Optional[str] = None+ delivery: DeliveryRecord = field(default_factory=DeliveryRecord)def to_dict(self) -> Dict[str, Any]:"""Serialize to a plain JSON-serializable dict.@@ -252,6 +358,9 @@ class ScheduledResearchJob:"failure_kind": self.failure_kind,"config": self.config,"timezone": self.timezone,+ "delivery_channel": self.delivery_channel,+ "delivery_target": self.delivery_target,+ "delivery": self.delivery.to_dict(),}@classmethod@@ -311,6 +420,14 @@ class ScheduledResearchJob:status = JobStatus(data["status"])raw_config = data.get("config")config: Dict[str, Any] = raw_config if isinstance(raw_config, dict) else {}+ delivery_channel = data.get("delivery_channel")+ delivery_target = data.get("delivery_target")+ for name, value in (+ ("delivery_channel", delivery_channel),+ ("delivery_target", delivery_target),+ ):+ if value is not None and not isinstance(value, str):+ raise TypeError(f"'{name}' must be a string or null")return cls(id=job_id,prompt=prompt,@@ -324,4 +441,7 @@ class ScheduledResearchJob:failure_kind=failure_kind,config=config,timezone=tz,+ delivery_channel=delivery_channel,+ delivery_target=delivery_target,+ delivery=DeliveryRecord.from_dict(data.get("delivery")),)diff --git a/agent/tests/test_scheduled_delivery_outbox.py b/agent/tests/test_scheduled_delivery_outbox.pynew file mode 100644index 000000000..d5122389f--- /dev/null+++ b/agent/tests/test_scheduled_delivery_outbox.py@@ -0,0 +1,196 @@+"""Briefing delivery is an outbox, not a callback (#942).++The dispatch path returns once the agent attempt is *accepted*, so "the job+fired" and "the briefing is ready" are different facts. Delivery therefore+hangs off a persisted row whose only source of truth is the store: a crash+between the two can cost the speed of a delivery, never the fact that one is+owed, and no restart or retry can send the same briefing twice.+"""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from src.scheduled_research.executor import ScheduledResearchExecutor+from src.scheduled_research.models import (+ DeliveryStatus,+ JobStatus,+ ScheduledResearchJob,+)+from src.scheduled_research.store import ScheduledResearchJobStore+++class _Sender:+ def __init__(self, fail_times: int = 0) -> None:+ self.sent: list[tuple[str, str | None, str]] = []+ self._fail_times = fail_times++ async def __call__(self, channel: str, target: str | None, text: str) -> None:+ if self._fail_times > 0:+ self._fail_times -= 1+ raise RuntimeError("channel unreachable")+ self.sent.append((channel, target, text))+++def _store(tmp_path: Path) -> ScheduledResearchJobStore:+ return ScheduledResearchJobStore(tmp_path / "jobs.json")+++def _job(**overrides) -> ScheduledResearchJob:+ base = dict(id="j1", prompt="brief me", schedule="60000", next_run_at=0)+ base.update(overrides)+ return ScheduledResearchJob(**base)+++def _executor(store, *, reader=None, sender=None, dispatch=None, now=1_000) -> ScheduledResearchExecutor:+ async def _default_dispatch(job):+ return "sess-1"++ return ScheduledResearchExecutor(+ store,+ dispatch or _default_dispatch,+ now_fn=lambda: now,+ enabled=False,+ briefing_reader=reader,+ channel_sender=sender,+ max_consecutive_failures=3,+ )+++def test_a_job_without_a_channel_never_arms_the_outbox(tmp_path: Path) -> None:+ """Delivery is opt-in: no channel, no row, nothing sent anywhere."""+ store = _store(tmp_path)+ store.upsert(_job())+ sender = _Sender()+ executor = _executor(store, reader=lambda _s: ("completed", "text"), sender=sender)++ asyncio.run(executor.tick(now_ms=1_000))++ assert store.get("j1").delivery.status is DeliveryStatus.NONE+ assert sender.sent == []+++def test_a_firing_arms_the_outbox_and_the_sweep_delivers_it(tmp_path: Path) -> None:+ store = _store(tmp_path)+ store.upsert(_job(delivery_channel="telegram", delivery_target="chat-9"))+ sender = _Sender()+ executor = _executor(store, reader=lambda _s: ("completed", "VERDICT: hold"), sender=sender)++ asyncio.run(executor.tick(now_ms=1_000))++ record = store.get("j1").delivery+ assert record.status is DeliveryStatus.SENT+ assert record.session_id == "sess-1"+ assert record.key == "j1:sess-1:telegram"+ assert sender.sent == [("telegram", "chat-9", "VERDICT: hold")]+++def test_a_run_still_in_flight_is_left_for_a_later_sweep(tmp_path: Path) -> None:+ """The briefing does not exist yet; the row must survive to try again."""+ store = _store(tmp_path)+ store.upsert(_job(delivery_channel="telegram"))+ sender = _Sender()+ executor = _executor(store, reader=lambda _s: None, sender=sender)++ asyncio.run(executor.tick(now_ms=1_000))++ assert store.get("j1").delivery.status is DeliveryStatus.PENDING+ assert sender.sent == []+++def test_a_second_sweep_does_not_send_the_same_briefing_again(tmp_path: Path) -> None:+ store = _store(tmp_path)+ store.upsert(_job(delivery_channel="telegram"))+ sender = _Sender()+ executor = _executor(store, reader=lambda _s: ("completed", "text"), sender=sender)++ asyncio.run(executor.tick(now_ms=1_000))+ asyncio.run(executor.sweep_deliveries())+ asyncio.run(executor.sweep_deliveries())++ assert len(sender.sent) == 1+++def test_a_restart_delivers_what_the_previous_process_never_sent(tmp_path: Path) -> None:+ """The row is the source of truth, so a new process finishes the work.++ This is the case a callback alone cannot cover: the run finished while the+ poller was down, and no in-memory subscriber exists any more.+ """+ store = _store(tmp_path)+ store.upsert(_job(delivery_channel="telegram"))+ asyncio.run(_executor(store, reader=lambda _s: None, sender=_Sender()).tick(now_ms=1_000))+ assert store.get("j1").delivery.status is DeliveryStatus.PENDING++ # A brand new executor over the same store — the process restarted.+ sender = _Sender()+ revived = _executor(_store(tmp_path), reader=lambda _s: ("completed", "late"), sender=sender)+ asyncio.run(revived.sweep_deliveries())++ assert sender.sent == [("telegram", None, "late")]+ assert store.get("j1").delivery.status is DeliveryStatus.SENT+++def test_a_failed_run_is_terminal_because_no_briefing_will_ever_exist(tmp_path: Path) -> None:+ store = _store(tmp_path)+ store.upsert(_job(delivery_channel="telegram"))+ sender = _Sender()+ executor = _executor(store, reader=lambda _s: ("failed", ""), sender=sender)++ asyncio.run(executor.tick(now_ms=1_000))++ record = store.get("j1").delivery+ assert record.status is DeliveryStatus.FAILED+ assert "run failed" in (record.error or "")+ assert sender.sent == []+++def test_a_channel_outage_is_retried_rather_than_written_off(tmp_path: Path) -> None:+ """A transient send failure must not throw the briefing away."""+ store = _store(tmp_path)+ store.upsert(_job(delivery_channel="telegram"))+ sender = _Sender(fail_times=2)+ executor = _executor(store, reader=lambda _s: ("completed", "text"), sender=sender)++ asyncio.run(executor.tick(now_ms=1_000))+ assert store.get("j1").delivery.status is DeliveryStatus.PENDING+ assert store.get("j1").delivery.attempts == 1++ asyncio.run(executor.sweep_deliveries())+ assert store.get("j1").delivery.status is DeliveryStatus.PENDING++ asyncio.run(executor.sweep_deliveries())+ assert store.get("j1").delivery.status is DeliveryStatus.SENT+ assert len(sender.sent) == 1+++def test_delivery_gives_up_once_the_attempt_threshold_is_reached(tmp_path: Path) -> None:+ """Retrying forever would be its own failure mode."""+ store = _store(tmp_path)+ store.upsert(_job(delivery_channel="telegram"))+ sender = _Sender(fail_times=99)+ executor = _executor(store, reader=lambda _s: ("completed", "text"), sender=sender)++ asyncio.run(executor.tick(now_ms=1_000))+ for _ in range(5):+ asyncio.run(executor.sweep_deliveries())++ record = store.get("j1").delivery+ assert record.status is DeliveryStatus.FAILED+ assert record.attempts == 3+ assert sender.sent == []+++def test_the_sweep_is_inert_without_collaborators(tmp_path: Path) -> None:+ """An install with no channel runtime must not be changed by any of this."""+ store = _store(tmp_path)+ store.upsert(_job(delivery_channel="telegram"))+ executor = _executor(store)++ asyncio.run(executor.tick(now_ms=1_000))++ assert asyncio.run(executor.sweep_deliveries()) == 0+ assert store.get("j1").delivery.status is DeliveryStatus.PENDING