runner.py
1"""Decisions run only after the market and existing orders have committed."""23from __future__ import annotations45from typing import (6 TYPE_CHECKING,7 Any,8 Callable,9 ContextManager,10 Dict,11 Iterable,12 List,13 Optional,14 Tuple,15 Union,16)1718from sim_platform.domain.models import ContractError19from sim_platform.decisions.policy.models import (20 CAPABILITIES,21 DecisionConfig,22 Observation,23 fingerprint,24)25from sim_platform.decisions.policy.handoffs import DecisionRequest, StaleAuthority, decision_state2627from sim_platform.decisions.policy.contracts import policy_descriptor, default_config, Policy28from sim_platform.resources import cleanup_after_error, serialized29from sim_platform.decisions.base import DecisionRunner3031if TYPE_CHECKING: # Annotation only.32 from sim_platform.decisions.policy.controls import PolicyControls33 from sim_platform.decisions.policy.handoffs import (34 HandoffCondition,35 HandoffRecord,36 SwitchRecord,37 )38 from sim_platform.decisions.policy.invocation import InvocationResult39 from sim_platform.decisions.policy.models import (40 Action,41 DecisionJournal,42 DecisionRecord,43 MarketInput,44 PolicyResponse,45 )46 from sim_platform.decisions.policy.scheduling import HandoffSchedule47 from sim_platform.decisions.service import ActionResult48 from sim_platform.execution.models import ExecutionSnapshot, Frontier49 from sim_platform.execution.session import ExecutionSession50 from sim_platform.experiments.execution.market import (51 ExecutionCommands,52 LocalMarketExecution,53 )54 from sim_platform.market.models import MarketEvent, MarketSnapshot, MarketTrade, NewsRecord55 from sim_platform.market.pacing import PlaybackSchedule5657 # Opens the run's financial session: (profile, run_id, maker, market) -> session.58 ExecutionFactory = Callable[[str, str, str, MarketInput], ExecutionSession]5960# Marks "no response supplied", so a supplied None is still validated as a response.61_UNSET = object()62# Run events and decision summaries shown in the background owner's presentation.63PRESENTATION_RECORD_LIMIT = 1006465# Detached presentation reads for the Live owner: 'run' (the run without records),66# 'events', 'decisions' (recent summaries) and 'handoffs'.67ActivityRecords = Dict[str, Any]686970def several_markets(market: MarketSnapshot) -> Optional[Tuple[MarketSnapshot, ...]]:71 """Every symbol's book when the market covers several symbols, else None."""72 books = getattr(market, 'books', None)73 return tuple(books.values()) if books and len(books) > 1 else None747576class PolicyDecisionRunner(DecisionRunner):77 """Existing human/rule observation → policy → atomic decision implementation.7879 Owns the run's ExecutionSession (opened through ``execution_factory``) and closes80 it on close(); it borrows the market, whose lifetime stays with the caller. All81 public mutating methods run under the session's control lock (``serialized``).82 Authority is a (maker, generation) pair that only a committed handoff changes.8384 Args:85 operations: App financial reads/writes (DatabaseOperations). Typed ``Any``86 because the application package is not annotated yet.87 profile: Profile that owns the run.88 run_id: Run already configured with a decision policy and no journal.89 maker: Decision maker that currently holds authority.90 market: Market to observe and drive; borrowed.91 policy: Policy whose descriptor must equal the run's configured policy.92 execution_factory: Opens the owned ExecutionSession.93 commands: Financial commit port; defaults to ExecutionCommands over operations.94 """9596 def __init__(97 self,98 operations: Any,99 profile: str,100 run_id: str,101 maker: str,102 market: MarketInput,103 policy: Policy,104 *,105 execution_factory: ExecutionFactory,106 commands: Optional[ExecutionCommands] = None,107 ) -> None:108 run = operations.run(profile, run_id)109 if 'decision' not in run['config']:110 raise ContractError('run is not configured for decisions')111 self.config = DecisionConfig(**run['config']['decision']['config'])112 descriptor = run['config']['decision']['policy']113 if descriptor != policy_descriptor(policy):114 raise ContractError('policy identity, parameters or capabilities differ from run')115 if any(c not in CAPABILITIES for c in descriptor['requires']):116 raise ContractError('required data capability is unavailable')117 if run['policy_state']:118 raise ContractError('decision restart is unsupported')119 self._app, self._profile, self._run, self._maker = operations, profile, run_id, maker120 from sim_platform.experiments.execution.market import ExecutionCommands121122 self._commands = commands or ExecutionCommands(operations.commit_decision, profile, run_id)123 self._market, self._policy = market, policy124 from sim_platform.market.pacing import PlaybackSchedule125 from sim_platform.decisions.policy.controls import PolicyControls126127 self._playback: PlaybackSchedule = PlaybackSchedule(market)128 self._controls: PolicyControls = PolicyControls(self, market, maker, policy)129 self._boundary = 0130 self._last_time: Optional[int] = None131 self._busy = False132 self._replaying = False133 from sim_platform.decisions.policy.scheduling import HandoffSchedule134135 self._generation = 0136 self._schedule: HandoffSchedule = HandoffSchedule()137 self._execution = execution_factory(profile, run_id, maker, market)138 from sim_platform.experiments.execution.market import LocalMarketExecution139140 self._market_execution: LocalMarketExecution = LocalMarketExecution(self._execution, market)141 self._on_close: Callable[[], None] = lambda: None142 self._observation_factory: Optional[Callable[[str], Observation]] = None143 self._execution.on_close(self._execution_closed)144 # Initial journal is schema-compatible with the existing finite JSON policy state.145 try:146 operations.initialize_decisions(profile, run_id, maker)147 except Exception as exc:148 cleanup_after_error(exc, self._execution.close)149 raise150151 def control_boundary(self) -> ContextManager[None]:152 return self._execution.control_boundary()153154 def _execution_closed(self) -> None:155 self._schedule.clear()156 # A policy that owns a resource, such as a model process, releases it here.157 close = getattr(self._policy, 'close', None)158 if callable(close):159 close()160 self._on_close()161162 def on_close(self, callback: Callable[[], None]) -> None:163 self._on_close = callback164165 @property166 def run_id(self) -> str:167 return self._run168169 @property170 def snapshot(self) -> ExecutionSnapshot:171 return self._execution.snapshot172173 @property174 def closed(self) -> bool:175 return self._execution.closed176177 @property178 def active(self) -> bool:179 return not self.closed and self.snapshot.status == 'running'180181 @property182 def policy_controls(self) -> PolicyControls:183 return self._controls184185 @property186 def market_snapshot(self) -> MarketSnapshot:187 return self._execution.market_snapshot188189 @property190 def records(self) -> List[DecisionRecord]:191 return self._app.decision_records(self._profile, self._run)192193 def recent_decisions(self, limit: int = 1) -> List[Dict[str, Any]]:194 """Bounded presentation summaries; records remains the full audit API."""195 return self._app.decision_summaries(self._profile, self._run, limit=limit)196197 @property198 def replay_state(self) -> Frontier:199 return self._execution.replay_state200201 @property202 def generation(self) -> int:203 return self._generation204205 @serialized206 def begin_recorded_replay(self) -> None:207 """Switch to Replay: later decisions come only from recorded values."""208 self._execution.validate_control()209 if self._boundary or self._app.decision_journal(self._profile, self._run).get(210 '_record_count', 0211 ):212 raise ContractError('recorded replay must begin before decisions')213 self._replaying = True214215 @serialized216 def apply_recorded_operation(217 self,218 position: Dict[str, Any],219 *,220 response: Optional[PolicyResponse] = None,221 action: Optional[Action] = None,222 ) -> Union[DecisionRecord, Tuple[ActionResult, ExecutionSnapshot]]:223 """Trusted prepared Replay: supplied actions only, never invoke a policy."""224 if not self._replaying or (response is None) == (action is None):225 raise ContractError('supply one recorded response or financial action in Replay')226 if action is None:227 return self._decide('manual', response, position=position)228 self._execution.validate_control()229 return self._commands.commit(230 self._maker, self.market_snapshot, action=action, position=position231 )232233 @serialized234 def apply_recorded_decision(self, record: DecisionRecord) -> DecisionRecord:235 """Replay one audited decision after checking its observation still matches."""236 if not self._replaying:237 raise ContractError('runner is not in recorded replay mode')238 observation = self.observe(record['observation']['trigger'])239 if fingerprint(observation.to_json()) != record['fingerprint']:240 raise ContractError('recorded observation mismatch')241 if record['status'] == 'ok':242 return self._decide(record['observation']['trigger'], record['response'])243 actual = self._app.commit_decision(244 self._profile,245 self._run,246 self._maker,247 self._market.snapshot,248 record,249 self._app.decision_journal(self._profile, self._run),250 )251 self._execution.fail('policy ' + record['status'])252 return actual253254 @serialized255 def apply_recorded_handoff(self, record: HandoffRecord, policy: Policy) -> HandoffRecord:256 if not self._replaying:257 raise ContractError('runner is not in recorded replay mode')258 return self.handoff(259 record['to_maker'],260 policy,261 DecisionConfig(**record['to_policy']['config']),262 state_mode=record['state_mode'],263 reason=record['reason'],264 _schedule_id=record['schedule_id'],265 )266267 @serialized268 def apply_recorded_rejection(self, record: Dict[str, Any]) -> None:269 """Replay one audited authority rejection (see handoffs.reject for its keys)."""270 if not self._replaying:271 raise ContractError('runner is not in recorded replay mode')272 return self._app.handoff(273 'reject',274 self._profile,275 self._run,276 record['maker_id'],277 record['generation'],278 record['reason'],279 )280281 @serialized282 def finish_recorded_replay(283 self, status: str, reason: str, *, time_ns: Optional[int] = None284 ) -> ExecutionSnapshot:285 if time_ns is not None:286 if not self._replaying:287 raise ContractError('recorded finish requires Replay')288 return self._execution.finish(status, reason, time_ns=time_ns)289 return self._execution.finish_recorded_replay(status, reason)290291 @serialized292 def resume_recorded_replay(self, bindings: Optional[Dict[str, Policy]] = None) -> None:293 """Leave Replay and continue live with policies bound per maker ID."""294 if not self._replaying:295 raise ContractError('runner is not in recorded replay mode')296 journal = self._app.decision_journal(self._profile, self._run)297 expected = self._app.run(self._profile, self._run, include_records=False)['config'][298 'decision'299 ]['policy']300 bindings = bindings or {}301 selected = bindings.get(self._maker)302 if selected is None and expected['kind'] == 'human':303 from sim_platform.decisions.policy.policies import HumanPolicy304305 selected = HumanPolicy()306 if selected is None or policy_descriptor(selected) != expected:307 raise ContractError('supply a compatible policy binding to resume this maker')308 self._schedule.resume_bindings(journal, bindings)309 self._policy = selected310 self._replaying = False311312 @property313 def handoffs(self) -> List[HandoffRecord]:314 return self._app.decision_journal(self._profile, self._run).get('handoffs', [])315316 def controller(self) -> DecisionController:317 """Capture instruction authority; a handle never follows a later handoff."""318 return DecisionController(self, self._maker, self._generation)319320 def _check_authority(self, maker: str, generation: int) -> None:321 """Raise StaleAuthority (after auditing it) unless maker/generation hold authority."""322 if self._execution.closed:323 raise ContractError('execution session is closed')324 status, owner, current_generation = self._app.decision_authority(self._profile, self._run)325 if status != 'running':326 raise ContractError('run is not active')327 if maker != owner or generation != current_generation:328 self._app.handoff(329 'reject', self._profile, self._run, maker, generation, 'stale instruction authority'330 )331 raise StaleAuthority('stale instruction authority')332333 def observe(self, trigger: str = 'manual') -> Observation:334 self._execution.validate_control()335 if self._observation_factory is not None:336 return self._observation_factory(trigger)337 limit = self.config.history_limit338 spec = getattr(self._policy, 'bar_spec', None)339 several = several_markets(self.market_snapshot)340 wants_bars = 'bars' in self._policy.requires and spec is not None341 return Observation(342 self._boundary,343 trigger,344 self.market_snapshot,345 self.snapshot,346 self._market.trades(limit=limit),347 self._market.news(limit=limit),348 spec.completed(self._market) if spec and wants_bars and not several else None,349 several,350 spec.completed_by_symbol(self._market) if spec and wants_bars and several else None,351 )352353 def _policy_due(self, time_ns: int) -> bool:354 """A policy with decision_due() chooses its own cadence, such as once per bar."""355 due = getattr(self._policy, 'decision_due', None)356 return True if due is None else bool(due(time_ns))357358 def _decide(359 self,360 trigger: str,361 response: Any = _UNSET,362 request: Optional[DecisionRequest] = None,363 *,364 position: Optional[Dict[str, Any]] = None,365 ) -> DecisionRecord:366 """Invoke the policy (or use ``response``), then commit and audit the decision.367368 A policy failure is committed as a non-ok record and fails the run.369 """370 if self._busy:371 raise ContractError('decision runner is already invoking a policy')372 self._check_authority(self._maker, self._generation)373 observation = self.observe(trigger) if request is None else request.observation374 journal = (375 self._app.decision_journal(self._profile, self._run)376 if request is None377 else request.journal378 )379 if journal['_record_count'] >= self.config.max_decisions:380 self._execution.fail('decision budget exhausted')381 raise ContractError('decision budget exhausted')382 observation_json = observation.to_json()383 record = {384 'index': journal['_record_count'] + 1,385 'observation': observation_json,386 'maker_id': self._maker,387 'generation': self._generation,388 'fingerprint': fingerprint(observation_json),389 'status': 'ok',390 'error': None,391 'response': None,392 'attempted_response': None,393 }394 self._busy = True395 try:396 from sim_platform.decisions.policy.invocation import invoke397398 record.update(399 invoke(400 self._policy,401 observation,402 journal['state'],403 self.config,404 response=response,405 supplied=response is not _UNSET,406 )407 )408 record = self._commands.commit(409 self._maker, self.market_snapshot, record, journal, position=position410 )411 self._last_time = observation.market.time_ns412 if record['status'] != 'ok':413 self._execution.fail(f"policy {record['status']}")414 return record415 except StaleAuthority:416 raise417 except Exception as exc:418 if not self._execution.closed:419 cleanup_after_error(exc, lambda: self._execution.fail('decision commit failed'))420 raise421 finally:422 self._busy = False423424 @property425 def execution(self) -> ExecutionSession:426 """Borrow the financial session for Platform-owned background assembly.427428 The runner retains lifetime ownership. Callers must not close it independently.429 """430 return self._execution431432 def bind_observations(self, factory: Callable[[str], Observation]) -> None:433 """Install the owner-local observation source once, before any work starts."""434 if self._observation_factory is not None or self._boundary or self._busy:435 raise ContractError('bind observations once before policy work')436 self._observation_factory = factory437438 def initial_history(self) -> Tuple[Tuple[MarketTrade, ...], Tuple[NewsRecord, ...]]:439 """Return bounded trade/news values for the background owner's initial view."""440 limit = self.config.history_limit441 return self._market.trades(limit=limit), self._market.news(limit=limit)442443 def record_market_events(self, count: int) -> None:444 """Advance the observation boundary on the sole financial owner."""445 self._boundary += count446447 def observed_market(448 self, trigger: str, trades: Iterable[MarketTrade], news: Iterable[NewsRecord]449 ) -> Observation:450 """Build an observation from owner-maintained history and current finance."""451 return Observation(452 self._boundary,453 trigger,454 self.market_snapshot,455 self.snapshot,456 tuple(trades),457 tuple(news),458 None,459 # Every symbol's book in a run on several symbols; None (and absent) otherwise.460 several_markets(self.market_snapshot),461 )462463 def decision_context(self, trigger: str) -> Tuple[Observation, DecisionJournal]:464 """Check authority/budget and capture the observation and policy-state baseline."""465 self._check_authority(self._maker, self.generation)466 journal = self._app.decision_journal(self._profile, self.run_id)467 if journal['_record_count'] >= self.config.max_decisions:468 self._execution.fail('decision budget exhausted')469 raise ContractError('decision budget exhausted')470 return self.observe(trigger), journal471472 def apply_live_response(473 self, response: PolicyResponse, position: Dict[str, Any]474 ) -> DecisionRecord:475 """Apply a manual Live response at its admitted position through normal decisions."""476 from sim_platform.domain.json_values import copy_json477478 response = copy_json(response)479 if response['state'] is None:480 response['state'] = self._app.decision_journal(self._profile, self.run_id)['state']481 return self._decide('manual', response, position=position)482483 def commit_observation(484 self,485 observation: Observation,486 journal: DecisionJournal,487 response: InvocationResult,488 position: Dict[str, Any],489 ) -> DecisionRecord:490 """Commit a child-produced response against its original observation/state.491492 Financial effects use the admitted command's current market/position; no policy493 is invoked here. The caller is the financial owner, not the Rule child.494 """495 record = dict(496 index=journal['_record_count'] + 1,497 observation=observation.to_json(),498 maker_id=self._maker,499 generation=self.generation,500 fingerprint=fingerprint(observation.to_json()),501 **response,502 )503 result = self._commands.commit(504 self._maker, self.market_snapshot, record, journal, position=position505 )506 if record['status'] != 'ok':507 self._execution.fail('policy ' + record['status'])508 return result509510 def activity_records(self) -> ActivityRecords:511 """Read bounded detached presentation records off the financial owner."""512 run = self._app.run(self._profile, self.run_id, include_records=False)513 return dict(514 run=run,515 events=self._app.run_events(516 self._profile, self.run_id, limit=PRESENTATION_RECORD_LIMIT517 ),518 decisions=self.recent_decisions(PRESENTATION_RECORD_LIMIT),519 handoffs=run['policy_state'].get('handoffs', []),520 )521522 @serialized523 def prepare(self) -> DecisionRequest:524 """Capture a manual request, allowing a delayed adapter response to be checked."""525 if self.config.mode != 'manual' or self._busy:526 raise ContractError('prepare requires an idle manual decision runner')527 self._check_authority(self._maker, self._generation)528 return DecisionRequest(529 self._maker,530 self._generation,531 self.observe('manual'),532 self._app.decision_journal(self._profile, self._run),533 )534535 @serialized536 def respond(self, request: DecisionRequest, response: PolicyResponse) -> DecisionRecord:537 """Commit a response to a prepared request if nothing changed since prepare()."""538 if not isinstance(request, DecisionRequest):539 raise ContractError('expected DecisionRequest')540 self._check_authority(request.maker_id, request.generation)541 if decision_state(request.journal) != decision_state(542 self._app.decision_journal(self._profile, self._run)543 ) or fingerprint(request.observation.to_json()) != fingerprint(544 self.observe('manual').to_json()545 ):546 self._app.handoff(547 'reject',548 self._profile,549 self._run,550 request.maker_id,551 request.generation,552 'stale decision observation',553 )554 raise StaleAuthority('stale decision observation')555 return self._decide('manual', response, request)556557 def _adopt_committed_handoff(558 self, maker: str, policy: Policy, config: DecisionConfig, record: HandoffRecord559 ) -> None:560 """Update local authority only after its persistent transaction succeeds."""561 self._maker, self._policy, self.config = maker, policy, config562 self._generation = record['generation']563 self._execution.adopt_maker(maker)564 self._last_time = None565 self._schedule.reconcile(self._app.decision_journal(self._profile, self._run))566567 @serialized568 def handoff(569 self,570 maker: str,571 policy: Policy,572 config: Optional[DecisionConfig] = None,573 *,574 state_mode: str = 'reset',575 reason: str = 'manual',576 _schedule_id: Optional[int] = None,577 ) -> HandoffRecord:578 """Pass authority to an existing maker now; ``state_mode`` is 'reset' or 'restore'."""579 if self._busy:580 raise ContractError('handoff requires a completed decision boundary')581 self._execution.validate_control()582 config = default_config(policy) if config is None else config583 if not isinstance(config, DecisionConfig):584 raise ContractError('expected DecisionConfig')585 from dataclasses import asdict586587 record = self._app.handoff(588 'switch',589 self._profile,590 self._run,591 self._maker,592 self._generation,593 self.market_snapshot,594 self._boundary,595 maker,596 policy_descriptor(policy),597 asdict(config),598 state_mode,599 reason,600 _schedule_id,601 )602 self._adopt_committed_handoff(maker, policy, config, record)603 return record604605 @serialized606 def managed_handoff(607 self,608 policy: Policy,609 maker: Optional[str] = None,610 *,611 state_mode: str = 'reset',612 condition: Optional[HandoffCondition] = None,613 ) -> str:614 """Create a managed maker and its handoff together, then publish runtime state."""615 if self._busy:616 raise ContractError('handoff requires a completed decision boundary')617 self._check_authority(self._maker, self._generation)618 self._execution.validate_control()619 config = default_config(policy)620 from dataclasses import asdict621622 target, record = self._app.managed_handoff(623 'switch' if condition is None else 'schedule',624 self._profile,625 self._run,626 self._maker,627 self._generation,628 self.market_snapshot,629 self._boundary,630 maker,631 policy_descriptor(policy),632 asdict(config),633 state_mode,634 'manual' if condition is None else condition,635 )636 if condition is not None:637 self._schedule.register(record, target, policy, config, state_mode)638 else:639 self._adopt_committed_handoff(target, policy, config, record)640 return target641642 @serialized643 def schedule_handoff(644 self,645 maker: str,646 policy: Policy,647 condition: HandoffCondition,648 config: Optional[DecisionConfig] = None,649 *,650 state_mode: str = 'reset',651 ) -> SwitchRecord:652 """Persist a switch to ``maker`` that fires automatically when ``condition`` holds."""653 if self._busy:654 raise ContractError('schedule requires a completed decision boundary')655 self._execution.validate_control()656 config = default_config(policy) if config is None else config657 if not isinstance(config, DecisionConfig):658 raise ContractError('expected DecisionConfig')659 from dataclasses import asdict660661 record = self._app.handoff(662 'schedule',663 self._profile,664 self._run,665 self._maker,666 self._generation,667 self.market_snapshot,668 self._boundary,669 maker,670 policy_descriptor(policy),671 asdict(config),672 state_mode,673 condition,674 )675 self._schedule.register(record, maker, policy, config, state_mode)676 return record677678 def _switch_if_due(self) -> None:679 if not self._schedule._policies:680 return681 journal = self._app.decision_journal(self._profile, self._run)682 due = self._schedule.due(journal, lambda: self.snapshot)683 if due is not None:684 switch, (target, policy, config, mode) = due685 self.handoff(686 target,687 policy,688 config,689 state_mode=mode,690 reason=switch['condition']['kind'],691 _schedule_id=switch['id'],692 )693694 @serialized695 def act(self, actions: List[Action], state: Any = None) -> DecisionRecord:696 """Commit manual actions; ``state`` None keeps the current policy state."""697 if self.config.mode != 'manual':698 raise ContractError('manual actions require manual mode')699 if state is None:700 state = self._app.decision_journal(self._profile, self._run)['state']701 return self._decide('manual', {'actions': actions, 'state': state})702703 @serialized704 def decide(self) -> DecisionRecord:705 """Invoke a registered adapter at a manual boundary, including recorded actions."""706 if self.config.mode != 'manual':707 raise ContractError('explicit decisions require manual mode')708 return self._decide('manual')709710 def _advance(self, method: Callable[[], MarketEvent]) -> MarketEvent:711 """Process one market event, fire due switches, then decide if it triggers one."""712 if self._busy:713 raise ContractError('cannot advance during a decision')714 event = method()715 if event.kind in ('market', 'clock', 'news'):716 self._boundary += 1717 try:718 self._switch_if_due()719 except Exception as exc:720 cleanup_after_error(exc, lambda: self._execution.fail('automatic handoff failed'))721 raise722 if (723 not self._replaying724 and self.config.mode == 'automatic'725 and event.kind in self.config.triggers726 and (727 self._last_time is None728 or event.time_ns - self._last_time >= self.config.interval_ns729 )730 and self._policy_due(event.time_ns)731 ):732 self._decide(event.kind)733 return event734735 @serialized736 def step(self) -> MarketEvent:737 return self._advance(self._market_execution.step)738739 @serialized740 def pump(self, count: int = 1) -> Tuple[MarketEvent, ...]:741 """Advance up to ``count`` events; stops early when the run or market stops."""742 if type(count) is not int or count < 1:743 raise ContractError('pump count must be positive')744 events = []745 for _ in range(count):746 if self._execution.closed or self._market.status != 'playing':747 break748 events.append(self._advance(lambda: self._market_execution.pump()[0]))749 return tuple(events)750751 @serialized752 def poll(self, *, max_events: int = 1, budget_seconds: Optional[float] = None) -> None:753 self._playback.poll(self.pump, max_events=max_events, budget_seconds=budget_seconds)754755 @serialized756 def play(self, speed: Optional[float] = None) -> Any:757 if self._busy:758 raise ContractError('cannot play during a decision')759 self._playback.play(speed)760 return self._execution.play()761762 @serialized763 def pause(self) -> Any:764 if self._busy:765 raise ContractError('cannot pause during a decision')766 self._playback.pause()767 return self._execution.pause()768769 @serialized770 def close(self) -> None:771 if self._busy:772 raise ContractError('cannot close during a decision')773 self._execution.close()774775776class DecisionController:777 """Maker/generation-bound public instruction handle.778779 Holds no resources: every call first checks that its captured maker and generation780 still hold authority on the borrowed runner, so a handle stops working after a handoff.781 """782783 def __init__(self, runner: PolicyDecisionRunner, maker: str, generation: int) -> None:784 self._runner, self._maker, self._generation = runner, maker, generation785786 def control_boundary(self) -> ContextManager[None]:787 return self._runner.control_boundary()788789 @serialized790 def act(self, actions: List[Action], state: Any = None) -> DecisionRecord:791 self._runner._check_authority(self._maker, self._generation)792 return self._runner.act(actions, state)793794 @serialized795 def prepare(self) -> DecisionRequest:796 self._runner._check_authority(self._maker, self._generation)797 return self._runner.prepare()798799 @serialized800 def respond(self, request: DecisionRequest, response: PolicyResponse) -> DecisionRecord:801 self._runner._check_authority(self._maker, self._generation)802 return self._runner.respond(request, response)803804 @serialized805 def handoff(806 self, maker: str, policy: Policy, config: Optional[DecisionConfig] = None, **kwargs: Any807 ) -> HandoffRecord:808 self._runner._check_authority(self._maker, self._generation)809 return self._runner.handoff(maker, policy, config, **kwargs)810811 @serialized812 def schedule_handoff(813 self,814 maker: str,815 policy: Policy,816 condition: HandoffCondition,817 config: Optional[DecisionConfig] = None,818 **kwargs: Any,819 ) -> SwitchRecord:820 self._runner._check_authority(self._maker, self._generation)821 return self._runner.schedule_handoff(maker, policy, condition, config, **kwargs)822823 @serialized824 def decide(self) -> DecisionRecord:825 self._runner._check_authority(self._maker, self._generation)826 return self._runner.decide()