Test persistent feed reuse across IPC subscriptions
Exercise the canonical endpoint registry and per-feed task lifetime through real `tractor` contexts, TCP streams, sampling and SHM. Use a controlled provider/history source and private actors rather than requiring a live Gateway or production storage. Cover, - concurrent requests held across history startup and allocation locking, requiring one writer and matching descriptors; - dated/continuous alias reuse after subscriber detach and reopen, preserving SHM tokens without another producer; - quote fanout to overlapping clients, continued delivery after one closes, and persistent writers after every client detaches; - history prepends and sampled prices visible through parent-side SHM attachments; - remote startup failure joining its producer while existing feeds continue delivering quotes; - unlinking all history/realtime buffers and index segments when the owning actor exits. Keep four complementary focused cases for missing/empty metadata, quote-start endpoint mismatch and normal sampler-return cleanup. Avoid duplicating the actor lifecycle and already-committed IB resolver tests with another fake chart/subscription framework. The actor suite does not drive Qt, a live broker, NativeDB or the samplerd bar clock. Controlled prepends prove quote progress in that scenario, not the absence of stalls during real disk backfill. (this patch was generated in some part by `opencode` using `openai/gpt-6-astra` (`openai`))wkt/land_datad_names
parent
3289c26030
commit
036b7ed9fa
|
|
@ -0,0 +1,434 @@
|
||||||
|
'''
|
||||||
|
Actor/IPC/SHM feed lifecycle integration with a controlled provider.
|
||||||
|
|
||||||
|
'''
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from decimal import Decimal
|
||||||
|
from types import ModuleType
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
import tractor
|
||||||
|
import trio
|
||||||
|
from trio.testing import wait_all_tasks_blocked
|
||||||
|
from trio_typing import TaskStatus
|
||||||
|
from tractor.ipc import _shm
|
||||||
|
|
||||||
|
from piker.accounting import Asset, MktPair
|
||||||
|
from piker.data import feed
|
||||||
|
from piker.data._sharedmem import maybe_open_shm_array
|
||||||
|
from piker.data._source import def_iohlcv_fields
|
||||||
|
from piker.data.flows import Flume
|
||||||
|
from piker.data.validate import FeedInit
|
||||||
|
|
||||||
|
|
||||||
|
@tractor.context
|
||||||
|
async def controlled_datad(
|
||||||
|
ctx: tractor.Context,
|
||||||
|
prefix: str,
|
||||||
|
) -> None:
|
||||||
|
'''
|
||||||
|
Own a real feed bus in a child actor and expose test controls.
|
||||||
|
|
||||||
|
Replace provider metadata/quotes and history retrieval only.
|
||||||
|
The real allocator, sampler, subscription handler, IPC streams
|
||||||
|
and SHM implementation run unchanged. History creates uniquely
|
||||||
|
named real buffers, then parks on its input channel to model a
|
||||||
|
backfill task awaiting its next frame. No live service is used.
|
||||||
|
|
||||||
|
Control replies fence subscription changes with
|
||||||
|
``trio.testing.wait_all_tasks_blocked()``. Quote completion is
|
||||||
|
acknowledged by receipt on the actual subscriber IPC stream,
|
||||||
|
not by sleeping or inspecting the provider's send operation.
|
||||||
|
|
||||||
|
'''
|
||||||
|
markets: dict[str, MktPair] = {}
|
||||||
|
for name, expiry in (
|
||||||
|
('qqq', ''), ('mnq', '20261218'), ('mnq', '20270319'),
|
||||||
|
('broken', ''),
|
||||||
|
):
|
||||||
|
venue = 'nasdaq'
|
||||||
|
atype = 'stock'
|
||||||
|
if expiry:
|
||||||
|
venue = 'cme'
|
||||||
|
atype = 'future'
|
||||||
|
mkt = MktPair(
|
||||||
|
dst=Asset(name=name, atype=atype, tx_tick=Decimal('1')),
|
||||||
|
src=Asset(
|
||||||
|
name='usd', atype='fiat', tx_tick=Decimal('.01'),
|
||||||
|
),
|
||||||
|
price_tick=Decimal('.25'),
|
||||||
|
size_tick=Decimal('1'),
|
||||||
|
bs_mktid=f'{name}{expiry}',
|
||||||
|
broker='testfeed',
|
||||||
|
venue=venue,
|
||||||
|
expiry=expiry,
|
||||||
|
_fqme_without_src=True,
|
||||||
|
)
|
||||||
|
markets[mkt.bs_fqme] = mkt
|
||||||
|
markets['mnq.cme'] = markets['mnq.cme.20261218']
|
||||||
|
producers: dict[str, trio.MemorySendChannel] = {}
|
||||||
|
backfills: dict[str, trio.MemorySendChannel] = {}
|
||||||
|
starts: list[str] = []
|
||||||
|
exits: list[str] = []
|
||||||
|
histories: list[str] = []
|
||||||
|
history_gate = trio.Event()
|
||||||
|
history_gate.set()
|
||||||
|
|
||||||
|
async def get_mkt_info(symbol: str) -> tuple[MktPair, None]:
|
||||||
|
'''
|
||||||
|
Resolve the continuous spelling to the December endpoint.
|
||||||
|
|
||||||
|
'''
|
||||||
|
return markets[symbol], None
|
||||||
|
|
||||||
|
async def stream_quotes(
|
||||||
|
send_chan: trio.MemorySendChannel,
|
||||||
|
symbols: list[str],
|
||||||
|
feed_is_live: trio.Event,
|
||||||
|
task_status: TaskStatus = trio.TASK_STATUS_IGNORED,
|
||||||
|
) -> None:
|
||||||
|
'''
|
||||||
|
Forward controlled ticks through the real sampler input.
|
||||||
|
|
||||||
|
'''
|
||||||
|
mkt = markets[symbols[0]]
|
||||||
|
key: str = mkt.bs_fqme
|
||||||
|
tx, rx = trio.open_memory_channel(8)
|
||||||
|
starts.append(key)
|
||||||
|
producers[key] = tx
|
||||||
|
try:
|
||||||
|
async with rx, tx:
|
||||||
|
feed_is_live.set()
|
||||||
|
task_status.started((
|
||||||
|
[FeedInit(mkt_info=mkt)], {'last': 100.},
|
||||||
|
))
|
||||||
|
async for quote in rx:
|
||||||
|
await send_chan.send({key: quote})
|
||||||
|
finally:
|
||||||
|
producers.pop(key)
|
||||||
|
exits.append(key)
|
||||||
|
|
||||||
|
async def history(
|
||||||
|
mod: ModuleType,
|
||||||
|
mkt: MktPair,
|
||||||
|
some_data_ready: trio.Event,
|
||||||
|
feed_is_live: trio.Event,
|
||||||
|
loglevel: str,
|
||||||
|
task_status: TaskStatus = trio.TASK_STATUS_IGNORED,
|
||||||
|
) -> None:
|
||||||
|
'''
|
||||||
|
Seed real SHM and accept deterministic historical prepends.
|
||||||
|
|
||||||
|
'''
|
||||||
|
key: str = mkt.bs_fqme
|
||||||
|
if key == 'broken.nasdaq':
|
||||||
|
raise ValueError('controlled history failure')
|
||||||
|
histories.append(key)
|
||||||
|
await history_gate.wait()
|
||||||
|
buffers = []
|
||||||
|
for suffix in ('hist', 'rt'):
|
||||||
|
shm, opened = maybe_open_shm_array(
|
||||||
|
key=f'{prefix}.{key}.{suffix}',
|
||||||
|
size=32,
|
||||||
|
append_start_index=16,
|
||||||
|
dtype=np.dtype(def_iohlcv_fields),
|
||||||
|
)
|
||||||
|
assert opened, f'Duplicate SHM writer for {key}'
|
||||||
|
rows = np.zeros(2, dtype=def_iohlcv_fields)
|
||||||
|
rows['time'] = [1000, 1001]
|
||||||
|
for field in ('open', 'high', 'low', 'close'):
|
||||||
|
rows[field] = 100.
|
||||||
|
shm.push(rows)
|
||||||
|
buffers.append(shm)
|
||||||
|
hist, rt = buffers
|
||||||
|
tx, rx = trio.open_memory_channel(8)
|
||||||
|
backfills[key] = tx
|
||||||
|
some_data_ready.set()
|
||||||
|
task_status.started((15, hist, 15, rt))
|
||||||
|
try:
|
||||||
|
async with tx, rx:
|
||||||
|
async for _ in rx:
|
||||||
|
rows = np.zeros(1, dtype=def_iohlcv_fields)
|
||||||
|
rows['time'] = 999
|
||||||
|
rows['close'] = 99.
|
||||||
|
hist.push(rows, prepend=True)
|
||||||
|
finally:
|
||||||
|
backfills.pop(key)
|
||||||
|
|
||||||
|
mod = ModuleType('testfeed')
|
||||||
|
mod.name = 'testfeed'
|
||||||
|
mod.get_mkt_info = get_mkt_info
|
||||||
|
mod.stream_quotes = stream_quotes
|
||||||
|
with pytest.MonkeyPatch.context() as patch:
|
||||||
|
async with trio.open_nursery() as tn:
|
||||||
|
bus = feed._FeedsBus(brokername='testfeed', nursery=tn)
|
||||||
|
patch.setattr(feed, 'get_brokermod', lambda _: mod)
|
||||||
|
patch.setattr(feed, 'get_feed_bus', lambda _: bus)
|
||||||
|
patch.setattr(feed, 'manage_history', history)
|
||||||
|
await ctx.started(True)
|
||||||
|
async with ctx.open_stream() as controls:
|
||||||
|
async for request in controls:
|
||||||
|
operation: str = request['op']
|
||||||
|
if operation == 'hold-history':
|
||||||
|
history_gate = trio.Event()
|
||||||
|
elif operation == 'release-history':
|
||||||
|
history_gate.set()
|
||||||
|
elif operation == 'quote':
|
||||||
|
await producers[request['key']].send({
|
||||||
|
'last': request['price'],
|
||||||
|
'ticks': [{
|
||||||
|
'type': 'trade',
|
||||||
|
'price': request['price'],
|
||||||
|
'size': 1.,
|
||||||
|
'broker_time': 1001.,
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
elif operation == 'backfill':
|
||||||
|
await backfills[request['key']].send(True)
|
||||||
|
await wait_all_tasks_blocked()
|
||||||
|
await controls.send({
|
||||||
|
'starts': list(starts),
|
||||||
|
'exits': list(exits),
|
||||||
|
'histories': list(histories),
|
||||||
|
'producers': sorted(producers),
|
||||||
|
'feeds': sorted(bus.feeds),
|
||||||
|
'allocation_waiters': (
|
||||||
|
bus.task_lock.statistics().tasks_waiting
|
||||||
|
),
|
||||||
|
'subs': {
|
||||||
|
key: len(value)
|
||||||
|
for key, value in (
|
||||||
|
bus._subscribers.items()
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
tn.cancel_scope.cancel()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('first_request', [
|
||||||
|
'mnq.cme.20261218', 'mnq.cme',
|
||||||
|
])
|
||||||
|
def test_persistent_feed_ipc_reopen_and_quote_flow(
|
||||||
|
first_request: str,
|
||||||
|
) -> None:
|
||||||
|
'''
|
||||||
|
Keep actual quote delivery alive across IPC subscriber lifetimes.
|
||||||
|
|
||||||
|
Reproduce dated-search then continuous-alias reopening against a
|
||||||
|
persistent datad actor. Two simultaneous subscriber contexts must
|
||||||
|
receive the same quote; closing one must preserve the other,
|
||||||
|
and closing all must preserve writers for a later multi-endpoint
|
||||||
|
reopen. Verify identical SHM tokens and sampled prices through a
|
||||||
|
real read-only SHM attachment in the parent process.
|
||||||
|
|
||||||
|
Before that sequence, hold QQQ history startup until one IPC
|
||||||
|
request is initializing and another waits on the allocation lock.
|
||||||
|
Release the gate and assert one writer and identical descriptors.
|
||||||
|
|
||||||
|
Also prepend history while live sampling continues, and inject a
|
||||||
|
startup failure after quotes start. Existing subscriptions must
|
||||||
|
still receive new ticks and the failed producer must finalize.
|
||||||
|
This covers actual TCP IPC/SHM/sampling, not Qt, IB connectivity,
|
||||||
|
NativeDB I/O or the separate samplerd bar-clock process.
|
||||||
|
|
||||||
|
'''
|
||||||
|
async def main() -> None:
|
||||||
|
'''
|
||||||
|
Run a private actor tree with ephemeral transport endpoints.
|
||||||
|
|
||||||
|
'''
|
||||||
|
prefix: str = f'feed_e2e_{uuid4().hex}'
|
||||||
|
async with (
|
||||||
|
tractor.open_root_actor(
|
||||||
|
name=prefix,
|
||||||
|
tpt_bind_addrs=[('127.0.0.1', 0)],
|
||||||
|
),
|
||||||
|
tractor.open_nursery() as an,
|
||||||
|
):
|
||||||
|
portal = await an.start_actor(
|
||||||
|
name='datad.testfeed',
|
||||||
|
enable_modules=[__name__, feed.__name__],
|
||||||
|
)
|
||||||
|
async with (
|
||||||
|
portal.open_context(
|
||||||
|
controlled_datad, prefix=prefix,
|
||||||
|
) as (control_ctx, ready),
|
||||||
|
control_ctx.open_stream() as controls,
|
||||||
|
):
|
||||||
|
assert ready
|
||||||
|
|
||||||
|
async def control(op: str, **kwargs) -> dict:
|
||||||
|
'''
|
||||||
|
Fence actor state after a controlled action.
|
||||||
|
|
||||||
|
'''
|
||||||
|
await controls.send({'op': op, **kwargs})
|
||||||
|
return await controls.receive()
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def subscribe(
|
||||||
|
symbols: list[str],
|
||||||
|
) -> AsyncIterator[tuple[dict, tractor.MsgStream]]:
|
||||||
|
'''
|
||||||
|
Open real feed IPC and drain its initial quotes.
|
||||||
|
|
||||||
|
'''
|
||||||
|
async with (
|
||||||
|
portal.open_context(
|
||||||
|
feed.open_feed_bus,
|
||||||
|
brokername='testfeed',
|
||||||
|
symbols=symbols,
|
||||||
|
) as (ctx, descriptors),
|
||||||
|
ctx.open_stream() as stream,
|
||||||
|
):
|
||||||
|
for _ in descriptors:
|
||||||
|
await stream.receive()
|
||||||
|
await control('state')
|
||||||
|
yield descriptors, stream
|
||||||
|
|
||||||
|
key: str = 'mnq.cme.20261218'
|
||||||
|
fqme: str = f'{key}.testfeed'
|
||||||
|
|
||||||
|
# Force two requests to overlap before QQQ registers.
|
||||||
|
# Both travel through actual IPC and open_feed_bus's
|
||||||
|
# allocation lock, rather than a fake client context.
|
||||||
|
await control('hold-history')
|
||||||
|
ready_tx, ready_rx = trio.open_memory_channel(2)
|
||||||
|
|
||||||
|
async def concurrent_subscriber() -> None:
|
||||||
|
'''
|
||||||
|
Hold an IPC subscription after reporting startup.
|
||||||
|
|
||||||
|
Do not use the shared controls stream from these
|
||||||
|
tasks: only the parent reads its acknowledgments.
|
||||||
|
|
||||||
|
'''
|
||||||
|
async with (
|
||||||
|
portal.open_context(
|
||||||
|
feed.open_feed_bus,
|
||||||
|
brokername='testfeed',
|
||||||
|
symbols=['qqq.nasdaq'],
|
||||||
|
) as (ctx, descriptors),
|
||||||
|
ctx.open_stream() as stream,
|
||||||
|
):
|
||||||
|
await stream.receive()
|
||||||
|
await ready_tx.send(descriptors)
|
||||||
|
await trio.sleep_forever()
|
||||||
|
|
||||||
|
async with (
|
||||||
|
ready_tx,
|
||||||
|
ready_rx,
|
||||||
|
trio.open_nursery() as clients,
|
||||||
|
):
|
||||||
|
clients.start_soon(concurrent_subscriber)
|
||||||
|
clients.start_soon(concurrent_subscriber)
|
||||||
|
# IPC requests may still be in flight. Poll the
|
||||||
|
# actor until one request is in history startup
|
||||||
|
# and the other waits on its allocation lock.
|
||||||
|
state = await control('state')
|
||||||
|
while (
|
||||||
|
not state['histories']
|
||||||
|
or
|
||||||
|
state['allocation_waiters'] != 1
|
||||||
|
):
|
||||||
|
state = await control('state')
|
||||||
|
assert state['feeds'] == []
|
||||||
|
await control('release-history')
|
||||||
|
first_client = await ready_rx.receive()
|
||||||
|
second_client = await ready_rx.receive()
|
||||||
|
assert first_client == second_client
|
||||||
|
state = await control('state')
|
||||||
|
assert state['starts'] == ['qqq.nasdaq']
|
||||||
|
assert state['histories'] == ['qqq.nasdaq']
|
||||||
|
clients.cancel_scope.cancel()
|
||||||
|
|
||||||
|
async with subscribe(['qqq.nasdaq']) as (_, qqq):
|
||||||
|
async with subscribe([first_request]) as (
|
||||||
|
first, dated,
|
||||||
|
):
|
||||||
|
original = first[fqme]
|
||||||
|
await control('quote', key=key, price=101.)
|
||||||
|
received = await dated.receive()
|
||||||
|
assert received[fqme]['last'] == 101.
|
||||||
|
state = await control('state')
|
||||||
|
assert state['subs'][key] == 0
|
||||||
|
await control(
|
||||||
|
'quote', key='qqq.nasdaq', price=102.,
|
||||||
|
)
|
||||||
|
assert (await qqq.receive())[
|
||||||
|
'qqq.nasdaq.testfeed'
|
||||||
|
]['last'] == 102.
|
||||||
|
|
||||||
|
async with subscribe([
|
||||||
|
'mnq.cme', 'mnq.cme.20270319', 'qqq.nasdaq',
|
||||||
|
]) as (reopened, multi):
|
||||||
|
assert reopened[fqme]['_rt_shm_token'] == (
|
||||||
|
original['_rt_shm_token']
|
||||||
|
)
|
||||||
|
flume = Flume.from_msg(reopened[fqme])
|
||||||
|
async with subscribe([key]) as (_, second):
|
||||||
|
await control('quote', key=key, price=103.)
|
||||||
|
received = await multi.receive()
|
||||||
|
assert received[fqme]['last'] == 103.
|
||||||
|
received = await second.receive()
|
||||||
|
assert received[fqme]['last'] == 103.
|
||||||
|
await control('backfill', key=key)
|
||||||
|
with pytest.raises(
|
||||||
|
tractor.RemoteActorError,
|
||||||
|
match='controlled history failure',
|
||||||
|
):
|
||||||
|
async with subscribe(['broken.nasdaq']):
|
||||||
|
pytest.fail(
|
||||||
|
'Failed feed reported startup'
|
||||||
|
)
|
||||||
|
state = await control('state')
|
||||||
|
assert state['exits'] == ['broken.nasdaq']
|
||||||
|
assert len(state['histories']) == 3
|
||||||
|
assert len(state['producers']) == 3
|
||||||
|
await control('quote', key=key, price=104.)
|
||||||
|
received = await multi.receive()
|
||||||
|
assert received[fqme]['last'] == 104.
|
||||||
|
assert flume.rt_shm.array['close'][-1] == 104.
|
||||||
|
assert flume.hist_shm.array['time'][0] == 999.
|
||||||
|
march: str = 'mnq.cme.20270319'
|
||||||
|
await control('quote', key=march, price=105.)
|
||||||
|
received = await multi.receive()
|
||||||
|
march_quote = received[f'{march}.testfeed']
|
||||||
|
assert march_quote['last'] == 105.
|
||||||
|
state = await control('state')
|
||||||
|
assert all(
|
||||||
|
count == 0 for count in state['subs'].values()
|
||||||
|
)
|
||||||
|
assert len(state['producers']) == 3
|
||||||
|
assert state['starts'].count(key) == 1
|
||||||
|
await an.cancel()
|
||||||
|
|
||||||
|
# The child owned these buffers; its actor-lifetime cleanup
|
||||||
|
# must unlink them even though the parent attached to read.
|
||||||
|
names: set[str] = set()
|
||||||
|
for descriptor in reopened.values():
|
||||||
|
for field in ('_hist_shm_token', '_rt_shm_token'):
|
||||||
|
token = _shm.NDToken.from_msg(descriptor[field])
|
||||||
|
names.update({
|
||||||
|
token.shm_name,
|
||||||
|
token.shm_first_index_name,
|
||||||
|
token.shm_last_index_name,
|
||||||
|
})
|
||||||
|
assert len(names) == 18
|
||||||
|
for name in names:
|
||||||
|
with pytest.raises(FileNotFoundError):
|
||||||
|
segment = _shm.SharedMemory(name=name, create=False)
|
||||||
|
segment.close()
|
||||||
|
|
||||||
|
async def bounded_main() -> None:
|
||||||
|
'''
|
||||||
|
Bound missed handshakes while allowing actor cleanup to run.
|
||||||
|
|
||||||
|
'''
|
||||||
|
with trio.fail_after(30):
|
||||||
|
await main()
|
||||||
|
|
||||||
|
trio.run(bounded_main)
|
||||||
|
|
@ -0,0 +1,230 @@
|
||||||
|
'''
|
||||||
|
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)
|
||||||
Loading…
Reference in New Issue