agent_runs.py
1"""Atomic prepared-account check and execution run creation, within caller UOW."""23from __future__ import annotations45from dataclasses import asdict6from typing import TYPE_CHECKING, Any, Dict, Optional78from sim_platform.domain.json_values import copy_json9from sim_platform.domain.models import ContractError1011if TYPE_CHECKING: # Annotation only.12 from sim_platform.execution import ExecutionConfig13 from .accounts import AccountService14 from .agents import AgentService15 from .runs import RunService1617# The unit of work's persistence Repositories; use cases may not import persistence.18Repositories = Any1920# A created Agent run: 'maker_id', 'run_id', 'experiment_id' and 'config' (Agent config).21AgentRunBinding = Dict[str, Any]222324class AgentRunService:25 """Agent run creation and setup-failure cleanup inside the caller's unit of work."""2627 def __init__(28 self,29 repositories: Repositories,30 accounts: AccountService,31 runs: RunService,32 agents: AgentService,33 ) -> None:34 self.repo, self.accounts, self.runs = repositories, accounts, runs35 self.agents = agents3637 def cancel_unbound_agent_run(self, profile_id: str, run_id: str) -> bool:38 """End failed setup with no execution history; never bypass a financial owner."""39 run = self.runs.owned_run(profile_id, run_id)40 if not run.config.get('agent_experiment_id'):41 raise ContractError('not an agent run')42 if self.repo.events.has_run(run_id):43 return False44 run.require_active()45 self.runs.record_run_event(46 run,47 run_id + ':end',48 0,49 'execution_end',50 dict(reason='agent setup failed before execution binding', status='stopped'),51 )52 self.runs.finish_run(profile_id, run_id, 'stopped')53 return True5455 def create_agent_run(56 self, profile_id: str, experiment_id: str, source: Dict[str, Any]57 ) -> AgentRunBinding:58 """Create the run for a prepared experiment once its source and account still match."""59 from sim_platform.domain.experiment import validate_execution_mode6061 validate_execution_mode(source.get("execution_mode"))62 experiment = self.repo.agent_experiments.owned(experiment_id, profile_id)63 config = copy_json(experiment.config)64 if (65 source['symbol'] != config['symbol']66 or source['source_manifest_ref'] != config['source_manifest_ref']67 or source.get('experiment_start_ns', source['start_origin']['time_ns'])68 != int(config['start_ns'])69 ):70 raise ContractError('prepared source binding differs from the experiment')71 current = copy_json(asdict(self.accounts.snapshot(profile_id, experiment.account_id)))72 if current != experiment.initial_snapshot:73 raise ContractError(74 'account changed since experiment preparation; prepare a new experiment'75 )76 from sim_platform.agents.configuration import run_universe7778 universe = run_universe(config)79 if any(p['symbol'] not in universe for p in current['positions']):80 raise ContractError('agent experiments require positions in the selected symbols')81 descriptor = dict(82 name=config['definition']['name'], kind='agent', version=str(experiment.revision)83 )84 settings = dict(85 execution=copy_json(experiment.execution_config),86 research_source=copy_json(source),87 agent_experiment_id=experiment.id,88 agent=copy_json(config),89 )90 maker, run = self.runs.create_managed_run(91 profile_id,92 experiment.account_id,93 descriptor,94 config['symbol'] if len(universe) == 1 else universe,95 settings,96 )97 bound = copy_json(self.repo.runs.get(run).config)98 bound['agent']['run_id'] = run99 self.repo.runs.save_config(run, bound)100 return dict(maker_id=maker, run_id=run, experiment_id=experiment.id, config=bound['agent'])101102 def create_agent_experiment_run(103 self,104 profile: str,105 account: str,106 agent_id: str,107 revision: int,108 settings: Dict[str, Any],109 source: Dict[str, Any],110 execution_config: Optional[ExecutionConfig] = None,111 ) -> AgentRunBinding:112 """Save configuration and create its run together in the caller's single UOW."""113 experiment = self.agents.prepare_agent_experiment(114 profile, account, agent_id, revision, settings, execution_config115 )116 return self.create_agent_run(profile, experiment['id'], source)