"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(channels): avoid hang splitting telegram fenced markdown chunks
santhreal497274c6889c
diff --git a/agent/src/channels/telegram.py b/agent/src/channels/telegram.pyindex 668c4c2cb..64dc54c39 100644--- a/agent/src/channels/telegram.py+++ b/agent/src/channels/telegram.py@@ -50,6 +50,10 @@ def _split_telegram_markdown(content: str, max_len: int) -> list[str]:content = content.lstrip()if not content:return []+ # Non-positive max_len cannot advance the cut pointer; return unsplit+ # (same policy as split_message).+ if max_len <= 0:+ return [content]if len(content) <= max_len:return [content]@@ -89,26 +93,38 @@ def _split_telegram_markdown(content: str, max_len: int) -> list[str]:min_code_pos = len(fence)if content.startswith(fence + "\n"):min_code_pos += 1- if pos < min_code_pos and min_code_pos + len(closing) > max_len:- chunks.append(content[:max_len])- content = content[max_len:].lstrip()- continue+ # Fence-line-only cuts never consume body; force past the header.+ if pos <= min_code_pos:+ pos = max_lenif pos + len(closing) > max_len:budget = max_len - len(closing)- if budget > 0:+ if budget > min_code_pos:recut = content[:budget]adjusted = recut.rfind("\n")- if adjusted <= 0:+ if adjusted <= min_code_pos:adjusted = recut.rfind(" ")- pos = adjusted if adjusted > 0 else budget+ pos = adjusted if adjusted > min_code_pos else budget+ elif budget > 0:+ chunks.append(content[:max_len])+ content = content[max_len:].lstrip()+ continueelse:closing = "```"pos = max_len - len(closing)+ if pos <= min_code_pos:+ chunks.append(content[:max_len])+ content = content[max_len:].lstrip()+ continuechunks.append(content[:pos] + closing)remainder = content[pos:]if remainder.startswith("\n"):remainder = remainder[1:]- content = f"{fence}\n{remainder}"+ nxt = f"{fence}\n{remainder}"+ if nxt == content or len(nxt) >= len(content):+ chunks.append(content[:max_len])+ content = content[max_len:].lstrip()+ continue+ content = nxtcontinuechunks.append(content[:pos])diff --git a/agent/tests/test_telegram_split_fence_hang.py b/agent/tests/test_telegram_split_fence_hang.pynew file mode 100644index 000000000..721405135--- /dev/null+++ b/agent/tests/test_telegram_split_fence_hang.py@@ -0,0 +1,113 @@+"""Regression: telegram markdown split must not hang on long fenced bodies."""++from __future__ import annotations++import signal+import sys+import types+++def _stub_telegram_deps() -> None:+ """Install minimal stubs so telegram.py imports without python-telegram-bot."""++ def _mod(name: str) -> types.ModuleType:+ mod = types.ModuleType(name)+ sys.modules[name] = mod+ return mod++ tg = _mod("telegram")++ class _Accepting:+ def __init__(self, *args, **kwargs) -> None:+ pass++ for name in (+ "BotCommand",+ "InlineKeyboardButton",+ "InlineKeyboardMarkup",+ "ReactionTypeEmoji",+ "ReplyParameters",+ "Update",+ ):+ setattr(tg, name, _Accepting)++ err = _mod("telegram.error")+ for name in ("BadRequest", "NetworkError", "TimedOut"):+ setattr(err, name, type(name, (Exception,), {}))++ ext = _mod("telegram.ext")+ for name in (+ "Application",+ "CallbackQueryHandler",+ "ContextTypes",+ "MessageHandler",+ "filters",+ ):+ setattr(ext, name, _Accepting)++ _mod("telegram.request").HTTPXRequest = _Accepting+++_stub_telegram_deps()++from src.channels.telegram import ( # noqa: E402+ TELEGRAM_MAX_MESSAGE_LEN,+ _split_telegram_markdown,+)+++class _Hang(Exception):+ pass+++def _alarm_handler(signum, frame) -> None: # noqa: ANN001+ raise _Hang()+++def test_split_telegram_markdown_long_fence_body_no_hang() -> None:+ """Long fenced line with no breaks must finish under the production limit."""+ body = "a" * 5000+ content = f"```\n{body}"+ signal.signal(signal.SIGALRM, _alarm_handler)+ signal.alarm(2)+ try:+ chunks = _split_telegram_markdown(content, TELEGRAM_MAX_MESSAGE_LEN)+ finally:+ signal.alarm(0)++ assert chunks+ assert all(isinstance(c, str) and c for c in chunks)+ # Body must appear across chunks (close/reopen may repeat the fence marker).+ joined_body = "".join(c.replace("```", "").replace("\n", "") for c in chunks)+ assert body in joined_body or joined_body.count("a") >= len(body)+++def test_split_telegram_markdown_closed_long_fence_no_hang() -> None:+ content = "```\n" + "x" * 5000 + "\n```"+ signal.signal(signal.SIGALRM, _alarm_handler)+ signal.alarm(2)+ try:+ chunks = _split_telegram_markdown(content, TELEGRAM_MAX_MESSAGE_LEN)+ finally:+ signal.alarm(0)+ assert len(chunks) >= 2+ assert sum(c.count("x") for c in chunks) >= 5000+++def test_split_telegram_markdown_nonpositive_max_len_returns_unsplit() -> None:+ content = "hello world"+ assert _split_telegram_markdown(content, 0) == [content]+ assert _split_telegram_markdown(content, -1) == [content]+++def test_split_telegram_markdown_short_fence_mid_limit_no_hang() -> None:+ """Fence at index 0 with mid-size max_len must not rebuild the same chunk."""+ content = '```\n om/yyyyyyyyyyyyyyyyyyyy)\n\na"'+ signal.signal(signal.SIGALRM, _alarm_handler)+ signal.alarm(2)+ try:+ chunks = _split_telegram_markdown(content, 32)+ finally:+ signal.alarm(0)+ assert chunks+ assert "".join(chunks).replace("```", "").count("y") >= content.count("y")