Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: validate swarm tails precisely and exercise Matrix optional dependency path

Haozhe Wu0d384e9a79cf
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 48e8a387e..af5d02392 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -102,12 +102,13 @@ jobs:
# OpenBB Workspace bridge would report green while never being exercised.
# `stats` is included for the same reason: the quantlib econometrics
# tests skip without statsmodels/arch, and skipped is not tested.
- run: pip install -e ".[dev,openbb,stats,anthropic]"
+ run: pip install -e ".[dev,openbb,stats,anthropic,matrix]"
- name: Verify optional extras under test are importable
# Fails loudly if an extra stops resolving, instead of letting its
# suite silently degrade to skips.
run: |
+ python -c "import nio; from src.channels.matrix import MatrixChannel"
python -c "import openbb_ai, importlib.metadata as m; print('openbb-ai', m.version('openbb-ai'))"
python -c "import statsmodels; print('statsmodels', statsmodels.__version__)"
python -c "import arch; print('arch', arch.__version__)"
diff --git a/agent/src/swarm/store.py b/agent/src/swarm/store.py
index 788321185..3e1995caa 100644
--- a/agent/src/swarm/store.py
+++ b/agent/src/swarm/store.py
@@ -17,6 +17,8 @@ import threading
import time
import uuid
from datetime import datetime, timezone
+from pydantic import ValidationError
+
from pathlib import Path
from src.config.accessor import get_env_config
@@ -277,22 +279,26 @@ class SwarmStore:
return []
events: list[SwarmEvent] = []
- text = events_file.read_text(encoding="utf-8")
- lines = text.strip().splitlines()
+ text = events_file.read_bytes()
+ lines = text.splitlines()
# ``append_event`` is not atomic across processes/instances: a reader
# (the SSE poll loop, ``_persist_recovery``) can observe a final line
# that is still being written, or one cut short by a crashed host. That
# unterminated tail is not an event yet, so skip it instead of raising
# and killing the stream; the next poll sees it whole.
- tail_unterminated = bool(text) and not text.endswith("\n")
+ tail_unterminated = bool(text) and not text.endswith(b"\n")
for position, line in enumerate(lines[after_index:], start=after_index):
stripped = line.strip()
if not stripped:
continue
try:
events.append(SwarmEvent.model_validate_json(stripped))
- except ValueError:
- if tail_unterminated and position == len(lines) - 1:
+ except ValidationError as exc:
+ if (
+ tail_unterminated
+ and position == len(lines) - 1
+ and all(error["type"] == "json_invalid" for error in exc.errors())
+ ):
break
raise
return events
diff --git a/agent/tests/test_matrix_stream_end_no_preview.py b/agent/tests/test_matrix_stream_end_no_preview.py
index 62ff92057..26d95e4b1 100644
--- a/agent/tests/test_matrix_stream_end_no_preview.py
+++ b/agent/tests/test_matrix_stream_end_no_preview.py
@@ -4,6 +4,10 @@ from __future__ import annotations
import asyncio
+import pytest
+
+pytest.importorskip("nio")
+
from src.channels.matrix import MatrixChannel, _StreamBuf
@@ -79,3 +83,30 @@ class TestStreamEndWithoutPreview:
asyncio.run(channel.send_delta(chat_id, "", {"_stream_end": True}))
assert not sent
+
+
+def test_failed_preview_then_final_send_uses_real_payload_builder():
+ """Exercise buffering, preview failure and final thread delivery together."""
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock
+
+ async def scenario():
+ channel = _make_channel()
+ channel.client = SimpleNamespace(
+ room_send=AsyncMock(side_effect=[RuntimeError("temporary failure"), _FakeResponse("final")]),
+ room_typing=AsyncMock(),
+ )
+ metadata = {"thread_root_event_id": "root", "thread_reply_to_event_id": "reply"}
+ await channel.send_delta("room", "**Answer**", metadata)
+ assert channel._stream_bufs["room"].event_id is None
+ await channel.send_delta("room", "", {**metadata, "_stream_end": True})
+ sent = channel.client.room_send.call_args.kwargs
+ assert sent["content"]["body"] == "**Answer**"
+ assert sent["content"]["formatted_body"].strip() == "<p><strong>Answer</strong></p>"
+ assert sent["content"]["m.relates_to"]["rel_type"] == "m.thread"
+ assert sent["content"]["m.relates_to"]["event_id"] == "root"
+ assert "m.new_content" not in sent["content"]
+ assert sent["ignore_unverified_devices"] is True
+ assert "room" not in channel._stream_bufs
+
+ asyncio.run(scenario())
diff --git a/agent/tests/test_swarm_events_partial_tail.py b/agent/tests/test_swarm_events_partial_tail.py
index 961e0cd5b..7d39cce6b 100644
--- a/agent/tests/test_swarm_events_partial_tail.py
+++ b/agent/tests/test_swarm_events_partial_tail.py
@@ -38,3 +38,30 @@ def test_corrupt_terminated_line_still_raises(tmp_path):
f.write("not json\n")
with pytest.raises(ValueError):
store.read_events("run1")
+
+
+def test_partial_utf8_tail_is_retried_after_completion(tmp_path):
+ store = _store(tmp_path)
+ event = SwarmEvent(type="run_started", timestamp="2026-01-01T00:00:00+00:00", data={"text": "中文"})
+ encoded = (event.model_dump_json() + "\n").encode("utf-8")
+ split = encoded.index("中".encode("utf-8")) + 1
+ path = tmp_path / "run1" / "events.jsonl"
+ path.write_bytes(encoded[:split])
+ assert store.read_events("run1") == []
+ with path.open("ab") as stream:
+ stream.write(encoded[split:])
+ assert store.read_events("run1") == [event]
+
+
+def test_complete_json_with_invalid_schema_is_not_a_partial_tail(tmp_path):
+ store = _store(tmp_path)
+ (tmp_path / "run1" / "events.jsonl").write_text('{}', encoding="utf-8")
+ with pytest.raises(ValueError):
+ store.read_events("run1")
+
+
+def test_complete_unterminated_event_is_read(tmp_path):
+ store = _store(tmp_path)
+ event = SwarmEvent(type="run_started", timestamp="2026-01-01T00:00:00+00:00")
+ (tmp_path / "run1" / "events.jsonl").write_text(event.model_dump_json(), encoding="utf-8")
+ assert store.read_events("run1") == [event]