service.py
1"""Commit decision audit, policy state, and resulting OMS actions atomically."""23from __future__ import annotations45from dataclasses import asdict6from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union78from sim_platform.domain.models import ContractError, Intent, MarketOrder9from sim_platform.domain.json_values import copy_json10from sim_platform.market.models import book_for1112if TYPE_CHECKING: # Annotation only: these modules are imported lazily at runtime.13 from sim_platform.decisions.policy.models import Action, DecisionJournal, DecisionRecord14 from sim_platform.decisions.policy.models import PolicyDescriptor15 from sim_platform.domain.models import OrderSnapshot16 from sim_platform.execution.models import ExecutionSnapshot, OrderResult17 from sim_platform.execution.service import ExecutionService18 from sim_platform.market.models import MarketSnapshot1920 # The result of one submit (OrderResult) or cancel (OrderSnapshot) action.21 ActionResult = Union[OrderResult, OrderSnapshot]222324def execute_action(25 service: ExecutionService,26 profile: str,27 run_id: str,28 maker: str,29 market: MarketSnapshot,30 action: Action,31 *,32 position: Optional[Dict[str, Any]] = None,33) -> ActionResult:34 """Shared OMS action dispatch for policy decisions and positioned agent tools."""35 if action['kind'] == 'submit':36 intent = Intent(**action['intent'])37 return service.submit(38 profile,39 run_id,40 maker,41 intent,42 book_for(market, intent.symbol),43 operation_position=position,44 )45 if action['kind'] == 'submit_market':46 market_order = MarketOrder(**action['order'])47 return service.submit_market(48 profile,49 run_id,50 maker,51 market_order,52 book_for(market, market_order.symbol),53 operation_position=position,54 )55 if action['kind'] != 'cancel':56 raise ContractError('unsupported decision action')57 if 'order_id' in action:58 order_id = action['order_id']59 else:60 account = service.snapshot(profile, run_id).account61 intent_id = f"{run_id}:intent:{action['client_id']}"62 order = next(63 (o for o in account.orders if o.run_id == run_id and o.intent_id == intent_id), None64 )65 if order is None:66 raise ContractError('unknown cancellation client ID')67 order_id = order.order_id68 return service.cancel(profile, run_id, maker, order_id, market, operation_position=position)697071def commit(72 service: ExecutionService,73 profile: str,74 run_id: str,75 maker: str,76 market: MarketSnapshot,77 record: Optional[DecisionRecord] = None,78 expected_state: Optional[DecisionJournal] = None,79 *,80 action: Optional[Action] = None,81 position: Optional[Dict[str, Any]] = None,82) -> Union[DecisionRecord, Tuple[ActionResult, ExecutionSnapshot]]:83 """One submission path; policy audit and tool JSON keep their own contracts.8485 Policy calls supply record/journal; tools supply one positioned action.86 Neither form can silently omit its required context or mix the two forms.87 Both execute through execute_action in the caller's financial UOW.88 A tool call returns (action result, account snapshot); a policy call returns89 the committed audit record.90 """91 if action is not None:92 if record is not None or expected_state is not None or position is None:93 raise ContractError('tool submission requires only action and position')94 result = execute_action(service, profile, run_id, maker, market, action, position=position)95 return result, service.snapshot(profile, run_id)96 if record is None or expected_state is None:97 raise ContractError('policy submission requires record and journal')98 context = service.context(profile, run_id)99 run = context.run100 last = context.state101 from sim_platform.decisions.policy.handoffs import StaleAuthority, decision_state102103 run.require_active()104 if maker != run.maker_id or record.get('generation', 0) != run.policy_state.get(105 'generation', 0106 ):107 raise StaleAuthority('stale authority generation')108 service.synchronized(run, last, market)109 if decision_state(run.policy_state) != decision_state(expected_state):110 raise ContractError('decision state changed during invocation')111 state = copy_json(run.policy_state)112 if record['index'] != state['_record_count'] + 1:113 raise ContractError('decision audit index mismatch')114 results: List[Dict[str, Any]] = []115 if record['status'] == 'ok':116 for action in record['response']['actions']:117 try:118 results.append(119 asdict(120 execute_action(121 service,122 profile,123 run_id,124 maker,125 market,126 action,127 **({'position': position} if position is not None else {}),128 )129 )130 )131 except ContractError as exc:132 results.append({'status': 'rejected', 'reason': str(exc)})133 state['state'] = record['response']['state']134 committed: DecisionRecord = copy_json(record)135 if position is not None:136 committed['operation_position'] = copy_json(position)137 committed['results'] = results138 if service.runtime_state is not None:139 # Aliased so the import does not rebind this function's ``position`` parameter.140 from sim_platform.execution.position import position as frontier_position141142 committed['position'] = frontier_position(service.runtime_state)143 service.repo.runs.append_record(run_id, committed)144 state['_record_count'] += 1145 service.repo.runs.save_policy_state(run_id, state)146 return committed147148149def managed_handoff(150 service: ExecutionService,151 method: str,152 profile: str,153 run_id: str,154 maker: str,155 generation: int,156 market: MarketSnapshot,157 boundary: int,158 target: Optional[str],159 descriptor: PolicyDescriptor,160 config: Dict[str, Any],161 state_mode: str,162 argument: Any,163) -> Tuple[str, Dict[str, Any]]:164 """Create the target maker if needed, then run handoffs.<method> in the same UOW.165166 ``method`` is 'switch' (``argument`` is the reason) or 'schedule' (``argument`` is167 the condition). Returns the target maker and the handoff or switch record.168 """169 from sim_platform.decisions.policy import handoffs170171 service.accounts.owned_run(profile, run_id).require_authority(maker)172 if target is None:173 target = service.accounts.makers.create_maker(174 profile, descriptor['name'], descriptor['kind'], descriptor['version']175 )176 record = getattr(handoffs, method)(177 service,178 profile,179 run_id,180 maker,181 generation,182 market,183 boundary,184 target,185 descriptor,186 config,187 state_mode,188 argument,189 )190 return target, record191192193def initialize_decisions(service: ExecutionService, profile: str, run_id: str, maker: str) -> None:194 """Create an empty decision journal; refuses a run that already has one."""195 run = service.accounts.owned_run(profile, run_id)196 run.require_authority(maker)197 if run.policy_state:198 raise ContractError('decision journal already exists')199 service.repo.runs.save_policy_state(run_id, {'state': {}, '_record_count': 0})