runner.py
1"""Common background policy facade; the market owner is injected by Platform.23Controlled policy machinery retains audit/authority/state semantics. User-facing4commands enqueue detached values; only the owner calls the controlled core.5"""67from __future__ import annotations89from typing import TYPE_CHECKING, Any, Callable, Dict, List, NoReturn, Optional1011from sim_platform.decisions.base import DecisionRunner12from sim_platform.market.pacing import validate_poll13from sim_platform.domain.models import ContractError, Intent14from sim_platform.decisions.policy.models import submit15from sim_platform.domain.json_values import copy_json1617from sim_platform.experiments.execution.controls import CONTROL_ACK_TIMEOUT_SECONDS1819if TYPE_CHECKING: # Annotation only.20 from sim_platform.decisions.policy.live.owner import PolicyOwner21 from sim_platform.decisions.policy.models import Action, DecisionRecord22 from sim_platform.decisions.policy.runner import PolicyDecisionRunner23 from sim_platform.experiments.execution.controls import ExperimentControls24 from sim_platform.experiments.execution.session import ExperimentSession25 from sim_platform.experiments.recording import ExperimentLog26 from sim_platform.experiments.scheduling.host import ExperimentRuntimeHandle2728# The detached view carries at most this many recent trades and price/volume bars.29VIEW_TRADE_LIMIT = 10030VIEW_BAR_LIMIT = 60313233class LivePolicyControls:34 """Human order/cancel commands for a Live run; handoffs are refused in Live mode.3536 Borrowed from the Live runner, which owns it; holds no resources.37 """3839 def __init__(self, runner: LivePolicyDecisionRunner, symbol: str) -> None:40 self.runner, self.symbol = runner, symbol4142 def order(43 self,44 client_id: str,45 side: str,46 quantity: int,47 limit_price: int,48 symbol: Optional[str] = None,49 ) -> DecisionRecord:50 """Send a limit order; ``symbol`` chooses one symbol of a run on several."""51 return self.runner.act(52 [submit(Intent(client_id, symbol or self.symbol, side, quantity, limit_price))]53 )5455 def market_order(56 self, client_id: str, side: str, quantity: int, symbol: Optional[str] = None57 ) -> DecisionRecord:58 """Send a market order; it is priced at acceptance (docs/reference/orders.md)."""59 order = dict(60 client_id=client_id, symbol=symbol or self.symbol, side=side, quantity=quantity61 )62 return self.runner.act([dict(kind='submit_market', order=order)])6364 def cancel(self, client_id: str) -> DecisionRecord:65 return self.runner.act([dict(kind='cancel', client_id=client_id)])6667 def handoff(self, *args: Any, **kwargs: Any) -> NoReturn:68 raise ContractError(69 'handoff uses controlled mode; live authority is fixed for this experiment'70 )717273class LivePolicyDecisionRunner(DecisionRunner):74 """Background Human/Rule runner: a pipeline drives the market at 1x on its own threads.7576 Owns everything passed in: the controlled ``core`` runner (financial session and77 audit), the experiment ``pipeline`` and ``runtime``, the optional Rule ``host`` and78 ``recorder``, and the ``barrier`` that Platform attaches after construction.79 close() releases them in order and is safe to repeat.8081 Args:82 core: The Controlled policy runner that commits every decision.83 pipeline: Drives the market and orders owner operations.84 runtime: Schedules decision work for the Rule child.85 owner: Owner-side observation capture and command handling.86 host: Rule child process host (AgentProcessHost), or None for Human. Typed87 ``Any`` because this package may not import the agents package.88 recorder: Experiment log, closed with the runner.89 """9091 background = True9293 def __init__(94 self,95 core: PolicyDecisionRunner,96 pipeline: ExperimentSession,97 runtime: ExperimentRuntimeHandle,98 owner: PolicyOwner,99 host: Any = None,100 recorder: Optional[ExperimentLog] = None,101 ) -> None:102 self.core, self.pipeline, self.runtime, self.owner, self.host = (103 core,104 pipeline,105 runtime,106 owner,107 host,108 )109 self.recorder = recorder110 self._closed = False111 self._on_close: Callable[[], None] = lambda: None112 self._controls = LivePolicyControls(self, core.market_snapshot.symbol)113 self.barrier: Optional[ExperimentControls] = None114 self.pipeline.channels.ended.add_done_callback(115 lambda _: host.request_stop() if host else None116 )117118 def on_close(self, callback: Callable[[], None]) -> None:119 self._on_close = callback120121 @property122 def run_id(self) -> str:123 return self.core.run_id124125 @property126 def closed(self) -> bool:127 return self._closed128129 @property130 def active(self) -> bool:131 return not self.closed and self.pipeline.snapshot()['state'] in (132 'ready',133 'running',134 'paused',135 'pausing',136 'ending',137 )138139 @property140 def archive_ready(self) -> bool:141 return not self.active and self.pipeline.channels.ended.done()142143 @property144 def policy_controls(self) -> LivePolicyControls:145 return self._controls146147 def detached_view(self) -> Optional[Dict[str, Any]]:148 """The owner's last published view plus market data up to the experiment clock."""149 from dataclasses import asdict150151 published = self.owner.published152 if published is None:153 return None154 view = copy_json(published)155 cutoff = min(self.pipeline.clock.target_ns(), self.pipeline.reader.manifest['last_ns'])156 reader = self.pipeline.reader157 prefix = reader.prefix(cutoff)158 view['market'] = asdict(reader.snapshot_at(cutoff))159 view['trades'] = [160 asdict(t) for t in reader.history.trades(prefix, cutoff, limit=VIEW_TRADE_LIMIT)161 ]162 view['bars'] = [163 asdict(b) for b in reader.history.bars(prefix, cutoff, limit=VIEW_BAR_LIMIT)164 ]165 return dict(166 view,167 pipeline=self.pipeline.snapshot(),168 runtime=self.runtime.snapshot(),169 control=self.barrier.snapshot() if self.barrier else None,170 )171172 def poll(173 self, *, max_events: int = 1, budget_seconds: Optional[float] = None174 ) -> Optional[Dict[str, Any]]:175 validate_poll(max_events, budget_seconds)176 return self.detached_view()177178 def act(self, actions: List[Action], state: Any = None) -> DecisionRecord:179 """Queue a Human response on the owner and wait for its committed result."""180 if self.core.config.mode != 'manual' or self.pipeline.snapshot()['state'] != 'running':181 raise ContractError('manual commands require a running Human experiment')182 return self.pipeline.submit(183 dict(184 request_id='human', operation='manual', response=dict(actions=actions, state=state)185 )186 ).result(CONTROL_ACK_TIMEOUT_SECONDS)['result']187188 def play(self, speed: Optional[float] = None) -> Any:189 if speed not in (None, 1) or isinstance(speed, bool):190 raise ContractError(191 'Live experiments support only 1x; use controlled mode for other playback'192 )193 if self.barrier is not None:194 return self.barrier.play()195 state = self.pipeline.snapshot()['state']196 if state == 'ready':197 self.pipeline.start()198 elif state == 'paused':199 self.pipeline.control_and_wait('resume')200 elif state != 'running':201 raise ContractError('experiment ended')202 if self.host:203 self.host.play()204 return None205 return None206207 def pause(self) -> Any:208 if self.barrier is not None:209 return self.barrier.pause()210 if self.host:211 self.host.pause()212 self.pipeline.channels.pause_delivery()213 self.pipeline.control_and_wait('pause')214 return None215216 def close(self) -> None:217 if self.closed:218 return219 if self.host:220 self.host.request_stop()221 if self.barrier:222 self.barrier.stop()223 else:224 self.pipeline.close()225 if self.host:226 self.host.close()227 if not self.runtime.snapshot()['closed']:228 self.runtime.close()229 self.core.close()230 if self.recorder is not None:231 self.recorder.close()232 self._closed = True233 if self.barrier:234 self.barrier.resources_closed()235 self._on_close()