From cd1235128d00f3b2b61cdae05d7bc3dc4670734e Mon Sep 17 00:00:00 2001 From: goodboy Date: Sat, 31 Oct 2026 19:49:25 -0400 Subject: [PATCH] Fix IB metadata lookup without a supplied proxy `get_mkt_info()` assigned the `open_data_client` factory rather than calling it when no `MethodProxy` was supplied. Entering that function with `async with` raised `TypeError`; callers supplying a proxy took the working `nullcontext()` branch instead. Instantiate a fresh client context on uncached owned lookups and retain borrowed-proxy ownership. Document native-name qualification and annotate the resolver's context/metadata bindings. Add standalone coverage through the actual decorated resolver, replacing only client I/O. Check fresh context entry/exit, borrowed proxy calls, canonical endpoint identity, contract registration and same-spelling cache hits without further details queries. Unique request names avoid process-cache collisions between tests. Keep this backend-path repair independent of feed allocation, SHM lifetime and alias-registry changes. (this patch was generated in some part by `opencode` using `openai/gpt-6-astra` (`openai`)) --- piker/brokers/ib/symbols.py | 39 ++++++++-- tests/test_ib_symbols.py | 143 ++++++++++++++++++++++++++++++++++++ 2 files changed, 175 insertions(+), 7 deletions(-) create mode 100644 tests/test_ib_symbols.py diff --git a/piker/brokers/ib/symbols.py b/piker/brokers/ib/symbols.py index 2d066a76..77d4f59e 100644 --- a/piker/brokers/ib/symbols.py +++ b/piker/brokers/ib/symbols.py @@ -26,6 +26,7 @@ from decimal import Decimal from functools import partial import time from typing import ( + AsyncContextManager, Awaitable, TYPE_CHECKING, ) @@ -523,22 +524,46 @@ async def get_mkt_info( proxy: MethodProxy|None = None, ) -> tuple[MktPair, ibis.ContractDetails]: + ''' + Resolve an IB request name into market and contract metadata. + + - Accept native names such as ``mnq.cme`` and ``qqq.nasdaq``. + The data layer qualifies its registry lookup, but still sends + the native request name into provider APIs. Normalize the + broker suffix here for ``unpack_fqme()`` and direct callers. + - Borrow a supplied ``MethodProxy`` without owning its lifetime. + - Otherwise open a fresh ``open_data_client()`` context for this + uncached resolution and release it after querying the details. + + ''' if '.ib' not in fqme: fqme += '.ib' - broker, pair, venue, expiry = unpack_fqme(fqme) + broker: str + pair: str + venue: str + expiry: str + ( + broker, + pair, + venue, + expiry, + ) = unpack_fqme(fqme) - proxy: MethodProxy + client_ctx: AsyncContextManager[MethodProxy] if proxy is not None: client_ctx = nullcontext(proxy) else: from .feed import ( open_data_client, ) - client_ctx = open_data_client + client_ctx = open_data_client() + proxy: MethodProxy async with client_ctx as proxy: try: + con: ibis.Contract + details: ibis.ContractDetails ( con, # Contract details, # ContractDetails @@ -548,7 +573,7 @@ async def get_mkt_info( raise # TODO: more consistent field translation - atype = _asset_type_map[con.secType] + atype: str = _asset_type_map[con.secType] if atype == 'commodity': venue: str = 'cmdty' @@ -580,16 +605,16 @@ async def get_mkt_info( # XXX: GRRRR they don't support fractional share sizes for # stocks from the API?! # if con.secType == 'STK': - size_tick = Decimal('1') + size_tick: Decimal = Decimal('1') else: - size_tick: Decimal = Decimal( + size_tick = Decimal( str(details.minSize).rstrip('0') ) # ?TODO, there is also the Contract.sizeIncrement, bt wtf is it? # NOTE: this is duplicate from the .broker.norm_trade_records() # routine, we should factor all this parsing somewhere.. - expiry_str = str(con.lastTradeDateOrContractMonth) + expiry_str: str = str(con.lastTradeDateOrContractMonth) # if expiry: # expiry_str: str = str(pendulum.parse( # str(expiry).strip(' ') diff --git a/tests/test_ib_symbols.py b/tests/test_ib_symbols.py new file mode 100644 index 00000000..d5ba14f0 --- /dev/null +++ b/tests/test_ib_symbols.py @@ -0,0 +1,143 @@ +''' +IB metadata resolution without feed allocation or a live Gateway. + +''' +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from types import SimpleNamespace +from typing import cast +from uuid import uuid4 + +import ib_async as ibis +import pytest +import trio + +from piker.accounting import MktPair +from piker.brokers.ib import feed, symbols +from piker.brokers.ib.api import MethodProxy + + +@pytest.mark.parametrize('borrow_proxy', [False, True]) +def test_metadata_client_ownership_and_cache( + monkeypatch: pytest.MonkeyPatch, + borrow_proxy: bool, +) -> None: + ''' + Resolve uncached IB metadata with owned or borrowed clients. + + ``symbols.get_mkt_info()`` assigned the ``open_data_client`` + factory instead of calling it when no proxy was supplied. That + untested branch raised ``TypeError`` at ``async with``; existing + supplied-proxy calls used ``nullcontext()`` and worked. + + - Exercise the actual decorated resolver with real + ``ib_async.Future`` and ``ib_async.ContractDetails`` records. + - Replace only client I/O, requiring a fresh entered/exited + context for each uncached owned lookup and none for borrowing. + - Verify native-name qualification and canonical ``MktPair`` + identity, including contract-cache registration. + - Repeat a warmed request spelling with/without a proxy; require + result identity and no extra query or client-context entry. + + Unique request names avoid interference with the process-local + cache or other tests. No feed allocator, SHM, actor or Gateway is + involved, so this test can ship independently of feed changes. + + ''' + symbol: str = f'resolvertest{uuid4().hex}' + native: str = f'{symbol}.cme' + canonical: str = f'{native}.20261218.ib' + contract = ibis.Future( + conId=815824267, + symbol=symbol.upper(), + exchange='CME', + currency='USD', + lastTradeDateOrContractMonth='20261218', + multiplier='2', + ) + details = ibis.ContractDetails( + contract=contract, + minTick=0.25, + minSize=1, + ) + queries: list[str] = [] + entries: list[object] = [] + exits: list[object] = [] + client = SimpleNamespace(_contracts={}, _cons2mkts={}) + + async def get_sym_details( + fqme: str, + ) -> tuple[ibis.Contract, ibis.ContractDetails]: + ''' + Record qualified requests at the client I/O boundary. + + ''' + queries.append(fqme) + return contract, details + + proxy = cast(MethodProxy, SimpleNamespace( + get_sym_details=get_sym_details, + _aio_ns=client, + )) + + @asynccontextmanager + async def open_client() -> AsyncIterator[MethodProxy]: + ''' + Give each manager invocation a distinct lifetime marker. + + ''' + marker = object() + entries.append(marker) + try: + yield proxy + finally: + exits.append(marker) + + monkeypatch.setattr(feed, 'open_data_client', open_client) + + async def main() -> None: + ''' + Query two cold spellings, then repeat the first cached one. + + ''' + supplied: MethodProxy|None = None + expected_contexts: int = 2 + if borrow_proxy: + supplied = proxy + expected_contexts = 0 + + first_mkt: MktPair + first_details: ibis.ContractDetails + first_mkt, first_details = await symbols.get_mkt_info( + native, + proxy=supplied, + ) + dated_mkt: MktPair + dated_details: ibis.ContractDetails + dated_mkt, dated_details = await symbols.get_mkt_info( + canonical, + proxy=supplied, + ) + assert first_mkt.fqme == dated_mkt.fqme == canonical + assert first_mkt.bs_mktid == '815824267' + assert first_details is dated_details is details + assert queries == [f'{native}.ib', canonical] + assert len(entries) == expected_contexts + assert exits == entries + assert len({id(marker) for marker in entries}) == len(entries) + assert client._contracts[canonical] is contract + assert client._cons2mkts[contract] is dated_mkt + + repeated: tuple[MktPair, ibis.ContractDetails] + for supplied in (None, proxy): + repeated = await symbols.get_mkt_info( + native, + proxy=supplied, + ) + assert repeated[0] is first_mkt + assert repeated[1] is details + assert queries == [f'{native}.ib', canonical] + assert len(entries) == expected_contexts + assert exits == entries + + trio.run(main)