''' IB cached quote-channel ownership regressions. ''' from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager as acm import pytest from tractor import trionics import trio from piker.brokers.ib import feed def test_quote_stream_caches_channel_and_owns_child( monkeypatch: pytest.MonkeyPatch, ) -> None: ''' Give each ``feed.open_aio_quote_stream()`` caller its own cursor. - On a miss in ``feed._quote_streams``, piker cached the new ``tractor.to_asyncio.LinkedTaskChannel`` by symbol and yielded it directly. On each hit, ``trionics.broadcast_receiver()`` created a separate ``BroadcastReceiver`` with its own buffer. A quote read by one caller was then unavailable to the others. - On the first ``chan.subscribe()``, Tractor keeps the initial ``BroadcastReceiver`` in ``LinkedTaskChannel._broadcaster``. This is the channel's root broadcast receiver. Each caller, including the first, gets a child with its own cursor into the shared buffer. Both children can read the same quote. - Open the same symbol twice in one task. The stub for ``trionics.maybe_open_context()`` yields one channel on both entries. Check the requested factory and symbol key each time. - Read one marked quote from both children, close the inner context, and read a second quote from the outer child. At final exit only ``chan._broadcaster`` should remain subscribed. ''' class FakeLinkedTaskChannel: ''' Subscribe both quote contexts to the same broadcast receiver. ''' def __init__(self) -> None: ''' Wrap the receive end of the test's quote channel. ''' self._tx: trio.MemorySendChannel[dict[str, int]] rx: trio.MemoryReceiveChannel[dict[str, int]] self._tx, rx = trio.open_memory_channel(8) self._broadcaster: trionics.BroadcastReceiver = ( trionics.broadcast_receiver(rx, 8) ) @acm async def subscribe( self, ) -> AsyncIterator[trionics.BroadcastReceiver]: ''' Yield one child for the lifetime of the caller's context. ''' child: trionics.BroadcastReceiver async with self._broadcaster.subscribe() as child: yield child async def push(self, msg: dict[str, int]) -> None: ''' Send one marked quote into the shared source channel. ''' await self._tx.send(msg) chan: FakeLinkedTaskChannel = FakeLinkedTaskChannel() context_entries: int = 0 keys: list[str] = [] acm_funcs: list[Callable[..., object]] = [] @acm async def maybe_open_context( *, acm_func: Callable[..., object], key: str, **_: object, ) -> AsyncIterator[tuple[bool, FakeLinkedTaskChannel]]: ''' Record each request and yield a miss followed by a cache hit. ''' nonlocal context_entries keys.append(key) acm_funcs.append(acm_func) cache_hit: bool = context_entries > 0 context_entries += 1 yield cache_hit, chan monkeypatch.setattr( feed.tractor.trionics, 'maybe_open_context', maybe_open_context, ) async def main() -> None: ''' Nest two quote contexts so the second child exits first. ''' owner: trionics.BroadcastReceiver async with feed.open_aio_quote_stream('NVDA') as owner: hit: trionics.BroadcastReceiver async with feed.open_aio_quote_stream('NVDA') as hit: # Count `chan._broadcaster`, `owner` and `hit`. assert hit is not owner assert len(chan._broadcaster._state.subs) == 3 # A single send must reach both cursors. Two sends # could hide competing reads from the raw channel. await chan.push({'value': 1}) assert await owner.receive() == {'value': 1} assert await hit.receive() == {'value': 1} # Closing `hit` leaves `chan._broadcaster` and `owner`. # A fresh quote proves the owner's cursor still works. assert hit._closed assert not owner._closed assert len(chan._broadcaster._state.subs) == 2 await chan.push({'value': 2}) assert await owner.receive() == {'value': 2} # Both callers have exited. Only the receiver retained # by the stub in `chan._broadcaster` stays subscribed. assert owner._closed assert len(chan._broadcaster._state.subs) == 1 # The stub always returns the same channel. Check the # arguments that select it in the real context cache. assert keys == ['NVDA', 'NVDA'] assert acm_funcs == [ feed._open_aio_quote_channel, feed._open_aio_quote_channel, ] trio.run(main)