''' Startup contracts complementary to ``test_feed_actor_e2e``. ''' from collections.abc import Awaitable, Callable from dataclasses import dataclass, field from decimal import Decimal from functools import partial from types import ModuleType, SimpleNamespace from msgspec.structs import replace import numpy as np import pytest import trio from trio.testing import wait_all_tasks_blocked from trio_typing import TaskStatus from piker.accounting import Asset, MktPair from piker.data import feed from piker.data.validate import FeedInit @dataclass class Startup: ''' Control readiness and observe task lifetimes, without actor I/O. ``Startup.history_gate`` parks initialization before publication. ``Startup.mismatch`` makes quotes report a different endpoint. ``Startup.finish_sampler`` ends an otherwise persistent sampler. ''' mod: ModuleType history_gate: trio.Event = field(default_factory=trio.Event) mismatch: bool = False finish_sampler: bool = False quote_starts: int = 0 quote_exits: int = 0 history_starts: int = 0 history_exits: int = 0 @pytest.fixture def startup(monkeypatch: pytest.MonkeyPatch) -> Startup: ''' Run feed orchestration with controlled provider/history I/O. Real ``trio`` tasks execute the allocator. A small NumPy buffer supplies initialized data; IPC, subscriptions and actual SHM are exercised separately by ``test_feed_actor_e2e.py``. ''' mod = ModuleType('testfeed') state = Startup(mod=mod) mkt = MktPair( dst=Asset(name='asset', atype='stock', tx_tick=Decimal('1')), src=Asset(name='usd', atype='fiat', tx_tick=Decimal('.01')), price_tick=Decimal('.01'), size_tick=Decimal('1'), bs_mktid='asset', broker='testfeed', venue='venue', _fqme_without_src=True, ) async def resolve(symbol: str) -> tuple[MktPair, None]: ''' Return the fixture's canonical endpoint before quote startup. ''' return mkt, None async def quotes( send_chan: trio.MemorySendChannel, symbols: list[str], feed_is_live: trio.Event, task_status: TaskStatus = trio.TASK_STATUS_IGNORED, ) -> None: ''' Publish metadata and record finalization after cancellation. ''' state.quote_starts += 1 try: reported = mkt if state.mismatch: reported = replace(mkt, venue='different') feed_is_live.set() task_status.started(([FeedInit(mkt_info=reported)], {})) await trio.sleep_forever() finally: state.quote_exits += 1 async def history( task_status: TaskStatus = trio.TASK_STATUS_IGNORED, **kwargs, ) -> None: ''' Hold the history handshake until the test releases its gate. ''' state.history_starts += 1 try: await state.history_gate.wait() shm = SimpleNamespace(array=np.zeros(1), token='unused') kwargs['some_data_ready'].set() task_status.started((0, shm, 0, shm)) await trio.sleep_forever() finally: state.history_exits += 1 async def sample(**kwargs) -> None: ''' Return normally only when the cleanup test requests it. ''' if not state.finish_sampler: await trio.sleep_forever() mod.name = 'testfeed' mod.get_mkt_info = resolve mod.stream_quotes = quotes monkeypatch.setattr(feed, 'get_brokermod', lambda _: mod) monkeypatch.setattr(feed, 'manage_history', history) monkeypatch.setattr(feed, 'sample_and_broadcast', sample) return state def start_feed( bus: feed._FeedsBus, ) -> Callable[..., Awaitable[None]]: ''' Bind allocator inputs without emulating a chart subscription. The subscriber gate is already set: these tests target startup ownership, while the actor suite verifies subscriber handshakes. ''' registered = trio.Event() registered.set() return partial( feed.maybe_allocate_persistent_feed, bus=bus, sub_registered=registered, brokername='testfeed', symstr='asset.venue', loglevel='error', ) @pytest.mark.parametrize('failure', ['missing', 'empty', 'mismatch']) def test_metadata_failure_precedes_history( startup: Startup, monkeypatch: pytest.MonkeyPatch, failure: str, ) -> None: ''' Never allocate history for missing or inconsistent metadata. Missing/empty resolution must fail before quote startup. If the quote handshake names a different endpoint, join that producer before propagating failure. Assert no history writer or registry entry exists while the service nursery remains alive. ''' async def empty(symbol: str) -> None: ''' Model a provider which cannot resolve the request. ''' return None error: type[Exception] = ValueError reason: str = 'differs from' expected_quotes: int = 0 if failure == 'missing': monkeypatch.delattr(startup.mod, 'get_mkt_info') error = NotImplementedError reason = 'must expose get_mkt_info' elif failure == 'empty': monkeypatch.setattr(startup.mod, 'get_mkt_info', empty) reason = 'returned no market metadata' else: startup.mismatch = True expected_quotes = 1 async def main() -> None: ''' Catch startup failure without canceling the service nursery. ''' async with trio.open_nursery() as tn: bus = feed._FeedsBus(brokername='testfeed', nursery=tn) with pytest.raises(error, match=reason): await tn.start(start_feed(bus)) assert startup.quote_starts == expected_quotes assert startup.quote_exits == expected_quotes assert startup.history_starts == 0 assert not bus.feeds trio.run(main) def test_normal_sampler_return_joins_children( startup: Startup, ) -> None: ''' Normal sampler return must stop both persistent child tasks. Nursery exit alone would wait forever. Allow startup to finish, then make sampling return and fence task progress. Require both producer and history finalization before canceling the service. ''' async def main() -> None: ''' Let allocation finish without service cancellation. ''' startup.finish_sampler = True startup.history_gate.set() async with trio.open_nursery() as tn: bus = feed._FeedsBus(brokername='testfeed', nursery=tn) await tn.start(start_feed(bus)) await wait_all_tasks_blocked() assert startup.quote_starts == startup.quote_exits == 1 assert startup.history_starts == 1 assert startup.history_exits == 1 trio.run(main)