m/market labResearch, with a record.
Source on GitHub ↗

runtime_policy.py

1"""Trusted prepared-market observation adapter injected into the Runtime child.23Only this trusted adapter opens the immutable event index. Agent and Tools never4receive its path or reader. Financial notifications retain their existing5journal sequence; clock-visible market observations have a separate watermark.6"""78from __future__ import annotations910from typing import TYPE_CHECKING, Any, Dict, Optional, Union1112from sim_platform.experiments.scheduling.clock import real_delay_ns13from sim_platform.experiments.scheduling.policy.controller import LiveWorkPolicy14from sim_platform.market.prepared.reader import PreparedMarket1516if TYPE_CHECKING:  # Annotation only.17    from sim_platform.experiments.scheduling.clock import ClockReader18    from sim_platform.experiments.scheduling.worker import NoticeCallback19    from sim_platform.market.prepared.publications import PublicationReader2021# Fail work if a model receipt is still unsealed after this many wall seconds.22RECEIPT_SEAL_TIMEOUT_SECONDS = 523# Poll interval while an attempt waits for its receipt seal.24EXPIRY_POLL_SECONDS = 0.0125NS_PER_SECOND = 1e9262728class PreparedWorkPolicy(LiveWorkPolicy):29    """LiveWorkPolicy that also watches the prepared market inside the Runtime child.3031    Built in the Runtime child by its factory; it opens its own read-only prepared32    reader and closes it in end(). Market updates come from the reader at the clock's33    time; financial notifications cannot move market visibility backwards.34    """3536    def __init__(37        self, configuration: Dict[str, Any], clock: ClockReader, notice: NoticeCallback38    ) -> None:39        super().__init__(configuration, clock, notice)40        self._reader: Union[PreparedMarket, PublicationReader] = PreparedMarket(41            configuration['prepared_artifact']42        )43        if configuration.get('prepared_news'):44            from sim_platform.market.prepared.publications import PublicationReader45            from sim_platform.market.models import NewsRecord4647            self._reader = PublicationReader(48                self._reader, tuple(NewsRecord(**n) for n in configuration['prepared_news'])49            )50        self._market_prefix = self._reader.prefix(clock.target_ns())51        self._visible_sequence = self._reader.snapshot_at(clock.target_ns()).sequence52        self.observed['sequence'] = self._visible_sequence53        self._reader_closed = False54        self.attempts.require_receipt_seal = True55        self._seal_pending_since: Optional[float] = None56        self._model_error: Optional[str] = None5758    def _notice(self, event: Optional[Dict[str, Any]]) -> None:59        if event is not None and event['event'] == 'attempt_failed':60            self._model_error = event.get('error')61        super()._notice(event)6263    def snapshot(self) -> Dict[str, Any]:64        return dict(super().snapshot(), model_error=self._model_error)6566    def _observe(self, data: Dict[str, Any], *, resync: bool = False) -> Dict[str, bool]:67        # A delayed financial publication cannot move market visibility backwards.68        from sim_platform.domain.json_values import copy_json6970        data = copy_json(data)71        data['observation']['sequence'] = max(72            data['observation']['sequence'], self._visible_sequence73        )74        data['events'] = [e for e in data['events'] if e['kind'] != 'market_update']75        return super()._observe(data, resync=resync)7677    def step(self) -> None:78        if not self._stopped and not self._paused and self.clock.snapshot()['running']:79            self._market_now = self.clock.target_ns()80            now = min(self._market_now, self._reader.manifest['last_ns'])81            prefix = self._reader.prefix(now)82            if prefix > self._market_prefix:83                self._market_prefix = prefix84                self._visible_sequence = self._reader.snapshot_at(now).sequence85                self.observed['sequence'] = self._visible_sequence86                self.work.observe(87                    dict(kind='market_update', symbol=self.work.symbol), self._position()88                )89        super().step()90        import time9192        if self._paused:93            self._seal_pending_since = None94        elif self.attempts.state == 'expiry_pending':95            if self._seal_pending_since is None:96                self._seal_pending_since = time.monotonic()97            elif time.monotonic() - self._seal_pending_since > RECEIPT_SEAL_TIMEOUT_SECONDS:98                self.work.end('MODEL_RECEIPT_UNAVAILABLE', failed=True)99                self.attempts.end()100                self.notice('platform_failure', dict(error='MODEL_RECEIPT_UNAVAILABLE'))101        else:102            self._seal_pending_since = None103104    def dispatch(self, name: str, data: Dict[str, Any]) -> Any:105        if name == 'model_receipt':106            accepted = self.attempts.receive_at(107                data['attempt_id'],108                data['received_ns'],109                result=(110                    dict(received=True, **({'usage': data['usage']} if data.get('usage') else {}))111                    if data.get('error') is None112                    else None113                ),114                error=data.get('error'),115                retry_after_seconds=data.get('retry_after_seconds'),116            )117            sealed = self.attempts.seal_receipt(data['attempt_id'])118            return dict(accepted=accepted, sealed=sealed)119        return super().dispatch(name, data)120121    def wait_seconds(self) -> Optional[float]:122        delay = super().wait_seconds()123        if self.attempts.state == 'expiry_pending':124            delay = EXPIRY_POLL_SECONDS125        if self._stopped or self._paused or not self.clock.snapshot()['running']:126            return delay127        if self._market_prefix >= self._reader.manifest['frames']:128            return delay129        next_ns = self._reader.event_time(self._market_prefix)130        market_delay = real_delay_ns(self.clock, next_ns) / NS_PER_SECOND131        return min(delay, market_delay) if delay is not None else market_delay132133    def end(self, reason: str) -> None:134        try:135            super().end(reason)136        finally:137            if not self._reader_closed:138                self._reader.close()139                self._reader_closed = True