Repository navigation
fix(sender): settle sends when the loop terminates #170
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Ehsan-hash
wants to merge
2
commits into
agentclientprotocol:main
from
Ehsan-hash:fix/sender-terminal-state
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import json | ||
| from typing import Any, cast | ||
|
|
||
| import pytest | ||
|
|
||
| from acp.task import MessageSender, TaskSupervisor | ||
|
|
||
|
|
||
| class _ControlledWriter: | ||
| def __init__(self, *, error: BaseException | None = None) -> None: | ||
| self.error = error | ||
| self.drain_started = asyncio.Event() | ||
| self.release = asyncio.Event() | ||
| self.writes: list[bytes] = [] | ||
|
|
||
| def write(self, payload: bytes) -> None: | ||
| self.writes.append(payload) | ||
|
|
||
| async def drain(self) -> None: | ||
| self.drain_started.set() | ||
| await self.release.wait() | ||
| if self.error is not None: | ||
| raise self.error | ||
|
|
||
|
|
||
| async def _wait_for_queue_size(sender: MessageSender, size: int) -> None: | ||
| async def queue_reached_size() -> None: | ||
| while sender._queue.qsize() < size: | ||
| await asyncio.sleep(0) | ||
|
|
||
| await asyncio.wait_for(queue_reached_size(), timeout=1) | ||
|
|
||
|
|
||
| async def _assert_tasks_finish(tasks: list[asyncio.Task[Any]]) -> None: | ||
| _done, pending = await asyncio.wait(tasks, timeout=1) | ||
| try: | ||
| assert not pending, f"send tasks still pending: {pending}" | ||
| finally: | ||
| for task in pending: | ||
| task.cancel() | ||
| await asyncio.gather(*tasks, return_exceptions=True) | ||
|
|
||
|
|
||
| async def _close_supervisor(supervisor: TaskSupervisor, tasks: list[asyncio.Task[Any]]) -> None: | ||
| await supervisor.shutdown() | ||
| for task in tasks: | ||
| if not task.done(): | ||
| task.cancel() | ||
| await asyncio.gather(*tasks, return_exceptions=True) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_writer_failure_settles_active_queued_and_late_sends() -> None: | ||
| error = BrokenPipeError("writer failed") | ||
| writer = _ControlledWriter(error=error) | ||
| supervisor = TaskSupervisor(source="test") | ||
| sender = MessageSender(cast(asyncio.StreamWriter, writer), supervisor) | ||
| tasks: list[asyncio.Task[Any]] = [] | ||
|
|
||
| try: | ||
| first = asyncio.create_task(sender.send({"id": 1}), name="send-1") | ||
| tasks.append(first) | ||
| await asyncio.wait_for(writer.drain_started.wait(), timeout=1) | ||
|
|
||
| second = asyncio.create_task(sender.send({"id": 2}), name="send-2") | ||
| tasks.append(second) | ||
| await _wait_for_queue_size(sender, 1) | ||
|
|
||
| writer.release.set() | ||
| with pytest.raises(BrokenPipeError, match="writer failed"): | ||
| await first | ||
|
|
||
| late = asyncio.create_task(sender.send({"id": 3}), name="send-3") | ||
| tasks.append(late) | ||
| await _assert_tasks_finish(tasks) | ||
|
|
||
| for task in (second, late): | ||
| assert isinstance(task.exception(), BrokenPipeError) | ||
| assert str(task.exception()) == "writer failed" | ||
| finally: | ||
| await _close_supervisor(supervisor, tasks) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_supervisor_shutdown_settles_active_queued_and_late_sends() -> None: | ||
| writer = _ControlledWriter() | ||
| supervisor = TaskSupervisor(source="test") | ||
| sender = MessageSender(cast(asyncio.StreamWriter, writer), supervisor) | ||
| tasks: list[asyncio.Task[Any]] = [] | ||
|
|
||
| try: | ||
| first = asyncio.create_task(sender.send({"id": 1}), name="send-1") | ||
| tasks.append(first) | ||
| await asyncio.wait_for(writer.drain_started.wait(), timeout=1) | ||
|
|
||
| second = asyncio.create_task(sender.send({"id": 2}), name="send-2") | ||
| tasks.append(second) | ||
| await _wait_for_queue_size(sender, 1) | ||
|
|
||
| await supervisor.shutdown() | ||
| late = asyncio.create_task(sender.send({"id": 3}), name="send-3") | ||
| tasks.append(late) | ||
| await _assert_tasks_finish(tasks) | ||
|
|
||
| for task in tasks[:2]: | ||
| assert task.cancelled() | ||
| assert late.cancelled() | ||
| finally: | ||
| await _close_supervisor(supervisor, tasks) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_shutdown_before_sender_loop_starts_rejects_later_send() -> None: | ||
| writer = _ControlledWriter() | ||
| supervisor = TaskSupervisor(source="test") | ||
| sender = MessageSender(cast(asyncio.StreamWriter, writer), supervisor) | ||
| tasks: list[asyncio.Task[Any]] = [] | ||
|
|
||
| try: | ||
| await supervisor.shutdown() | ||
| late = asyncio.create_task(sender.send({"id": 1}), name="send-after-shutdown") | ||
| tasks.append(late) | ||
| await _assert_tasks_finish(tasks) | ||
| assert late.cancelled() | ||
| finally: | ||
| await _close_supervisor(supervisor, tasks) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_healthy_sends_preserve_order_and_graceful_close() -> None: | ||
| writer = _ControlledWriter() | ||
| supervisor = TaskSupervisor(source="test") | ||
| sender = MessageSender(cast(asyncio.StreamWriter, writer), supervisor) | ||
| tasks: list[asyncio.Task[Any]] = [] | ||
| closing: asyncio.Task[None] | None = None | ||
|
|
||
| try: | ||
| tasks.extend([ | ||
| asyncio.create_task(sender.send({"id": 1}), name="send-1"), | ||
| asyncio.create_task(sender.send({"id": 2}), name="send-2"), | ||
| ]) | ||
| await asyncio.wait_for(writer.drain_started.wait(), timeout=1) | ||
| await _wait_for_queue_size(sender, 1) | ||
|
|
||
| closing = asyncio.create_task(sender.close(), name="sender-close") | ||
| await asyncio.sleep(0) | ||
| assert not closing.done() | ||
| assert [json.loads(payload)["id"] for payload in writer.writes] == [1] | ||
|
|
||
| writer.release.set() | ||
| await asyncio.gather(*tasks) | ||
| await asyncio.wait_for(closing, timeout=1) | ||
| assert [json.loads(payload)["id"] for payload in writer.writes] == [1, 2] | ||
|
|
||
| late = asyncio.create_task(sender.send({"id": 3}), name="send-after-close") | ||
| tasks.append(late) | ||
| await _assert_tasks_finish([late]) | ||
| assert late.cancelled() | ||
| finally: | ||
| if closing is not None and not closing.done(): | ||
| closing.cancel() | ||
| if closing is not None: | ||
| await asyncio.gather(closing, return_exceptions=True) | ||
| await _close_supervisor(supervisor, tasks) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems unnecessarily complicated, what does it do differently than this simple change?
send() needs to listen to a completeness flag of course.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for reviewing this, @frostming. For the active send when the loop is cancelled, I agree that
item.future.cancel()is sufficient.With the terminal flag you mentioned, the remaining cases are cancelling the queued futures too, and detecting cancellation before
_loop()starts (its exception handler never runs in that case, which is why there is a task-done callback). The writer-failure path separately preserves the original exception, such asBrokenPipeError, for active, queued and later sends instead of turning it into cancellation.Those are the cases covered by the sender lifecycle regressions and the two-request connection regression. A simpler version using direct cancellation plus the terminal flag, queue cleanup and pre-start handling could preserve the same behaviour; the helper itself is not required.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok, then we can add the
_on_task_donecallback to clear all pending futures.