Source code for palaestrai.simulation.scripted_simulation_controller

from __future__ import annotations

import asyncio
import copy
import hashlib
import json
import logging
import math
from asyncio import Future
from collections.abc import Mapping
from typing import (
    TYPE_CHECKING,
    Any,
    Dict,
    List,
    Optional,
    Sequence,
    cast,
)

import numpy as np

from palaestrai.core import BasicState, EventStateMachine as ESM
from palaestrai.core.protocol import (
    AgentSetupRequest,
    AgentSetupResponse,
    SimulationStartRequest,
)
from palaestrai.agent.reward_information import RewardInformation
from palaestrai.types import Box, Mode, SimulationFlowControl
from palaestrai.util.dynaloader import load_with_params
from palaestrai.environment.loading import instantiate_environment
from .definition_agent_interface import (
    DefinitionAgentInterface,
    build_definition_agent_interface,
    definition_actions_from_response,
)
from .environment_definition import (
    DeclarativePatch,
    DefinitionProvider,
    ProposedDefinition,
)

from .simulation_controller import SimulationController, FlowControlChange

if TYPE_CHECKING:
    from palaestrai.agent import Agent, ActuatorInformation

LOG = logging.getLogger(__name__)


[docs] class ScriptedSimulationController(SimulationController): """ A concrete SimulationController that executes a declarative ``script`` loaded from ``simulation.params.script`` instead of a hard-coded ``advance`` or ``simulate`` loop. Lifecycle per simulation start request -------------------------------------- 1. ``episode_start()`` — pre-creation boundary turns against the committed (or initial) definition. May stage a declarative patch. Runs once per ``SimulationStartRequest``, before environment creation; in-place episode resets do not rerun it. 2. ``EnvironmentConductor`` creates environments (driven by the base class ``_handle_simulation_start_request`` after ``episode_start`` completes). 3. ``loop()`` — ordered turn groups, worker-local. Required and must be nonempty. 4. ``flow_control()`` — terminal notification (inherited from base). 5. ``episode_end()`` — no-op in v1 (no end-phase mutation; coordinator designation and cohort barrier are v2 concerns). The current version supports one initial scenario change by a meta agent in ``episode_start``, not a repeated meta (learning) loop across episodes. Terminal reward handoff does not schedule another definition decision; repeated scenario adaptation would require additional orchestration. The controller carries a versioned copy of the shared environment definition and stages declarative patches at the episode barrier. Patches are cleared on ``_restart`` or ``flow_control`` and are available via the :attr:`staged_patch` property for consumption by the RunGovernor. Parameters ---------- params : Optional[Dict[str, Any]] Optional controller parameters. When present, ``params["script"]`` supplies the declarative lifecycle policy:: { "episode_start": [{"agents": [...], "environments": [...]}], "loop": [{"agents": [...], "environments": [...]}], "episode_end": [{"agents": [...], "environments": [...]}], } ``environments`` (optional) restricts a group's update to the named environments (environment UID or the routing key that prefixes their sensor and actuator UIDs); the others are not stepped and their simulation time does not advance. Without it, every group steps every active environment. ``rewards_to`` (optional) names agents that receive the group's rewards in addition to the acting agents; this lets a later group, e.g. one that applies a power flow after a mapper agent has acted, deliver the rewards for an earlier group's actions. ``episode_start`` and ``episode_end`` default to ``[]`` if absent. ``loop`` is required and must be nonempty when a script is provided. When ``params`` is absent or empty, or when ``params["script"]`` is absent, the controller behaves as a vanilla single-agent controller (backward-compatible default). """ def __init__( self, agent_conductor_ids: Sequence[str], environment_conductor_ids: Sequence[str], agents: Dict[str, Dict], mode: Mode, termination_conditions: Sequence[Dict[str, Any]], params: Optional[Dict[str, Any]] = None, *args, **kwargs, ): super().__init__( agent_conductor_ids, environment_conductor_ids, agents, mode, termination_conditions, *args, **kwargs, ) self._params = params if params is not None else {} self._script: Optional[Dict[str, Any]] = self._params.get( "script", None ) self._definition_revision: int = 0 self._patch_staged: Optional[DeclarativePatch] = None self._environment_configuration_overrides: Dict[ str, Dict[str, Any] ] = {} self._definition_agent_interfaces: Dict[ str, DefinitionAgentInterface ] = {} self._future_definition_agent_setup: Optional[Future[Any]] = None self._meta_loop_profile: Optional[tuple[str, str]] = None self._meta_loop_reward_values: list[float] = [] # Adapter construction is deliberately performed only when the run # file configures adapters. In particular, importing core PalaestrAI # must not import optional MIDAS packages. # Validate script at construction time so that bad configurations fail # fast — before any worker is spawned or any ESM state machine starts. self._validate_script() # ── setup ───────────────────────────────────────────────────────────────── def setup(self): super().setup() def _validate_script(self) -> None: """ Validate script structure and agent references before simulate() runs. Raises ValueError on any configuration error so that bad configurations fail fast at setup time — before workers are spawned. """ script = self._script if script is None: return # loop is required and must be nonempty loop = script.get("loop") if loop is None: raise ValueError( "ScriptedSimulationController: script.loop is required; " "got None. Provide a nonempty list of turn groups." ) if not isinstance(loop, list): raise TypeError( f"script.loop must be a list of turn groups; " f"got {type(loop).__name__}" ) if not loop: raise ValueError( "ScriptedSimulationController: script.loop must be nonempty; " "got []" ) # episode_start and episode_end default to [] if absent; if present # must be lists for phase in ("episode_start", "episode_end"): if phase in script and not isinstance(script[phase], list): raise TypeError( f"script.{phase} must be a list of turn groups; " f"got {type(script[phase]).__name__}" ) all_agent_names = set(self._agent_configurations.keys()) for configuration in self._agent_configurations.values(): configured_name = configuration.get("name") if isinstance(configured_name, str): all_agent_names.add(configured_name) # Validate each phase's turn groups for phase in ("episode_start", "loop", "episode_end"): groups = script.get(phase, []) for group_idx, group in enumerate(groups): self._validate_turn_group( phase, group_idx, group, all_agent_names ) # A non-empty episode_start selects the definition-driven meta-loop # profile. Empty episode_start scripts retain the original generic # scripted behavior. self._meta_loop_agent_names() def _meta_loop_agent_names(self) -> Optional[tuple[str, str]]: """Return the meta and operating agent names for the strict profile.""" if self._meta_loop_profile is not None: return self._meta_loop_profile start = self._script.get("episode_start", []) if self._script else [] if not start: return None assert self._script is not None loop = self._script["loop"] if len(start) != 1 or len(start[0]["agents"]) != 1: raise ValueError( "meta-loop episode_start requires exactly one turn group with one agent" ) if len(loop) != 1 or len(loop[0]["agents"]) != 1: raise ValueError( "meta-loop loop requires exactly one turn group with one agent" ) if self._script.get("episode_end", []): raise ValueError("meta-loop episode_end is unsupported") names = (start[0]["agents"][0], loop[0]["agents"][0]) if names[0] == names[1]: raise ValueError( "meta-loop meta and operating agents must be distinct" ) self._meta_loop_profile = names return names def _agent_conductor_for_name(self, name: str) -> str: """Resolve a script agent name to its AgentConductor service UID.""" if name in self._agent_configurations: return name for conductor_id, configuration in self._agent_configurations.items(): if configuration.get("name") == name: return conductor_id raise ValueError( f"meta-loop agent {name!r} has no configured conductor" ) def _load_definition_environment( self, configurations: Mapping[str, Mapping[str, Any]] ) -> tuple[str, ProposedDefinition]: """Load the one configured environment that proposes a definition.""" candidates: list[tuple[str, ProposedDefinition]] = [] for uid, configuration in configurations.items(): environment = instantiate_environment( configuration, uid=uid, seed=0 ) proposed = environment.propose_definition() if proposed.interface.sensors or proposed.interface.actuators: candidates.append((uid, proposed)) if len(candidates) != 1: raise ValueError( "meta-loop requires exactly one environment proposing a " f"definition interface; got {[uid for uid, _ in candidates]!r}" ) return candidates[0] def _definition_for_meta_loop( self, configurations: Mapping[str, Mapping[str, Any]] ) -> dict[str, dict[str, Any]]: """Extract copied scenario mappings from the current start request.""" result: dict[str, dict[str, Any]] = {} for uid, entry in configurations.items(): try: params = entry["environment"]["params"] except (KeyError, TypeError) as exc: raise ValueError( f"meta-loop environment {uid!r} has no environment params" ) from exc if not isinstance(params, Mapping): raise TypeError( f"meta-loop environment {uid!r} params must be a mapping" ) provider = cast(Mapping[str, Any], params.get("params", params)) if ( not isinstance(provider, Mapping) or provider.get("scenario_provider") != "inline" ): raise ValueError( f"meta-loop environment {uid!r} must use Inline scenario provider" ) if "scenario" not in provider or not isinstance( provider["scenario"], Mapping ): raise ValueError( f"meta-loop environment {uid!r} requires an inline scenario mapping" ) result[uid] = copy.deepcopy(dict(provider["scenario"])) return result @staticmethod def _mutable_definition(value: Any) -> Any: """Copy a validated value object into mutable adapter input.""" if isinstance(value, Mapping): return { copy.deepcopy( key ): ScriptedSimulationController._mutable_definition(item) for key, item in value.items() } if isinstance(value, list): return [ ScriptedSimulationController._mutable_definition(item) for item in value ] if isinstance(value, tuple): return tuple( ScriptedSimulationController._mutable_definition(item) for item in value ) return copy.deepcopy(value) def _overrides_from_candidate( self, configurations: Mapping[str, Mapping[str, Any]], definition: Mapping[str, Mapping[str, Any]], ) -> Dict[str, Dict[str, Any]]: """Build complete setup entries containing candidate scenario mappings.""" overrides: Dict[str, Dict[str, Any]] = {} for uid, scenario in definition.items(): if uid not in configurations: raise ValueError( f"meta-loop candidate has unknown environment {uid!r}" ) entry = copy.deepcopy(dict(configurations[uid])) try: params = entry["environment"]["params"] except (KeyError, TypeError) as exc: raise ValueError( f"meta-loop environment {uid!r} has no environment params" ) from exc if not isinstance(params, Mapping): raise TypeError( f"meta-loop environment {uid!r} params must be a mapping" ) params = cast(Dict[str, Any], params) provider = params.get("params", params) if not isinstance(provider, Mapping): raise TypeError( f"meta-loop environment {uid!r} provider params must be a mapping" ) provider = dict(provider) if ( not isinstance(provider, Mapping) or provider.get("scenario_provider") != "inline" ): raise ValueError( f"meta-loop environment {uid!r} must use Inline scenario provider" ) if not isinstance(scenario, Mapping): raise TypeError( f"meta-loop candidate environment {uid!r} scenario must be a mapping" ) provider["scenario"] = copy.deepcopy(dict(scenario)) if "params" in params: params["params"] = provider else: params["scenario"] = provider["scenario"] overrides[uid] = entry return overrides def _validate_turn_group( self, phase: str, group_idx: int, group: Dict[str, Any], valid_names: set, ) -> None: if not isinstance(group, dict): raise TypeError( f"script.{phase}[{group_idx}] must be a turn group dict; " f"got {type(group).__name__}" ) if "agents" not in group: raise ValueError( f"script.{phase}[{group_idx}]: missing 'agents' key" ) agents = group["agents"] if not isinstance(agents, list): raise TypeError( f"script.{phase}[{group_idx}].agents must be a list; " f"got {type(agents).__name__}" ) if not agents: raise ValueError( f"script.{phase}[{group_idx}].agents must be nonempty; got []" ) seen: set = set() for name in agents: if not isinstance(name, str): raise TypeError( f"script.{phase}[{group_idx}].agents must contain strings; " f"got {type(name).__name__}" ) if name in seen: raise ValueError( f"script.{phase}[{group_idx}]: duplicate agent name '{name}'" ) seen.add(name) if name not in valid_names: raise ValueError( f"script.{phase}[{group_idx}]: unknown agent '{name}'. " f"Valid agent names: {sorted(valid_names)}" ) # environments key is optional; if present must be a list if "environments" in group: envs = group["environments"] if not isinstance(envs, list): raise TypeError( f"script.{phase}[{group_idx}].environments must be a list; " f"got {type(envs).__name__}" ) if not envs or not all(isinstance(e, str) for e in envs): raise ValueError( f"script.{phase}[{group_idx}].environments must be a " f"nonempty list of environment names; got {envs!r}" ) if "rewards_to" in group: recipients = group["rewards_to"] if not isinstance(recipients, list) or not all( isinstance(r, str) for r in recipients ): raise TypeError( f"script.{phase}[{group_idx}].rewards_to must be a list " f"of agent names; got {recipients!r}" ) for name in recipients: if name not in valid_names: raise ValueError( f"script.{phase}[{group_idx}]: unknown agent " f"'{name}' in rewards_to. " f"Known agents: {sorted(valid_names)}" ) # ── lifecycle hooks ─────────────────────────────────────────────────────── async def episode_start(self) -> None: """ Pre-creation phase: boundary actors execute ordered turn groups against the committed (or initial) definition before any environment is created or reset. Boundary actors may stage a declarative patch via ``_stage_patch()``. The patch is held locally and made available at the episode barrier. """ script = self._script if script is None: return if self._meta_loop_agent_names() is not None: # The constrained profile is driven by _run_definition_meta_turn # at the SimulationStartRequest seam. In particular, do not # route it through the ordinary act -> step implementation. return groups = script.get("episode_start", []) await self._execute_turn_groups(groups, allow_patch=True) @ESM.requests def _request_definition_agent_setup(self, request: AgentSetupRequest): """Send the normal setup request used by the pre-environment agent.""" return request @ESM.on(AgentSetupResponse) def _handle_agent_setup_response(self, response: AgentSetupResponse): """Reapply a definition interface after setup replaces an agent.""" super()._handle_agent_setup_response(response) binding = self._definition_agent_interfaces.get( response.sender_agent_conductor ) if binding is None: return agent = cast("Agent", self._agents[response.sender_agent_conductor]) agent.sensors = list(binding.sensors) agent.actuators = list(binding.actuators) async def _setup_definition_agent( self, agent_name: str, binding: DefinitionAgentInterface ) -> None: """Set up the meta agent through the ordinary AgentConductor path.""" conductor_id = self._agent_conductor_for_name(agent_name) self._definition_agent_interfaces[conductor_id] = binding self._rewards_per_agent.setdefault(agent_name, []) # This also makes the helper convenient for hermetic lifecycle tests, # which provide an already-created mock agent. A real controller has # no entry here until the setup response is handled. if ( self._agents.get(conductor_id) is None and self._agents.get(agent_name) is not None ): self._agents[conductor_id] = self._agents[agent_name] agent = self._agents.get(conductor_id) if agent is not None: agent.sensors = list(binding.sensors) agent.actuators = list(binding.actuators) return self._agents[conductor_id] = None request = AgentSetupRequest( sender_simulation_controller=self.uid, receiver_agent_conductor=conductor_id, experiment_run_id=self._experiment_run_id, experiment_run_instance_id=self._experiment_run_instance_id, experiment_run_phase=self._experiment_run_phase, muscle_name=agent_name, sensors=list(binding.sensors), actuators=list(binding.actuators), configuration=copy.deepcopy( self._agent_configurations[conductor_id] ), static_models={}, mode=self._mode, experiment_run_phase_id=getattr( self, "_experiment_run_phase_id", None ), ) future = asyncio.get_running_loop().create_future() self._future_definition_agent_setup = future _ = self._request_definition_agent_setup(request) await future self._future_definition_agent_setup = None async def _run_definition_meta_turn( self, configurations: Mapping[str, Mapping[str, Any]] ) -> None: """Run the one-shot definition action and prepare setup overrides.""" self._environment_configuration_overrides = {} definition = self._definition_for_meta_loop(configurations) environment_uid, proposed = self._load_definition_environment( configurations ) if proposed.environment != environment_uid: raise ValueError( f"environment {environment_uid!r} proposed definition for " f"{proposed.environment!r}" ) provider = DefinitionProvider(proposed) baseline = provider.validate({proposed.environment: proposed.scenario}) baseline_definition = self._mutable_definition(baseline.definition) interface = provider.describe(baseline_definition) # None deliberately requests the provider's complete declared manifest. vector = provider.vectorize(baseline_definition, None) binding = build_definition_agent_interface(interface, vector) names = self._meta_loop_agent_names() if names is None: raise RuntimeError( "definition meta turn requires a meta-loop profile" ) meta_name, _ = names await self._setup_definition_agent(meta_name, binding) previous_readings = self._current_sensor_readings previous_lookup = self._current_sensor_readings_lookup try: self._current_sensor_readings = list(binding.sensors) self._current_sensor_readings_lookup = { str(item.uid): item for item in binding.sensors } meta_agent = self._agents.get( self._agent_conductor_for_name(meta_name) ) if meta_agent is None: meta_agent = self._agents.get(meta_name) if meta_agent is None: raise RuntimeError("meta-loop agent setup produced no agent") responses = await self.act([meta_agent]) finally: self._current_sensor_readings = previous_readings self._current_sensor_readings_lookup = previous_lookup if len(responses) != 1: raise ValueError( "meta-loop definition action must return one response" ) actions = definition_actions_from_response( responses[0].actuator_information, {item.uid for item in binding.actuators}, ) patch = provider.propose_patch(baseline_definition, actions) candidate = provider.validate(baseline_definition, patch) self._environment_configuration_overrides = ( self._overrides_from_candidate( configurations, self._mutable_definition(candidate.definition) ) ) async def episode_end(self) -> None: """ v1 no-op — no end-phase mutation. The cohort barrier, coordinator designation, and end-phase Deep-RL action are v2 concerns. This method exists as a documented seam. """ pass async def _execute_turn_groups( self, groups: List[Dict[str, Any]], allow_patch: bool = False, ) -> None: """ Execute ordered turn groups in sequence. Each group: 1. resolves logical agent names to resolved ``Agent`` objects 2. calls ``act()`` for the whole group 3. calls ``step()`` with the returned actuator setpoints If ``allow_patch`` is True, any response carrying a ``patch`` attribute stages it at the episode barrier (consumed by the RunGovernor in v2; cleared on reset/flow_control in v1). """ for group in groups: agent_names = group["agents"] # The optional ``environments`` key restricts which environments # step() updates; ``rewards_to`` forwards this group's rewards. # Resolve logical names → Agent objects agents: List[Agent] = [] for name in agent_names: agent = self._agents.get(name) if agent is None: try: agent = self._agents.get( self._agent_conductor_for_name(name) ) except ValueError: pass if agent is None: # Belt-and-suspenders; validation should have caught this LOG.warning( "ScriptedSimulationController: agent '%s' has no " "rollout worker, skipping turn group", name, ) continue agents.append(agent) if not agents: continue # validated, but guard against empty list responses = await self.act(agents) # Each response carries a flat list of ActuatorInformation. # step() expects List[ActuatorInformation] — flatten the per-agent # lists into a single flat list. setpoints: List["ActuatorInformation"] = [] for rsp in responses: setpoints.extend(rsp.actuator_information) step_kwargs: Dict[str, Any] = {} if "environments" in group: step_kwargs["environments"] = group["environments"] try: await self.step(agents, setpoints, **step_kwargs) except FlowControlChange: # step() stores the rewards before it raises, so the terminal # rewards reach the recipients as well. self._forward_group_rewards(group, agents) self._accumulate_meta_loop_step_rewards(agents) raise else: self._forward_group_rewards(group, agents) self._accumulate_meta_loop_step_rewards(agents) # Patch staging — future: only at episode barrier; in v1 cleared # on flow_control / _restart before any reuse if allow_patch: for rsp in responses: patch = getattr(rsp, "patch", None) if patch is not None: self._stage_patch(patch) def _resolve_agent(self, name: str) -> Optional["Agent"]: agent = self._agents.get(name) if agent is None: try: agent = self._agents.get(self._agent_conductor_for_name(name)) except ValueError: agent = None return agent def _forward_group_rewards( self, group: Dict[str, Any], agents: List["Agent"] ) -> None: """Give the rewards stored for ``agents`` to ``group["rewards_to"]``.""" recipients = group.get("rewards_to") or [] if not recipients or not agents: return rewards = self._rewards_per_agent.get(agents[0].uid) if rewards is None: return for name in recipients: agent = self._resolve_agent(name) if agent is None: LOG.warning( "ScriptedSimulationController: rewards_to agent '%s' has " "no rollout worker", name, ) continue self._rewards_per_agent[agent.uid] = rewards @ESM.requests def _dispatch_agent_setup_requests(self, requests): return requests def _try_setup_agents(self): """Set up only the operating agent in the meta-loop profile.""" names = self._meta_loop_agent_names() if names is None: requests = self._setup_agents_for(self._agent_conductor_ids) else: _, operating_name = names operating_id = self._agent_conductor_for_name(operating_name) requests = self._setup_agents_for([operating_id]) # ESM handlers call this from inside the event loop. Returning the # request list directly also keeps this lifecycle seam usable by # synchronous unit tests without manufacturing an ESM event loop. try: asyncio.get_running_loop() except RuntimeError: return requests self._dispatch_agent_setup_requests(requests) return requests def _send_environment_setup_requests(self, overrides=None): """Delegate setup with the candidate produced by the meta turn.""" if overrides is None: overrides = self._environment_configuration_overrides return super()._send_environment_setup_requests(overrides) def _stage_patch( self, patch: DeclarativePatch | Mapping[str, Any] ) -> None: """Stage one validated declarative patch for the episode boundary.""" if self._patch_staged is not None: LOG.warning( "ScriptedSimulationController: a patch is already staged for " "this episode; ignoring additional patch from the same phase" ) return if isinstance(patch, DeclarativePatch): staged = patch elif isinstance(patch, Mapping): # Preserve the V1 response seam while upgrading its internal # representation to the contract value object. content = copy.deepcopy(dict(patch)) staged = DeclarativePatch( content=content, content_hash=hashlib.sha256( json.dumps( content, sort_keys=True, separators=(",", ":") ).encode() ).hexdigest(), revision=self._definition_revision, ) else: raise TypeError("staged patch must be a DeclarativePatch") if staged.revision != self._definition_revision: raise ValueError( "staged patch revision does not match the controller revision" ) self._patch_staged = staged # ── simulate ───────────────────────────────────────────────────────────── async def simulate(self) -> None: """ Execute the scripted episode. Run order (per episode): 1. loop — ordered turn groups until FlowControlChange 2. episode_end() — no-op in v1 3. flow_control() — notify the RunGovernor of the terminal flow The episode_start() pre-creation phase runs via the extended _handle_simulation_start_request ESM handler BEFORE simulate() is even called. This ensures boundary actors act on the committed definition before any environment world exists. Raises FlowControlChange to abort the loop on termination. """ script = self._script # 1. loop (required and nonempty when script is present) if script is not None: loop_groups = script.get("loop", []) else: # Backward-compatible default: single-agent loop equivalent to # VanillaSimController loop_groups = [] if loop_groups: while self.is_running: try: await self._execute_turn_groups(loop_groups) except FlowControlChange: self._state = BasicState.STOPPING LOG.debug( "ScriptedSimulationController: FlowControlChange " "during loop, stopping" ) break # 2. episode_end no-op in v1 if script is not None: await self.episode_end() # Match the base controller lifecycle: once the scripted simulation # task has completed, notify the RunGovernor of the terminal flow so it # can advance its phase and shut down the child processes. await self.flow_control() # ── ESM handlers ───────────────────────────────────────────────────────── @ESM.on(SimulationStartRequest) async def _handle_simulation_start_request( self, request: SimulationStartRequest ): """ Extended handler: run ``episode_start`` pre-creation phase before any environment is set up, then delegate to the base handler for normal environment/agent setup and simulate() start. The base ``_handle_simulation_start_request`` sends ``EnvironmentSetupRequest`` and waits for ``_future_init`` before calling ``_start_simulation_task``, which seeds sensors and starts ``self.simulate()``. By running ``episode_start`` first we ensure boundary actors act against the committed definition before any environment world exists. The ESM dispatches by method name; the ``@ESM.on`` decorator on the base class registers the handler. Overriding this method by name without a decorator replaces the base handler while still allowing super() delegation. """ # Pre-creation boundary turns BEFORE environment setup. # This matches the episode_start pre-creation phase design: boundary # actors act on the committed definition, may stage patches, and only # after this completes does the conductor create/reset environments. if self._meta_loop_agent_names() is None: await self.episode_start() else: # The base handler normally copies this request context before # sending any agent requests. The meta turn runs before # delegating to it, so seed the same fields for its request. self._run_governor_uid = request.sender_run_governor_id self._experiment_run_id = request.experiment_run_id self._experiment_run_instance_id = ( request.experiment_run_instance_id ) self._experiment_run_phase = request.experiment_run_phase self._experiment_run_phase_id = request.experiment_run_phase_id self._episode = request.episode await self._run_definition_meta_turn( getattr(request, "environment_configurations", {}) ) # Now delegate to base for normal setup → environments → simulate() return await super()._handle_simulation_start_request(request) # ── reset / shutdown ───────────────────────────────────────────────────── async def _restart(self) -> None: """ Clear staged patch and delegate to base for in-place reset. v1 uses in-place reset with reseeding. Recreation (``create_new_instance=True``) is a separate follow-on ticket. """ self._patch_staged = None self._environment_configuration_overrides = {} self._meta_loop_reward_values.clear() names = self._meta_loop_agent_names() if names is not None: meta_name, _ = names meta_id = self._agent_conductor_for_name(meta_name) meta_agent = self._agents.get(meta_id) or self._agents.get( meta_name ) meta_uid = meta_agent.uid if meta_agent is not None else meta_name self._rewards_per_agent.pop(meta_uid, None) self._rewards_per_agent.pop(meta_name, None) await super()._restart() async def flow_control(self) -> None: """ Clear any residual staged patch at the episode barrier, then delegate to the base terminal notification flow. """ self._patch_staged = None if self._flow_control_indicator != SimulationFlowControl.CONTINUE: self._set_meta_loop_terminal_reward() await super().flow_control() def _accumulate_meta_loop_step_rewards(self, agents: List[Agent]) -> None: """Accumulate finite scalar environment rewards for the meta-loop.""" names = self._meta_loop_agent_names() if names is None: return _, operating_name = names operating_id = self._agent_conductor_for_name(operating_name) configured_operating_agent = self._agents.get(operating_id) operating_agent = next( ( agent for agent in agents if agent is configured_operating_agent or agent.uid == operating_name ), None, ) if operating_agent is None: return values = [] for reward in self._rewards_per_agent.get(operating_agent.uid, []): values.append(self._coerce_meta_loop_reward_value(reward.value)) self._meta_loop_reward_values.extend(values) @staticmethod def _coerce_meta_loop_reward_value(value: Any) -> float: """Convert one reward to a finite Python scalar or reject it.""" try: array = np.asarray(value) except (TypeError, ValueError) as exc: raise ValueError( "meta-loop rewards must be scalar numeric values" ) from exc if array.ndim != 0: raise ValueError("meta-loop rewards must be scalar numeric values") scalar = array.item() if isinstance(scalar, (str, bytes, bool)) or np.iscomplexobj(scalar): raise ValueError("meta-loop rewards must be real numeric values") try: converted = float(scalar) except (TypeError, ValueError, OverflowError) as exc: raise ValueError( "meta-loop rewards must be real numeric values" ) from exc if not math.isfinite(converted): raise ValueError("meta-loop rewards must be finite") return converted def _set_meta_loop_terminal_reward(self) -> None: """Expose the episode return to the meta agent's terminal update.""" names = self._meta_loop_agent_names() if names is None: return meta_name, operating_agent = names meta_id = self._agent_conductor_for_name(meta_name) meta_agent = self._agents.get(meta_id) or self._agents.get(meta_name) meta_agent_uid = ( meta_agent.uid if meta_agent is not None else meta_name ) self._rewards_per_agent[meta_agent_uid] = [ RewardInformation( value=math.fsum(self._meta_loop_reward_values), space=Box(low=-math.inf, high=math.inf, shape=()), uid=operating_agent + ".return", ) ] # ── patch / revision public interface ─────────────────────────────────── @property def staged_patch(self) -> Optional[DeclarativePatch]: """ Return the currently staged patch and clear it. Called at the episode barrier by the RunGovernor (v2). In v1 the patch is cleared on ``flow_control`` or ``_restart`` before any reuse. Returns None if no patch is staged. """ patch = self._patch_staged self._patch_staged = None return patch @property def definition_revision(self) -> int: """Monotonically increasing definition revision for this controller.""" return self._definition_revision def apply_definition_revision(self, revision: int) -> None: """Record a caller-supplied committed revision at a boundary. The controller does not allocate revisions or own the committed definition. ``RunGovernor`` (or another coordinating caller) supplies the monotonic value after validating and committing its candidate. """ if ( isinstance(revision, bool) or not isinstance(revision, int) or revision < 0 ): raise ValueError( "definition revision must be a non-negative integer" ) if revision < self._definition_revision: raise ValueError( f"definition revision {revision} is older than current revision " f"{self._definition_revision}" ) self._definition_revision = revision