From a5501a787d341134201e04f2a3b4d2881b51a171 Mon Sep 17 00:00:00 2001 From: goodboy Date: Wed, 2 Dec 2026 16:49:10 -0500 Subject: [PATCH] Explain the IB broadcast test's cursor ownership Piker 4af885d9 originally described a concurrent cache hit. The test opens two nested contexts in a single Trio task and stubs `maybe_open_context()` to return one retained channel. Deats, - Trace the cache miss to the raw channel and each hit to a separate `BroadcastReceiver` with its own buffer. Identify the root broadcast receiver as `LinkedTaskChannel._broadcaster`. Each `chan.subscribe()` yields a child sharing its buffer. - Explain why the stub checks the requested factory and key. - Explain the subscriber counts after each exit. The stub keeps `chan._broadcaster` while the two callers unsubscribe. The second quote checks that the outer cursor still works. - Type the fixture, channel payloads and context-manager yields. Preserve the original assertions and their order. (this patch was generated in some part by `Codex` using `GPT-6` (`OpenAI`)) --- tests/providers/test_ib_broadcast.py | 106 ++++++++++++++++----------- 1 file changed, 65 insertions(+), 41 deletions(-) diff --git a/tests/providers/test_ib_broadcast.py b/tests/providers/test_ib_broadcast.py index 37250701..afd440a5 100644 --- a/tests/providers/test_ib_broadcast.py +++ b/tests/providers/test_ib_broadcast.py @@ -2,62 +2,72 @@ IB cached quote-channel ownership regressions. ''' +from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager as acm -import tractor +import pytest +from tractor import trionics import trio from piker.brokers.ib import feed def test_quote_stream_caches_channel_and_owns_child( - monkeypatch, + monkeypatch: pytest.MonkeyPatch, ) -> None: ''' - IB quote callers must share one cached channel through child cursors. + Give each ``feed.open_aio_quote_stream()`` caller its own cursor. - `open_aio_quote_stream()` previously stored the first caller's raw - `LinkedTaskChannel` in `_quote_streams`, yielded that root directly, - and wrapped the same source in a new broadcaster for each later - caller. The first caller therefore owned source lifetime while - competing roots split quote receives between concurrent users. - - Stub `maybe_open_context()` with one retained channel and enter a - miss owner plus concurrent hit. Prove both receive the same quote - through distinct children of one broadcaster, the hit closes - independently, and the owner keeps receiving until its own exit. - Also verify both calls request the same symbol cache key. + - 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: ''' - Retain one real broadcaster and expose child subscriptions. + Subscribe both quote contexts to the same broadcast receiver. ''' def __init__(self) -> None: - self._tx: trio.MemorySendChannel - rx: trio.MemoryReceiveChannel + ''' + 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: ( - tractor.trionics.BroadcastReceiver - ) = tractor.trionics.broadcast_receiver( - rx, - 8, + self._broadcaster: trionics.BroadcastReceiver = ( + trionics.broadcast_receiver(rx, 8) ) @acm - async def subscribe(self): + async def subscribe( + self, + ) -> AsyncIterator[trionics.BroadcastReceiver]: ''' - Yield one caller-owned child from the retained root. + Yield one child for the lifetime of the caller's context. ''' - child: tractor.trionics.BroadcastReceiver + child: trionics.BroadcastReceiver async with self._broadcaster.subscribe() as child: yield child - async def push(self, msg: dict) -> None: + async def push(self, msg: dict[str, int]) -> None: ''' - Send one ticker through the retained source channel. + Send one marked quote into the shared source channel. ''' await self._tx.send(msg) @@ -65,17 +75,22 @@ def test_quote_stream_caches_channel_and_owns_child( chan: FakeLinkedTaskChannel = FakeLinkedTaskChannel() context_entries: int = 0 keys: list[str] = [] - acm_funcs: list = [] + acm_funcs: list[Callable[..., object]] = [] @acm - async def maybe_open_context(**kwargs): + async def maybe_open_context( + *, + acm_func: Callable[..., object], + key: str, + **_: object, + ) -> AsyncIterator[tuple[bool, FakeLinkedTaskChannel]]: ''' - Return one retained channel as a miss followed by a hit. + Record each request and yield a miss followed by a cache hit. ''' nonlocal context_entries - keys.append(kwargs['key']) - acm_funcs.append(kwargs['acm_func']) + keys.append(key) + acm_funcs.append(acm_func) cache_hit: bool = context_entries > 0 context_entries += 1 yield cache_hit, chan @@ -87,30 +102,39 @@ def test_quote_stream_caches_channel_and_owns_child( ) async def main() -> None: - owner: tractor.trionics.BroadcastReceiver - async with feed.open_aio_quote_stream( - 'NVDA', - ) as owner: - hit: tractor.trionics.BroadcastReceiver - async with feed.open_aio_quote_stream( - 'NVDA', - ) as hit: + ''' + 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,