Repository navigation
fix(nats): clean up failed JetStream request subscriptions #3097
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
Open
Kuang-xianxin
wants to merge
3
commits into
ag2ai:main
Choose a base branch
from
Kuang-xianxin:codex/cleanup-jetstream-request-subscriptions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| from collections.abc import AsyncIterator | ||
| from typing import TypeAlias | ||
| from unittest.mock import AsyncMock | ||
|
|
||
| import anyio | ||
| import nats | ||
| import pytest | ||
| import pytest_asyncio | ||
| from nats.aio.client import Client | ||
| from nats.js import JetStreamContext | ||
| from nats.js.api import PubAck | ||
|
|
||
| from faststream.nats import NatsBroker | ||
|
|
||
| from .settings import Settings | ||
|
|
||
| pytestmark = [pytest.mark.asyncio(), pytest.mark.nats()] | ||
|
|
||
| RequestTransport: TypeAlias = tuple[NatsBroker, Client, list[bytes]] | ||
|
|
||
|
|
||
| @pytest_asyncio.fixture() | ||
| async def request_transport( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| ) -> AsyncIterator[RequestTransport]: | ||
| connection = Client() | ||
| commands: list[bytes] = [] | ||
|
|
||
| async def send_command(command: bytes) -> None: | ||
| await anyio.lowlevel.checkpoint() | ||
| commands.append(command) | ||
|
|
||
| monkeypatch.setattr(connection, "_send_command", send_command) | ||
| monkeypatch.setattr(connection, "_flush_pending", AsyncMock()) | ||
| monkeypatch.setattr(nats, "connect", AsyncMock(return_value=connection)) | ||
| broker = NatsBroker() | ||
| await broker.connect() | ||
| try: | ||
| yield broker, connection, commands | ||
| finally: | ||
| await connection.close() | ||
|
|
||
|
|
||
| async def test_failed_reply_limit_setup_removes_reply_subscription( | ||
| request_transport: RequestTransport, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| ) -> None: | ||
| broker, connection, commands = request_transport | ||
| send_unsubscribe = connection._send_unsubscribe | ||
|
|
||
| async def fail_initial_unsubscribe(sid: int, limit: int = 0) -> None: | ||
| if limit: | ||
| raise RuntimeError | ||
| await send_unsubscribe(sid, limit) | ||
|
|
||
| monkeypatch.setattr(connection, "_send_unsubscribe", fail_initial_unsubscribe) | ||
|
|
||
| with pytest.raises(RuntimeError): | ||
| await broker.request("request", "jobs", stream="jobs", timeout=0.01) | ||
|
|
||
| assert (connection._subs, commands[-1].split()) == ({}, [b"UNSUB", b"1"]) | ||
|
|
||
|
|
||
| @pytest.mark.connected() | ||
| async def test_real_timed_out_requests_remove_reply_subscriptions( | ||
| settings: Settings, | ||
| queue: str, | ||
| ) -> None: | ||
| async with NatsBroker(settings.url) as broker: | ||
| connection = broker._connection | ||
| assert connection is not None | ||
| jetstream = connection.jetstream() | ||
| await jetstream.add_stream(name=queue, subjects=[queue]) | ||
| try: | ||
| # Creating the stream first includes the shared JetStream reply mux. | ||
| subscriptions = set(connection._subs) | ||
| with pytest.raises(TimeoutError): | ||
| await broker.request("request", queue, stream=queue, timeout=0.05) | ||
|
|
||
| await connection.flush() | ||
| assert set(connection._subs) == subscriptions | ||
| finally: | ||
| await jetstream.delete_stream(queue) | ||
|
|
||
|
|
||
| async def test_cancelled_jetstream_request_unsubscribes_under_cancel_scope( | ||
| request_transport: RequestTransport, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| ) -> None: | ||
| broker, connection, commands = request_transport | ||
|
|
||
| async def publish(*args: object, **kwargs: object) -> None: | ||
| scope.cancel() | ||
| await anyio.sleep_forever() | ||
|
|
||
| monkeypatch.setattr(JetStreamContext, "publish", publish) | ||
| with anyio.CancelScope() as scope: | ||
| await broker.request("request", "jobs", stream="jobs") | ||
|
|
||
| assert (scope.cancelled_caught, connection._subs, commands[-1].split()) == ( | ||
| True, | ||
| {}, | ||
| [b"UNSUB", b"1"], | ||
| ) | ||
|
|
||
|
|
||
| async def test_closed_connection_preserves_publish_error( | ||
| request_transport: RequestTransport, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| ) -> None: | ||
| broker, connection, _ = request_transport | ||
|
|
||
| async def publish(*args: object, **kwargs: object) -> PubAck: | ||
| await connection.close() | ||
| raise nats.errors.TimeoutError | ||
|
|
||
| monkeypatch.setattr(JetStreamContext, "publish", publish) | ||
| with pytest.raises(nats.errors.TimeoutError): | ||
| await broker.request("request", "jobs", stream="jobs") | ||
|
|
||
| assert not connection._subs |
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.
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.
Add type hints
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.
I don’t like your parameterized tests because of the large number of branches.
Let’s write a separate test for each parameter.I don’t like your parameterized tests because of the large number of branches.
Let’s write a separate test for each parameter.
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.
Updated in c7a7fd4: timeout, publish failure, reply-limit failure, and cancellation now have separate tests with fixed expectations. Shared real-server setup is in a typed fixture; test arguments, fixture yields, and callbacks have type hints. The connected tests still repeat each failure three times to check for accumulating subscriptions.
Validation: 27 cleanup/request tests passed with real NATS 2.14.6, and the changed test module passes strict mypy plus Ruff lint/format. The production fix is unchanged.
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.
Reworked in a99dd63 following the repository testing-patterns skill: reduced nine cleanup cases to four distinct boundaries, removed duplicate success/failure coverage and the single-use fixture, used the existing settings/queue fixtures, and consolidated the subscription assertions. Existing request tests cover successful replies.
The named cleanup/request files pass all 22 tests with real NATS 2.14.6; reverting the production fix gives 3 failures. Disabling shielding and removing connection-error suppression each fail their specific retained test. Ruff/format, codespell, strict test typing, and configured mypy over 516 source files pass. Production code is unchanged.