''' Exercise shared IB quote restart with either consumer exiting first. ''' import asyncio from collections.abc import AsyncIterator, Callable import contextlib import os from pathlib import Path import types import ib_async import pytest import tractor import trio from piker.brokers.ib import feed STEP_TIMEOUT_S: int = 4 ACTOR_TIMEOUT_S: int = 20 type ExceptionHandler = Callable[ [asyncio.AbstractEventLoop, dict[str, object]], None, ] async def actor_pid() -> int: ''' Return the process ID of the Tractor actor running this call. ''' return os.getpid() async def share_then_restart(first_exit: int) -> int: ''' Exercise a single actor's shared quote channel and reopen it. - Enter the first consumer before the second. Publish a marked tick after both subscribe and require each to receive it. - Cancel the selected consumer and wait through its context exit before emitting a different tick to the survivor. - Cancel the last holder to make ``maybe_open_context()`` close ``feed._open_aio_quote_channel()`` while the asyncio quote producer is still running. Wait for that exit before reopening. - Require the producer to finish, its ticker callback to be removed, and the reopened channel to deliver a fresh quote. ''' contract: ib_async.Contract = ib_async.Contract(symbol='QQQ') tickers: list[ib_async.Ticker] = [] producers: list[asyncio.Task[object]] = [] cancels: list[ib_async.Contract] = [] callback_errors: list[dict[str, object]] = [] class ReplayIB: ''' Expose eventkit subscriptions without a Gateway connection. ''' def reqMktData( self, con: ib_async.Contract, options: str, ) -> ib_async.Ticker: ''' Record the task that registered this subscription. ''' producer: asyncio.Task[object]|None = ( asyncio.current_task() ) assert producer is not None producers.append(producer) ticker: ib_async.Ticker = ib_async.Ticker(contract=con) tickers.append(ticker) return ticker def cancelMktData(self, con: ib_async.Contract) -> None: ''' Record cancellation of each upstream subscription. ''' cancels.append(con) client: types.SimpleNamespace = types.SimpleNamespace( ib=ReplayIB(), ) @contextlib.asynccontextmanager async def clients( disconnect_on_exit: bool, ) -> AsyncIterator[dict[str, types.SimpleNamespace]]: ''' Inject the offline source into the real asyncio producer. ''' yield {'ib.replay': client} ready: list[trio.Event] = [trio.Event(), trio.Event()] done: list[trio.Event] = [trio.Event(), trio.Event()] scopes: list[trio.CancelScope] = [] send: trio.MemorySendChannel[tuple[int, float]] recv: trio.MemoryReceiveChannel[tuple[int, float]] send, recv = trio.open_memory_channel(4) async def hold(slot: int) -> None: ''' Keep receiving until the driver cancels this holder. ''' scope: trio.CancelScope with trio.CancelScope() as scope: scopes.append(scope) quotes: tractor.trionics.BroadcastReceiver async with feed.open_aio_quote_stream( 'qqq.nasdaq', contract=contract, ) as quotes: ready[slot].set() ticker: ib_async.Ticker async for ticker in quotes: await send.send((slot, ticker.last)) done[slot].set() def publish(price: float) -> None: ''' Deliver one distinct tick to the installed eventkit handler. ''' ticker: ib_async.Ticker = tickers[-1] ticker.last = price ticker.updateEvent.emit(ticker) loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() previous: ExceptionHandler|None = loop.get_exception_handler() loop.set_exception_handler( lambda _, context: callback_errors.append(context), ) survivor: int = 1 - first_exit try: patch: pytest.MonkeyPatch with pytest.MonkeyPatch.context() as patch: patch.setattr(feed, 'load_aio_clients', clients) patch.setattr( feed, 'get_preferred_data_client', lambda _: ('ib.replay', client), ) with trio.fail_after(STEP_TIMEOUT_S): tn: trio.Nursery async with trio.open_nursery() as tn: # Slot 0 has already entered the stream when # slot 1 opens it for the same contract. tn.start_soon(hold, 0) await ready[0].wait() tn.start_soon(hold, 1) await ready[1].wait() # One reqMktData() call, two deliveries of # one tick. Either receiver can report first. assert len(tickers) == 1 publish(101.0) first: tuple[int, float] = await recv.receive() second: tuple[int, float] = await recv.receive() assert {first, second} == {(0, 101), (1, 101)} # Wait for the selected context to exit before # checking its peer can receive a fresh tick. scopes[first_exit].cancel() await done[first_exit].wait() assert cancels == [] publish(102.0) assert await recv.receive() == (survivor, 102) scopes[survivor].cancel() await done[survivor].wait() # Only the last exit should cancel upstream, # finish the producer and disconnect its callback. assert cancels == [contract] assert producers[0].done() assert len(tickers[0].updateEvent) == 0 scope: trio.CancelScope with trio.CancelScope() as scope: quotes: tractor.trionics.BroadcastReceiver async with feed.open_aio_quote_stream( 'qqq.nasdaq', contract=contract, ) as quotes: # Reopen against a new ticker. A buffered # value from the old one cannot satisfy 103. assert len(tickers) == 2 publish(103.0) assert (await quotes.receive()).last == 103 scope.cancel() await trio.lowlevel.checkpoint() # The second generation must release its own # subscription and callback as well. assert cancels == [contract, contract] assert producers[1].done() assert len(tickers[1].updateEvent) == 0 # Let signal_trio_when_done() run before checking # whether it leaked the TrioTaskExited acknowledgement # to asyncio's loop exception handler. await tractor.to_asyncio.run_task(asyncio.sleep, delay=0) assert not callback_errors, callback_errors finally: loop.set_exception_handler(previous) return os.getpid() @pytest.mark.parametrize( 'first_exit', [0, 1], ids=[ 'first-consumer-exits-first', 'second-consumer-exits-first', ], ) def test_shared_quote_restart_after_both_consumers_exit( reg_addr: tuple[str, int|str], first_exit: int, monkeypatch: pytest.MonkeyPatch, ) -> None: ''' Reopen the shared IB quote stream after both consumers exit. - The raw quote channel let two tasks compete for one tick. Run ``share_then_restart()`` in a Trio actor using the real asyncio bridge. Require both tasks to receive the same tick. - Request each consumer to close its quote stream by cancelling its Trio scope. The first close leaves the other consumer receiving quotes. The final close makes ``open_channel_from()`` send ``TrioTaskExited`` to the still-running asyncio producer. - Before the bridge fix, the acknowledged signal could escape into Trio or raise from the asyncio completion callback. Reopen for a fresh quote, then check the loop exception handler for unhandled callback errors. - Call ``actor_pid()`` through the same Tractor portal. Compare its process ID with the one from ``share_then_restart()`` to verify the original actor still answers after teardown. ''' # Tractor imports this module by its pytest name in a fresh # interpreter. Expose the parent of the `providers` package. monkeypatch.setenv( 'PYTHONPATH', str(Path(__file__).resolve().parents[1]), prepend=os.pathsep, ) async def main() -> None: ''' Run the selected consumer exit sequence in a Tractor actor. ''' with trio.fail_after(ACTOR_TIMEOUT_S): nursery: tractor.ActorNursery async with ( tractor.open_root_actor(registry_addrs=[reg_addr]), tractor.open_nursery() as nursery, ): portal: tractor.Portal = await nursery.start_actor( 'ib_shared_replay', enable_modules=[__name__], infect_asyncio=True, ) pid: int = await portal.run( share_then_restart, first_exit=first_exit, ) # Ask the same actor for its PID after teardown. assert await portal.run(actor_pid) == pid await portal.cancel_actor() trio.run(main)