From 24943e3ee2306ae3be853458fcf54eb8407c9e21 Mon Sep 17 00:00:00 2001 From: goodboy Date: Thu, 5 Nov 2026 14:56:14 -0500 Subject: [PATCH] Limit IB trade filtering to its startup backlog The timestamp guard matched live trades against `samplerd`'s 1s row labels and waited for the next slot before quote fanout. Rounded timestamps misclassified valid ticks, and steady-state receipt-time matching was not the existing current-tail sampling contract. Replace it with a temporary IB startup policy in `piker.brokers.ib._util.StartupTradeFilter`. Capture local receipt time when consumption starts; exclude older stamped packets until the first post-start trade for each symbol. Then stop interpreting timestamps and apply trades to the current SHM tails before notify. Unstamped ticks remain admissible without ending the startup check. Move epoch-unit conversion, catch-up state and diagnostics into the backend utilities. The generic sampler only conditionally invokes the helper for IB. Other providers retain receipt-time sampling. Replace slot-matching tests with coverage for startup exclusion, equal/half-second boundaries, delayed stamps after catch-up and invalid/missing stamps. Hold rows ahead of or behind tick time; require no sampler wait and check both SHM writes at notification for admitted trades. This excludes an observed startup prefix; it does not reconcile or exactly deduplicate overlapping provider history. Keep that fuller startup handoff separate, without changing `samplerd`'s clock or introducing a queued writer which can notify before SHM updates. Regressed-by: 31c0a366 (steady-state sampler timestamp guard) Found-via: live MNQ/QQQ delay warnings and stalled quote delivery (this patch was generated in some part by `opencode` using `gpt-6.1-sol` (`openai`)) --- piker/brokers/ib/_util.py | 110 +++++++++++ piker/data/_sampling.py | 98 ++-------- tests/test_sampling_tick_times.py | 307 +++++++++++------------------- 3 files changed, 238 insertions(+), 277 deletions(-) diff --git a/piker/brokers/ib/_util.py b/piker/brokers/ib/_util.py index 5fb04ad8..931669dc 100644 --- a/piker/brokers/ib/_util.py +++ b/piker/brokers/ib/_util.py @@ -21,12 +21,15 @@ runnable script-programs. ''' from __future__ import annotations import asyncio +from collections import Counter from datetime import ( # noqa datetime, date, tzinfo as TzInfo, ) from functools import partial +from math import isfinite +import time from typing import ( Literal, TYPE_CHECKING, @@ -43,6 +46,113 @@ if TYPE_CHECKING: log = get_logger(name=__name__) + +def trade_time_s(tick: dict) -> float|None: + ''' + Normalize an IB startup tick's packet-receipt stamp to seconds. + + ``ib_async.TickData.time`` contains local packet-receipt + nanoseconds set by ``NonShittyWrapper.tcpDataArrived()``. This + conversion accepts common epoch units, but does not make other + providers' timestamps equivalent to that receipt-time contract. + Missing or invalid stamps return ``None``. + + ''' + raw: object = tick.get('time') + if ( + isinstance(raw, bool) + or + not isinstance(raw, (int, float)) + ): + return None + + seconds: float = float(raw) + if ( + not isfinite(seconds) + or + seconds <= 0 + ): + return None + + if seconds >= 1e17: + seconds /= 1e9 + elif seconds >= 1e14: + seconds /= 1e6 + elif seconds >= 1e11: + seconds /= 1e3 + return seconds + + +class StartupTradeFilter: + ''' + Temporarily exclude IB trades queued before live consumption. + + Construct at the start of the consuming task. Until the first + post-start stamped trade for each symbol, exclude packets whose + local receipt time predates that boundary. Once caught up, stop + interpreting timestamps and use ordinary current-tail sampling. + Unstamped trades remain admissible without ending this check. + + This is a workaround, not startup-history reconciliation: it + does not prove which trades a provider bar already contains. + TODO: reconcile incomplete frames/late trades through + ``ib_async.IB.barUpdateEvent`` with ``keepUpToDate=True`` or a + back-bar path. Emit ``FeedDelayed`` for ongoing sampling delays + separately; timestamp mismatch alone is not evidence of one. + + ''' + def __init__(self) -> None: + ''' + Capture the local receipt boundary and per-symbol progress. + + ''' + self.consume_start_s: float = time.time_ns() / 1_000_000_000 + self.live_symbols: set[str] = set() + self.skipped_ticks: Counter[str] = Counter() + + def skip_trade( + self, + symbol: str, + tick: dict, + ) -> bool: + ''' + Return whether this startup trade must bypass SHM writes. + + ``StartupTradeFilter.live_symbols`` disables filtering after + catch-up; ``StartupTradeFilter.skipped_ticks`` records the + excluded prefix for diagnostics. Neither consults bar labels + or waits for the sampler clock. + + ''' + if symbol in self.live_symbols: + return False + + tick_s: float|None = trade_time_s(tick) + if tick_s is None: + return False + + if tick_s < self.consume_start_s: + self.skipped_ticks[symbol] += 1 + if self.skipped_ticks[symbol] == 1: + log.info( + 'Skipping IB startup ticks\n' + f'{symbol!r}\n' + f'packet={tick_s}\n' + f'consume_start={self.consume_start_s}' + ) + return True + + self.live_symbols.add(symbol) + skipped: int = self.skipped_ticks[symbol] + if skipped: + log.info( + 'IB startup backlog drained\n' + f'{symbol!r}\n' + f'skipped={skipped}' + ) + return False + + _reset_tech: Literal[ 'vnc', 'i3ipc_xdotool', diff --git a/piker/data/_sampling.py b/piker/data/_sampling.py index d1bc2da0..89896036 100644 --- a/piker/data/_sampling.py +++ b/piker/data/_sampling.py @@ -25,7 +25,6 @@ from collections import ( defaultdict, ) from contextlib import asynccontextmanager as acm -from math import isfinite import time from typing import ( Any, @@ -68,42 +67,6 @@ if TYPE_CHECKING: # tick-event stream. _default_delay_s: float = 1.0 -# Give the independent samplerd incrementer one step to catch up -# before deciding a tick stamped for the next 1s bar is unusable. -_next_tick_step_wait_s: float = 1.5 - - -def trade_time_s(tick: dict) -> float|None: - ''' - Read a trade's epoch time in seconds, if one was supplied. - - Broker feeds may omit timestamps. IB's `TickData.time` uses - nanoseconds; other feeds may use seconds, milliseconds, or - microseconds. An absent or invalid value retains the existing - receive-time sampling behavior. - - ''' - raw: Any = tick.get('time') - if ( - isinstance(raw, bool) - or - not isinstance(raw, (int, float)) - ): - return None - - seconds: float = float(raw) - if not isfinite(seconds) or seconds <= 0: - return None - - if seconds >= 1e17: - seconds /= 1e9 - elif seconds >= 1e14: - seconds /= 1e6 - elif seconds >= 1e11: - seconds /= 1e3 - - return seconds - class Sampler: ''' @@ -647,7 +610,14 @@ async def sample_and_broadcast( log.info("Started shared mem bar writer") overruns = Counter() - mismatched_ticks: Counter[str] = Counter() + # Temporary backend-owned startup admission. Ordinary sampling + # still writes current SHM tails before notifying subscribers; + # the sampler does not interpret provider timestamps itself. + startup_filter = None + if brokername == 'ib': + from ..brokers.ib._util import StartupTradeFilter + + startup_filter = StartupTradeFilter() # NOTE, only used for debugging live-data-feed issues, though # this should be resolved more correctly in the future using the @@ -696,58 +666,14 @@ async def sample_and_broadcast( # write trade events to shm last OHLC sample if ticktype in ('trade', 'utrade'): - tick_s: float|None = trade_time_s(tick) - bar_s: float = float(rt_shm.array[-1]['time']) if ( - tick_s is not None + startup_filter is not None and - round(tick_s) == round(bar_s) + 1 - ): - # The chart cannot see this trade price until - # `Sampler.increment_ohlc_buffer()` advances. - # TODO: emit a `FeedDelayed` event to feed - # subscribers if this occurs beyond startup. - log.warning( - 'DELAYING LIVE TRADE SHM UPDATE until ' - f'next 1s OHLC slot for ' - f'{broker_symbol}!\n' - f'tick_time_s: {tick_s}\n' - f'current_bar_s: {bar_s}\n' - f'max_wait_s: {_next_tick_step_wait_s}' + startup_filter.skip_trade( + symbol=broker_symbol, + tick=tick, ) - with trio.move_on_after( - _next_tick_step_wait_s - ): - while round(tick_s) > round(bar_s): - await trio.sleep(0.01) - bar_s = float( - rt_shm.array[-1]['time'] - ) - if ( - tick_s is not None - and - round(tick_s) != round(bar_s) ): - # The newest provider frame may already hold - # queued startup trades. Replaying them into - # the sampler's current bar misdates them and - # can double-count provider history. Leave - # past rows to the history/backfill path. - # Sampler.increment_ohlc_buffer() rounds its - # 1s step timestamp, so use the same bucket. - # TODO: `Client.bars()` fetches a one-shot - # latest frame; a late trade may be absent - # from its unfinished last bar. Reconcile IB - # `barUpdateEvent` from `keepUpToDate=True`, - # or add a provider-neutral back-bar - # correction path. - mismatched_ticks[broker_symbol] += 1 - if mismatched_ticks[broker_symbol] == 1: - log.warning( - 'Skipping trade outside current 1s ' - f'bar for {broker_symbol}: ' - f'tick={tick_s}, bar={bar_s}' - ) continue last = tick['price'] diff --git a/tests/test_sampling_tick_times.py b/tests/test_sampling_tick_times.py index 9f9cda6f..8cf4f386 100644 --- a/tests/test_sampling_tick_times.py +++ b/tests/test_sampling_tick_times.py @@ -16,7 +16,7 @@ # . ''' -Live sampler checks for timestamped startup trade backlogs. +Startup backlog admission without changing current-slot sampling. ''' from types import SimpleNamespace @@ -25,218 +25,143 @@ import numpy as np import pytest import trio -from piker.data._sampling import ( - sample_and_broadcast, - trade_time_s, -) from piker.data import _sampling +from piker.brokers.ib import _util as ib_util -@pytest.mark.parametrize( - ('raw', 'expected'), - [ - (1_790_360_484, 1_790_360_484.), # seconds - (1_790_360_484_000, 1_790_360_484.), # milliseconds - (1_790_360_484_000_000, 1_790_360_484.), - (1_790_360_484_000_000_000, 1_790_360_484.), - (None, None), # provider without a tick timestamp - ], -) -def test_trade_time_s_accepts_common_epoch_units( - raw: int|None, - expected: float|None, -) -> None: - assert trade_time_s({'time': raw}) == expected - - -@pytest.mark.parametrize( - ('bar_time', 'current_time_ns'), - [ - ( - 1_790_360_484., - 1_790_360_484_250_000_000, - ), - ( - 1_790_360_485., - 1_790_360_484_750_000_000, - ), - ], -) -def test_queued_trade_is_not_written_to_a_later_bar( - bar_time: float, - current_time_ns: int, -) -> None: +@pytest.mark.parametrize('scale', [ + 1, 1000, 1_000_000, 1_000_000_000, +]) +def test_trade_time_units(scale: int) -> None: ''' - A 13:21:19 IB trade queued until the 13:21:24 1s bar must not - add its price or volume to either live SHM tail. A current tick - in the same input channel still updates both bars. + Normalize epoch units without interpreting provider semantics. ''' - dtype = [ - ('time', 'f8'), - ('open', 'f8'), - ('high', 'f8'), - ('low', 'f8'), - ('close', 'f8'), - ('volume', 'f8'), - ] - rt = np.array( - [(bar_time, 30_918., 30_918., - 30_918., 30_918., 19.)], - dtype=dtype, - ) - hist = np.array( - [(1_790_360_460., 30_918., 30_918., - 30_918., 30_918., 248.)], - dtype=dtype, - ) - rt_shm = SimpleNamespace(array=rt) - hist_shm = SimpleNamespace(array=hist) - bus = SimpleNamespace(get_subs=lambda key: set()) - - async def replay() -> None: - send, receive = trio.open_memory_channel(4) - async with send: - await send.send({ - 'mnq.cme.20261218': { - 'ticks': [{ - 'type': 'trade', - 'time': 1_790_360_479_217_767_927, - 'price': 30_923., - 'size': 12_013., - }], - 'volume': 2_222_721., - }, - }) - await send.send({ - 'mnq.cme.20261218': { - 'ticks': [{ - 'type': 'trade', - 'time': current_time_ns, - 'price': 30_918.25, - 'size': 2., - }], - 'volume': 2_222_723., - }, - }) - await send.send({ - 'mnq.cme.20261218': { - 'ticks': [{ - 'type': 'trade', - 'time': int( - (bar_time + 2.) * 1_000_000_000 - ), - 'price': 30_925., - 'size': 100., - }], - 'volume': 2_222_823., - }, - }) - await send.send({ - 'mnq.cme.20261218': { - 'ticks': [{ - 'type': 'trade', - 'price': 30_918.5, - 'size': 1., - }], - 'volume': 2_222_824., - }, - }) - async with receive: - await sample_and_broadcast( - bus, - rt_shm, - hist_shm, - receive, - 'ib', - ) - - trio.run(replay) - assert float(rt['high'][-1]) == 30_918.5 - assert float(rt['volume'][-1]) == 22. - assert float(hist['high'][-1]) == 30_918.5 - assert float(hist['volume'][-1]) == 251. + assert ib_util.trade_time_s({ + 'time': 1_790_360_484 * scale, + }) == 1_790_360_484. -def test_next_second_trade_waits_for_sampler_step( +@pytest.mark.parametrize('raw', [None, True, float('nan'), -1]) +def test_missing_trade_time(raw: object) -> None: + ''' + Invalid stamps leave the existing receipt-time path available. + + ''' + assert ib_util.trade_time_s({'time': raw}) is None + + +@pytest.mark.parametrize('broker', ['ib', 'other']) +@pytest.mark.parametrize('bar_offset', [-1., 0., 1.]) +def test_startup_admission_preserves_write_before_notify( monkeypatch: pytest.MonkeyPatch, + broker: str, + bar_offset: float, ) -> None: ''' - A trade for the next 1s slot must not update the older SHM bar. + Exclude IB startup backlog without imposing event-time placement. - The independent `Sampler.increment_ohlc_buffer()` can lag the - tick stream. Waiting avoids a misdated price but delays chart - updates, so a warning must fire before the slot advances. Hold - the old slot until that warning, then advance it and verify the - trade reaches both SHM tails without being dropped. + ``31c0a366`` waited for the sampler's row label to match tick + timestamps during steady state, blocking quote delivery. + Its rounded comparisons also misclassified half-second ticks. + + Feed old queued packets, a packet exactly at consumption startup, + then later data including the observed .5589051 offset and an old + stamp after startup has ended. Hold the row labels fixed, ahead + of or behind packet time. Require zero waits and both SHM writes + completed before each subscriber notification. Non-IB timestamps + must not be interpreted as local packet receipt time at all. + + This is explicitly a startup exclusion policy, not proof of exact + deduplication against provider history or event-time OHLC parity. ''' - dtype = [ - ('time', 'f8'), - ('open', 'f8'), - ('high', 'f8'), - ('low', 'f8'), - ('close', 'f8'), - ('volume', 'f8'), - ] - rt = np.array( - [(1_790_360_484., 30_918., 30_918., - 30_918., 30_918., 0.)], - dtype=dtype, - ) + start_s: float = 1_793_717_591. + dtype = [(name, 'f8') for name in ( + 'time', 'open', 'high', 'low', 'close', 'volume', + )] + rt = np.array([ + (start_s + bar_offset, 100., 100., 100., 100., 0.), + ], dtype=dtype) hist = rt.copy() - rt_shm = SimpleNamespace(array=rt) - hist_shm = SimpleNamespace(array=hist) - bus = SimpleNamespace(get_subs=lambda key: set()) - warnings: list[str] = [] - wait_started = trio.Event() + stamps: list[float|None] = [ + start_s - 5., + start_s - .01, + start_s, + start_s + .5589051, + start_s + 2., + start_s - 5., + None, + ] + sizes: list[float] = [12013., 99., 2., 3., 4., 5., 1.] + expected: list[float] = [] + accumulated: float = 0. + for index, size in enumerate(sizes): + if broker != 'ib' or index >= 2: + accumulated += size + expected.append(accumulated) + delivered: list[dict] = [] - def record_warning(message: str) -> None: - warnings.append(message) - wait_started.set() + async def notify(message: dict) -> None: + ''' + Read both SHM buffers at the notification boundary. - monkeypatch.setattr( - _sampling.log, - 'warning', - record_warning, + ''' + index: int = len(delivered) + assert rt['volume'][-1] == expected[index] + assert hist['volume'][-1] == expected[index] + if broker != 'ib' or index >= 2: + assert rt['close'][-1] == hist['close'][-1] + assert rt['close'][-1] == (101. + index) + delivered.append(message) + + async def forbidden_wait(delay: float) -> None: + ''' + Fail if trade admission waits for the sampler clock. + + ''' + pytest.fail(f'Timestamp admission waited {delay}s') + + clock = SimpleNamespace( + time_ns=lambda: int(start_s * 1_000_000_000), ) + monkeypatch.setattr( + ib_util, 'time', + clock, + ) + monkeypatch.setattr(_sampling.trio, 'sleep', forbidden_wait) + sub = SimpleNamespace( + throttle_rate=0., + ipc=SimpleNamespace(send=notify), + ) + bus = SimpleNamespace(get_subs=lambda _: [sub]) async def replay() -> None: - send, receive = trio.open_memory_channel(1) - async with send: - await send.send({ - 'mnq.cme.20261218': { + ''' + Drain a finite input through the production sampler/fanout. + + ''' + tx, rx = trio.open_memory_channel(len(stamps)) + async with tx, rx: + for index, stamp in enumerate(stamps): + tx.send_nowait({'asset.venue': { 'ticks': [{ 'type': 'trade', - 'time': 1_790_360_485_250_000_000, - 'price': 30_919., - 'size': 2., + 'time': stamp, + 'price': 101. + index, + 'size': sizes[index], }], - 'volume': 2_222_723., - }, - }) - - async def step() -> None: - with trio.fail_after(2): - await wait_started.wait() - rt['time'][-1] = 1_790_360_485. - - async with ( - receive, - trio.open_nursery() as nursery, - ): - nursery.start_soon(step) - await sample_and_broadcast( - bus, - rt_shm, - hist_shm, - receive, - 'ib', - ) + }}) + await tx.aclose() + with trio.fail_after(1): + await _sampling.sample_and_broadcast( + bus=bus, + rt_shm=SimpleNamespace(array=rt), + hist_shm=SimpleNamespace(array=hist), + quote_stream=rx, + brokername=broker, + ) trio.run(replay) - assert float(rt['high'][-1]) == 30_919. - assert float(rt['volume'][-1]) == 2. - assert float(hist['volume'][-1]) == 2. - assert len(warnings) == 1 - assert 'DELAYING LIVE TRADE SHM UPDATE' in warnings[0] + assert len(delivered) == len(stamps) + assert rt['time'][-1] == start_s + bar_offset