The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(streaming): trim salvaged #116385 suites to the two invariants per fix
teknium17fdeb2094ae6
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..285fe3d467d--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1 @@+HaisamAbbasdiff --git a/tests/gateway/test_stream_consumer_continuation_cut.py b/tests/gateway/test_stream_consumer_continuation_cut.pyindex 844a26ea80f..e17300b27d2 100644--- a/tests/gateway/test_stream_consumer_continuation_cut.py+++ b/tests/gateway/test_stream_consumer_continuation_cut.py@@ -42,11 +42,6 @@ class TestContinuationWordBoundary:assert consumer._continuation_text(final_text) == ("рядками (мій попередній EN-паттерн…")- def test_mid_word_prefix_backs_up_to_last_newline(self):- consumer = _make_consumer()- consumer._last_sent_text = "a\nb c\nword"- assert consumer._continuation_text("a\nb c\nword-two") == "word-two"-def test_one_long_token_keeps_original_cut(self):# No boundary to back up to: the original cut stands rather than# re-sending the whole message.@@ -54,27 +49,3 @@ class TestContinuationWordBoundary:consumer._last_sent_text = "у" * 100final_text = ("у" * 100) + ("д" * 20)assert consumer._continuation_text(final_text) == "д" * 20-- def test_prefix_ending_on_space_changes_nothing(self):- # Already at a word boundary: the cut stays exactly at the prefix end.- consumer = _make_consumer()- consumer._last_sent_text = "hello world "- assert consumer._continuation_text("hello world foo") == "foo"-- def test_fallback_prefix_takes_precedence(self):- consumer = _make_consumer()- consumer._fallback_prefix = "first line\nkeep word"- consumer._last_sent_text = "ignored older prefix "- final_text = "first line\nkeep word-zone tail"- assert consumer._continuation_text(final_text) == "word-zone tail"-- def test_unrelated_text_returns_whole_text(self):- consumer = _make_consumer()- consumer._last_sent_text = "something completely different"- final_text = "let me start over"- assert consumer._continuation_text(final_text) == final_text-- def test_full_match_returns_empty_tail(self):- consumer = _make_consumer()- consumer._last_sent_text = "всі слова повністю"- assert consumer._continuation_text("всі слова повністю") == ""\ No newline at end of filediff --git a/tests/gateway/test_stream_edit_flood_retry_after.py b/tests/gateway/test_stream_edit_flood_retry_after.pynew file mode 100644index 00000000000..eea17047640--- /dev/null+++ b/tests/gateway/test_stream_edit_flood_retry_after.py@@ -0,0 +1,65 @@+"""A flood-refused streaming edit honours the server's ``retry_after`` (#116312).++Telegram answers a flood-refused ``editMessageText`` with the seconds to wait. The stream+consumer used to ignore it and only double its own 0.8s interval, so every one of the three+allowed strikes was spent — and three more refused requests earned — inside the first ~5s of+a penalty that is usually 9s or longer.+"""++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig+++def _flood(wait: float):+ return SimpleNamespace(success=False, error=f"flood_control:{wait}", retry_after=wait)+++async def _stream(adapter, edit_interval: float, deltas: int, gap: float):+ consumer = GatewayStreamConsumer(+ adapter, "chat_1", StreamConsumerConfig(edit_interval=edit_interval, buffer_threshold=1, cursor=" ▉"))+ consumer.on_delta("Hello")+ task = asyncio.create_task(consumer.run())+ await asyncio.sleep(gap)+ for i in range(deltas):+ consumer.on_delta(f" w{i}")+ await asyncio.sleep(gap)+ consumer.finish()+ await task+ return consumer+++async def test_flood_refused_edit_waits_the_servers_retry_after_before_the_next_interim_edit():+ adapter = MagicMock()+ adapter.MAX_MESSAGE_LENGTH = 4096+ adapter.send = AsyncMock(return_value=SimpleNamespace(success=True, message_id="m1"))+ adapter.edit_message = AsyncMock(return_value=_flood(9.0))++ consumer = await _stream(adapter, edit_interval=0.02, deltas=6, gap=0.05)++ # The first refused interim edit reads retry_after=9s; every later interim tick (all inside+ # that window) is skipped instead of being sent into the same penalty.+ # Interim previews carry the cursor; the finalize path's cursor-strip edit does not.+ interim_edits = [c for c in adapter.edit_message.await_args_list if "▉" in c.kwargs["content"]]+ assert len(interim_edits) == 1+ assert consumer._current_edit_interval >= 9.0+++async def test_flood_without_retry_after_keeps_doubling_backoff():+ adapter = MagicMock()+ adapter.MAX_MESSAGE_LENGTH = 4096+ adapter.send = AsyncMock(return_value=SimpleNamespace(success=True, message_id="m1"))+ adapter.edit_message = AsyncMock(return_value=SimpleNamespace(success=False, error="flood_control:9"))++ consumer = await _stream(adapter, edit_interval=0.02, deltas=6, gap=0.05)++ interim_edits = [c for c in adapter.edit_message.await_args_list if "▉" in c.kwargs["content"]]+ assert len(interim_edits) >= 2 # 0.04s, 0.08s, 0.16s: the legacy doubling ladder keeps firing+ assert consumer._current_edit_interval <= 10.0+ assert consumer._flood_strikes >= 2diff --git a/tests/gateway/test_telegram_shared_outbound_budget.py b/tests/gateway/test_telegram_shared_outbound_budget.pyindex d0971c98791..a59abc9bedb 100644--- a/tests/gateway/test_telegram_shared_outbound_budget.py+++ b/tests/gateway/test_telegram_shared_outbound_budget.py@@ -37,7 +37,7 @@ async def test_interim_edit_skipped_when_slot_busy_but_final_edit_never_gated():result = await adapter.edit_message("c1", "900", "part one", finalize=False)assert result.success is True # consumed a slot on the first real edit- busy = _chat_slot_remaining(adapter, "c1")+ busy = adapter._chat_outbound_slot_remaining( "c1")assert busy > 0skipped = await adapter.edit_message("c1", "900", "part two", finalize=False)@@ -49,18 +49,6 @@ async def test_interim_edit_skipped_when_slot_busy_but_final_edit_never_gated():assert adapter._bot.edit_message_text.await_count == 2 # the final edit is never gated-async def test_skipped_interim_edit_consumes_no_slot():- """A skipped interim edit returns success but does NOT consume the slot — the next interim edit is- still allowed to fire."""- adapter = _adapter(AsyncMock())- await adapter.edit_message("c1", "900", "one", finalize=False)- await adapter.edit_message("c1", "900", "two", finalize=False) # skipped, no slot consumed- await adapter.edit_message("c1", "900", "three", finalize=False) # slot still held, skipped-- assert adapter._bot.edit_message_text.await_count == 1--@pytest.mark.asyncioasync def test_send_waits_for_held_slot():"""A send to a chat whose slot is held defers until the slot opens and then fires exactly once."""@@ -82,36 +70,3 @@ async def test_send_waits_for_held_slot():assert result.success is Trueassert adapter._bot.send_message.await_count == 1assert sleeps, "send should have awaited asyncio.sleep for the pending slot"---def _chat_slot_remaining(adapter: TelegramAdapter, chat_id: str) -> float:- return adapter._chat_outbound_slot_remaining(chat_id)---async def test_slot_is_per_chat():- """The shared slot is keyed per chat: one chat's burst must not gate another chat."""- adapter = _adapter(AsyncMock())- await adapter.edit_message("c1", "900", "one", finalize=False) # holds c1's slot- assert _chat_slot_remaining(adapter, "c1") > 0-- result = await adapter.send("c2", "hello other")- assert result.success is True- assert adapter._bot.send_message.await_count == 1 # c2 untouched by c1's slot- assert _chat_slot_remaining(adapter, "c2") > 0 # c2 consumed its own slot---async def test_slot_expiry_lets_interim_edit_fire():- """Once the budget window passes, the slot opens and an interim edit is allowed again."""- adapter = _adapter(AsyncMock())- await adapter.edit_message("c1", "900", "one", finalize=False)- assert adapter._bot.edit_message_text.await_count == 1-- deadline = adapter._telegram_chat_outbound_slot_until["c1"]- adapter._telegram_chat_outbound_slot_until["c1"] = _now() - 1.0 # expire the window- assert deadline is not None-- result = await adapter.edit_message("c1", "900", "two", finalize=False)- assert result.success is True- assert adapter._bot.edit_message_text.await_count == 2 # fired again now that the slot is free\ No newline at end of file