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`))
wkt/land_feed_endpoint_reuse
Gud Boi 2026-12-02 16:49:10 -05:00
parent a4d83e2a36
commit a5501a787d
1 changed files with 65 additions and 41 deletions

View File

@ -2,62 +2,72 @@
IB cached quote-channel ownership regressions. IB cached quote-channel ownership regressions.
''' '''
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager as acm from contextlib import asynccontextmanager as acm
import tractor import pytest
from tractor import trionics
import trio import trio
from piker.brokers.ib import feed from piker.brokers.ib import feed
def test_quote_stream_caches_channel_and_owns_child( def test_quote_stream_caches_channel_and_owns_child(
monkeypatch, monkeypatch: pytest.MonkeyPatch,
) -> None: ) -> 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 - On a miss in ``feed._quote_streams``, piker cached the new
`LinkedTaskChannel` in `_quote_streams`, yielded that root directly, ``tractor.to_asyncio.LinkedTaskChannel`` by symbol and yielded
and wrapped the same source in a new broadcaster for each later it directly. On each hit, ``trionics.broadcast_receiver()``
caller. The first caller therefore owned source lifetime while created a separate ``BroadcastReceiver`` with its own buffer.
competing roots split quote receives between concurrent users. A quote read by one caller was then unavailable to the others.
- On the first ``chan.subscribe()``, Tractor keeps the initial
Stub `maybe_open_context()` with one retained channel and enter a ``BroadcastReceiver`` in ``LinkedTaskChannel._broadcaster``.
miss owner plus concurrent hit. Prove both receive the same quote This is the channel's root broadcast receiver. Each caller,
through distinct children of one broadcaster, the hit closes including the first, gets a child with its own cursor into
independently, and the owner keeps receiving until its own exit. the shared buffer. Both children can read the same quote.
Also verify both calls request the same symbol cache key. - 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: class FakeLinkedTaskChannel:
''' '''
Retain one real broadcaster and expose child subscriptions. Subscribe both quote contexts to the same broadcast receiver.
''' '''
def __init__(self) -> None: 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._tx, rx = trio.open_memory_channel(8)
self._broadcaster: ( self._broadcaster: trionics.BroadcastReceiver = (
tractor.trionics.BroadcastReceiver trionics.broadcast_receiver(rx, 8)
) = tractor.trionics.broadcast_receiver(
rx,
8,
) )
@acm @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: async with self._broadcaster.subscribe() as child:
yield 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) await self._tx.send(msg)
@ -65,17 +75,22 @@ def test_quote_stream_caches_channel_and_owns_child(
chan: FakeLinkedTaskChannel = FakeLinkedTaskChannel() chan: FakeLinkedTaskChannel = FakeLinkedTaskChannel()
context_entries: int = 0 context_entries: int = 0
keys: list[str] = [] keys: list[str] = []
acm_funcs: list = [] acm_funcs: list[Callable[..., object]] = []
@acm @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 nonlocal context_entries
keys.append(kwargs['key']) keys.append(key)
acm_funcs.append(kwargs['acm_func']) acm_funcs.append(acm_func)
cache_hit: bool = context_entries > 0 cache_hit: bool = context_entries > 0
context_entries += 1 context_entries += 1
yield cache_hit, chan yield cache_hit, chan
@ -87,30 +102,39 @@ def test_quote_stream_caches_channel_and_owns_child(
) )
async def main() -> None: async def main() -> None:
owner: tractor.trionics.BroadcastReceiver '''
async with feed.open_aio_quote_stream( Nest two quote contexts so the second child exits first.
'NVDA',
) as owner: '''
hit: tractor.trionics.BroadcastReceiver owner: trionics.BroadcastReceiver
async with feed.open_aio_quote_stream( async with feed.open_aio_quote_stream('NVDA') as owner:
'NVDA', hit: trionics.BroadcastReceiver
) as hit: async with feed.open_aio_quote_stream('NVDA') as hit:
# Count `chan._broadcaster`, `owner` and `hit`.
assert hit is not owner assert hit is not owner
assert len(chan._broadcaster._state.subs) == 3 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}) await chan.push({'value': 1})
assert await owner.receive() == {'value': 1} assert await owner.receive() == {'value': 1}
assert await hit.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 hit._closed
assert not owner._closed assert not owner._closed
assert len(chan._broadcaster._state.subs) == 2 assert len(chan._broadcaster._state.subs) == 2
await chan.push({'value': 2}) await chan.push({'value': 2})
assert await owner.receive() == {'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 owner._closed
assert len(chan._broadcaster._state.subs) == 1 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 keys == ['NVDA', 'NVDA']
assert acm_funcs == [ assert acm_funcs == [
feed._open_aio_quote_channel, feed._open_aio_quote_channel,