435 lines
17 KiB
Python
435 lines
17 KiB
Python
'''
|
|
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)
|