"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: preserve scheduler opt-in, sync failures and zero token counts
Haozhe Wu068ec3bd6c44
diff --git a/agent/src/br_data/scheduling.py b/agent/src/br_data/scheduling.pyindex cb0eab483..d74579493 100644--- a/agent/src/br_data/scheduling.py+++ b/agent/src/br_data/scheduling.py@@ -35,9 +35,9 @@ The runnable itself is ``sync.run_sync``, registered under the literal key``"br_data.run_sync"`` in :mod:`src.scheduling.registry`. It is SYNC bydesign: the executor's internal-run supervisor offloads sync callables via``asyncio.to_thread``, so the (network-heavy) sync pass never runs on the-event loop. Per-source failures are reported in ``run_sync``'s return value,-not raised; an exception that does escape lands in the executor's existing-failure path (``failure_kind="dispatch"``, bounded backoff). The retired+event loop. The registry wrapper converts per-source errors in ``run_sync``'s+report into an exception naming the failed sources. This reaches the executor's+existing failure path (``failure_kind="dispatch"``, bounded backoff). The retired``python -m src.br_data daemon`` loop is replaced by this job (its``run_daemon`` now prints a migration notice and returns 0)."""diff --git a/agent/src/scheduling/registry.py b/agent/src/scheduling/registry.pyindex 5c555d4db..f6428ff18 100644--- a/agent/src/scheduling/registry.py+++ b/agent/src/scheduling/registry.py@@ -161,12 +161,20 @@ def _br_data_run_sync() -> None:Backs the ``br_data.run_sync`` key: daily sync, opt-in via``VIBE_BR_SYNC_ENABLED``; replaces the retired ``src.br_data`` daemon —- per-source failures are reported in ``run_sync``'s return value, not- raised (see :mod:`src.br_data.scheduling`).+ Per-source errors become a failed scheduled attempt, so the executor+ records the failure and applies its existing retry budget."""from src.br_data.sync import run_sync- run_sync()+ report = run_sync()+ failed = sorted(+ name for name, outcome in report.items()+ if isinstance(outcome, dict) and "error" in outcome+ )+ if failed:+ # Report source names only; upstream diagnostics can carry local+ # paths or credentials and must not be copied into the job store.+ raise RuntimeError(f"Brazilian dataset sync failed for: {', '.join(failed)}")# ---------------------------------------------------------------------------diff --git a/agent/tests/scheduling/test_br_sync_outcomes.py b/agent/tests/scheduling/test_br_sync_outcomes.pynew file mode 100644index 000000000..d8412d7ba--- /dev/null+++ b/agent/tests/scheduling/test_br_sync_outcomes.py@@ -0,0 +1,53 @@+"""A source failure must reach the scheduled job's retry bookkeeping."""++import asyncio++import pytest++from src.scheduled_research.executor import ScheduledResearchExecutor+from src.scheduled_research.internal_dispatch import resolve_scheduled_internal_callable+from src.scheduled_research.models import JobStatus, ScheduledResearchJob+from src.scheduled_research.store import ScheduledResearchJobStore++[email protected]("failed", [False, True])+def test_sync_report_drives_job_outcome(tmp_path, monkeypatch, failed):+ from src.br_data import sync++ reports = [+ {"db": "/private/database", "bcb": {"rows": 12},+ "tesouro": {"error": "private upstream diagnostic"} if failed else {"rows": 0}},+ {"bcb": {"rows": 12}, "tesouro": {"rows": 0}},+ ]+ monkeypatch.setattr(sync, "run_sync", lambda: reports.pop(0))+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ store.upsert(ScheduledResearchJob(+ id="system:br-data-sync", prompt="", schedule="1000",+ next_run_at=1000, created_at=0, source_type="system",+ executor_kind="internal", internal_callable="br_data.run_sync",+ ))++ async def scenario():+ executor = ScheduledResearchExecutor(+ store, lambda job: None, enabled=True, now_fn=lambda: 1000,+ retry_base_delay_ms=0, retry_max_delay_ms=0,+ internal_dispatcher=resolve_scheduled_internal_callable,+ )+ await executor.tick(1000)+ await asyncio.gather(*executor._internal._tasks)+ job = store.get("system:br-data-sync")+ assert job.status == (JobStatus.PENDING if failed else JobStatus.COMPLETED)+ assert job.consecutive_failures == int(failed)+ if failed:+ assert job.failure_kind == "dispatch"+ assert "tesouro" in job.last_error+ assert "private" not in job.last_error+ await executor.tick(job.next_run_at)+ await asyncio.gather(*executor._internal._tasks)+ recovered = store.get(job.id)+ assert recovered.status == JobStatus.COMPLETED+ assert recovered.consecutive_failures == 0+ assert recovered.last_error is None+ await executor.stop()++ asyncio.run(scenario())diff --git a/frontend/src/components/chat/SwarmDashboard.tsx b/frontend/src/components/chat/SwarmDashboard.tsxindex b08237fbe..6953f40d4 100644--- a/frontend/src/components/chat/SwarmDashboard.tsx+++ b/frontend/src/components/chat/SwarmDashboard.tsx@@ -123,10 +123,11 @@ function agentKey(agent: SwarmAgentStatus): string {}function agentTokenText(agent: SwarmAgentStatus): string | null {- const input = agent.input_tokens != null && agent.input_tokens > 0+ if (!agent.input_tokens && !agent.output_tokens) return null;+ const input = agent.input_tokens != null && Number.isFinite(agent.input_tokens) && agent.input_tokens >= 0? abbreviateNum(agent.input_tokens): null;- const output = agent.output_tokens != null && agent.output_tokens > 0+ const output = agent.output_tokens != null && Number.isFinite(agent.output_tokens) && agent.output_tokens >= 0? abbreviateNum(agent.output_tokens): null;if (!input && !output) return null;diff --git a/frontend/src/components/chat/SwarmStatusCard.tsx b/frontend/src/components/chat/SwarmStatusCard.tsxindex f7e997e5f..370033f1b 100644--- a/frontend/src/components/chat/SwarmStatusCard.tsx+++ b/frontend/src/components/chat/SwarmStatusCard.tsx@@ -107,8 +107,8 @@ function LayerStepper({);}-function formatPositive(value: number | undefined): string | null {- return value != null && Number.isFinite(value) && value > 0+function formatTokenCount(value: number | undefined): string | null {+ return value != null && Number.isFinite(value) && value >= 0? abbreviateNum(value): null;}@@ -126,8 +126,9 @@ function TokenUsageLine({status: SwarmRunStatus;t: ManifestTranslation;}) {- const input = formatPositive(status.total_input_tokens);- const output = formatPositive(status.total_output_tokens);+ if (!status.total_input_tokens && !status.total_output_tokens) return null;+ const input = formatTokenCount(status.total_input_tokens);+ const output = formatTokenCount(status.total_output_tokens);if (!input && !output) return null;const label = t("swarmStatus.tokens", {@@ -139,7 +140,7 @@ function TokenUsageLine({<div className="mt-2 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground"><spanclassName="font-mono"- title={`\u2191${String(status.total_input_tokens ?? 0)} \u2193${String(status.total_output_tokens ?? 0)}`}+ title={`\u2191${String(status.total_input_tokens ?? "—")} \u2193${String(status.total_output_tokens ?? "—")}`}>{label}</span>diff --git a/frontend/src/components/chat/__tests__/SwarmStatusCard.usage.test.tsx b/frontend/src/components/chat/__tests__/SwarmStatusCard.usage.test.tsxindex 632e0ab0a..69a064765 100644--- a/frontend/src/components/chat/__tests__/SwarmStatusCard.usage.test.tsx+++ b/frontend/src/components/chat/__tests__/SwarmStatusCard.usage.test.tsx@@ -31,6 +31,24 @@ function statusWith(overrides: Partial<SwarmRunStatus>): SwarmRunStatus {}describe("SwarmStatusCard token usage line", () => {+ it("distinguishes a reported zero from an unreported direction", () => {+ const { container } = render(+ <SwarmStatusCard status={statusWith({+ total_input_tokens: 42,+ total_output_tokens: 0,+ token_source: "provider",+ agents: [+ { agentId: "analyst", taskId: "t1", status: "done", input_tokens: 42, output_tokens: 0 },+ { agentId: "risk", taskId: "t2", status: "failed", input_tokens: 12 },+ ],+ })} />,+ );+ expect(container.textContent).toContain("↑42 ↓0 tokens");+ const rows = container.querySelector('[role="rowgroup"]');+ expect(rows?.textContent).toContain("↑42 ↓0");+ expect(rows?.textContent).toContain("↑12 ↓—");+ });+it("shows exact totals with a provider source and no caveat badge", () => {const { container } = render(<SwarmStatusCarddiff --git a/zimaos/README.md b/zimaos/README.mdindex e725afbbf..a29697542 100644--- a/zimaos/README.md+++ b/zimaos/README.md@@ -47,7 +47,7 @@ separate sidecar container or Compose profile: it now runs inside the mainapplication container as the protected system job `system:br-data-sync`, whichis seeded and fires only while the main service sets **both**`VIBE_TRADING_ENABLE_SCHEDULER=1` and `VIBE_BR_SYNC_ENABLED=1`. This compose-template sets both; set either to `0` to keep the daily network sync off.+template defaults both to `0`; explicitly set both to `1` to enable daily sync.Note the coupling this creates: `VIBE_TRADING_ENABLE_SCHEDULER=1` is themaster switch for the whole scheduled-research executor, so besides the syncjob it also runs **your own** stored scheduled research runs inside this@@ -85,9 +85,9 @@ Configure a imagem, a pasta persistente e as chaves antes de importar o Compose.O aplicativo não inicia com chaves de exemplo. A sincronização diária dos dadosbrasileiros não usa mais contêiner separado nem perfil do Compose: ela roda nocontêiner principal como tarefa de sistema protegida (`system:br-data-sync`),-ativada neste modelo por `VIBE_TRADING_ENABLE_SCHEDULER=1` e-`VIBE_BR_SYNC_ENABLED=1` (defina qualquer um dos dois como `0` para mantê-la-desativada). A primeira sincronização não ocorre ao iniciar o contêiner, mas no+desativada por padrão neste modelo. Para ativá-la, defina explicitamente+`VIBE_TRADING_ENABLE_SCHEDULER=1` e `VIBE_BR_SYNC_ENABLED=1`.+A primeira sincronização não ocorre ao iniciar o contêiner, mas nopróximo horário `VIBE_BR_SYNC_TIME` (fuso de São Paulo, padrão 21:30); essevalor vale apenas para a primeira criação da tarefa. Como a tarefa éprotegida (PATCH/DELETE via REST e CLI são recusados), mudar o horário depoisdiff --git a/zimaos/docker-compose.yml b/zimaos/docker-compose.ymlindex ca99bcb51..44ed56d6c 100644--- a/zimaos/docker-compose.yml+++ b/zimaos/docker-compose.yml@@ -81,10 +81,10 @@ services:# re-seed. NOTE: VIBE_TRADING_ENABLE_SCHEDULER=1 is the master switch# for ALL scheduled research — it also runs the user's own stored# scheduled runs (agent runs consuming model tokens) in this service.- # Set either flag to "0" to keep the daily network sync off.- VIBE_TRADING_ENABLE_SCHEDULER: "1"- VIBE_BR_SYNC_ENABLED: "1"- VIBE_BR_SYNC_TIME: "21:30"+ # Both flags default off. Set both to "1" to opt into daily sync.+ VIBE_TRADING_ENABLE_SCHEDULER: "${VIBE_TRADING_ENABLE_SCHEDULER:-0}"+ VIBE_BR_SYNC_ENABLED: "${VIBE_BR_SYNC_ENABLED:-0}"+ VIBE_BR_SYNC_TIME: "${VIBE_BR_SYNC_TIME:-21:30}"# Do NOT set VIBE_TRADING_TRUST_DOCKER_LOOPBACK here: with a LAN-published# port it would treat LAN clients as local.volumes: