Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 53 additions & 18 deletions src/s2_sdk/_s2s/_append_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from contextlib import suppress
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Any, NamedTuple
from typing import Any, Literal, NamedTuple

import s2_sdk._generated.s2.v1.s2_pb2 as pb
from s2_sdk._client import HttpClient
Expand Down Expand Up @@ -49,6 +49,13 @@
_QUEUE_MAX_SIZE = 100


class _NoInput(Enum):
VALUE = auto()


_NO_INPUT = _NoInput.VALUE


@dataclass(slots=True)
class _InflightInput:
num_records: int
Expand All @@ -63,6 +70,8 @@ class _InflightInput:
class _AppendSessionState:
inflight_inputs: deque[_InflightInput] = field(default_factory=deque)
inputs_exhausted: bool = False
# An input taken off the queue by an attempt that ended before sending it.
dequeued_input: AppendInput | None | Literal[_NoInput.VALUE] = _NO_INPUT


class _AttemptOutcome(Enum):
Expand Down Expand Up @@ -385,25 +394,17 @@ async def _body_gen(
while True:
if advised_reconnect.is_set():
return
try:
inp = input_queue.get_nowait()
except asyncio.QueueEmpty:
input_task = asyncio.create_task(input_queue.get())
advised_reconnect_task = asyncio.create_task(advised_reconnect.wait())
if session_state.dequeued_input is not _NO_INPUT:
inp = session_state.dequeued_input
session_state.dequeued_input = _NO_INPUT
else:
try:
await asyncio.wait(
{input_task, advised_reconnect_task},
return_when=asyncio.FIRST_COMPLETED,
)
if not input_task.done():
inp = input_queue.get_nowait()
except asyncio.QueueEmpty:
await _dequeue_input(session_state, input_queue, advised_reconnect)
if session_state.dequeued_input is _NO_INPUT:
return
inp = input_task.result()
finally:
input_task.cancel()
advised_reconnect_task.cancel()
await asyncio.gather(
input_task, advised_reconnect_task, return_exceptions=True
)
continue
if inp is None:
await input_queue.put(None)
session_state.inputs_exhausted = True
Expand All @@ -421,6 +422,40 @@ async def _body_gen(
yield encoded


async def _dequeue_input(
session_state: _AppendSessionState,
input_queue: asyncio.Queue[AppendInput | None],
advised_reconnect: asyncio.Event,
) -> None:
"""Wait for the next input, or for a reconnect to be advised.

The input is handed over through ``session_state.dequeued_input`` rather
than returned: the attempt can be cancelled at any await after the input
has left the queue, and it must then still reach the next attempt.
"""
input_task = asyncio.create_task(input_queue.get())
advised_reconnect_task = asyncio.create_task(advised_reconnect.wait())
try:
await asyncio.wait(
{input_task, advised_reconnect_task},
return_when=asyncio.FIRST_COMPLETED,
)
finally:
input_task.cancel()
advised_reconnect_task.cancel()
try:
await asyncio.gather(
input_task, advised_reconnect_task, return_exceptions=True
)
finally:
if (
input_task.done()
and not input_task.cancelled()
and input_task.exception() is None
):
session_state.dequeued_input = input_task.result()


def _encode_input(inp: AppendInput, compression: Compression) -> bytes:
proto = append_input_to_proto(inp)
body = proto.SerializeToString()
Expand Down
70 changes: 69 additions & 1 deletion tests/test_append_session.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
from collections.abc import AsyncGenerator, AsyncIterator
from contextlib import asynccontextmanager
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass
from typing import Any, cast
from unittest.mock import patch
Expand Down Expand Up @@ -156,3 +157,70 @@ async def inputs() -> AsyncIterator[AppendInput]:
assert err.final_attempt_error is final
else:
assert err is final


@pytest.mark.parametrize("ticks", range(1, 7))
async def test_input_dequeued_by_cancelled_attempt_is_not_lost(ticks: int) -> None:
def decoded_messages(stream: AsyncIterator[bytes]) -> AsyncIterator[Message]:
return cast(AsyncIterator[Message], stream)

input_ready = asyncio.Event()
batches = [AppendInput(records=[Record(body=b)]) for b in (b"a", b"b")]
attempts = 0
sent: list[bytes] = []

class _Client:
@asynccontextmanager
async def streaming_request(
self,
*args: Any,
content: AsyncGenerator[bytes, None] | None = None,
**kwargs: Any,
) -> AsyncGenerator[_Response, None]:
nonlocal attempts
assert content is not None
attempts += 1
if attempts == 1:
# Cancel the body sender at each point after the input it is
# waiting for becomes available, then fail the attempt.
send_task = asyncio.ensure_future(content.__anext__())
await asyncio.sleep(0)
input_ready.set()
for _ in range(ticks):
await asyncio.sleep(0)
send_task.cancel()
with suppress(asyncio.CancelledError):
await send_task
await content.aclose()
raise S2ServerError(
code="rate_limited", message="rate_limited", status_code=429
)
sent.extend([chunk async for chunk in content])
yield _Response((_ack(0), _ack(1)))

async def inputs() -> AsyncIterator[AppendInput]:
await input_ready.wait()
for batch in batches:
yield batch

with (
patch.object(append_session, "read_messages", new=decoded_messages),
patch.object(append_session, "compute_backoff", new=lambda *a, **k: 0.0),
):
async with asyncio.timeout(5):
acks = [
ack
async for ack in append_session.run_append_session(
cast(HttpClient, _Client()),
"stream",
inputs(),
Retry(max_attempts=2),
Compression.NONE,
ack_timeout=1.0,
)
]

assert sent == [
append_session._encode_input(batch, Compression.NONE) for batch in batches
]
assert [ack.end.seq_num for ack in acks] == [1, 2]
Loading