"""Evaluator bridge for declarative simulator-oracle patch programs. The patch program is task-independent. A task adapter supplies only typed, batched oracle signals; it does not choose a failure category, candidate, or promotion outcome. This keeps environment plumbing separate from the open category/program search. """ from __future__ import annotations from collections.abc import Mapping import copy import math import re from typing import Any, Protocol, runtime_checkable import torch from .program import CompiledPatchProgram, PatchProgramError, compile_patch_program class OracleProgramRuntimeError(RuntimeError): """Raised when an adapter or declarative program violates its contract.""" @runtime_checkable class OracleSignalProvider(Protocol): """Minimal task-adapter surface required by the generic runtime.""" @property def signal_specs(self) -> Mapping[str, Mapping[str, Any]]: ... @property def action_space(self) -> Mapping[str, Any]: ... @property def maximum_action_delta(self) -> tuple[float, ...]: ... @property def component_norms(self) -> tuple[Mapping[str, Any], ...]: ... @property def semantics_digest(self) -> str: ... @property def provenance(self) -> Mapping[str, Any]: ... def bind_environment(self, env: Any) -> None: ... def reset(self, batch_size: int) -> None: ... def observe( self, *, proposed_policy_action: torch.Tensor, robot_qpos: torch.Tensor | None, robot_qvel: torch.Tensor | None, step: int, ) -> Mapping[str, torch.Tensor]: ... class _OracleEstimatorSentinel: """Compatibility marker: this edition never instantiates an estimator.""" requires_policy_depth = False direct_candidate_only = True class SimOracleProgramPatcher: """Run one compiled finite program over a vectorized simulator batch.""" estimator = _OracleEstimatorSentinel() def __init__( self, program: CompiledPatchProgram | Mapping[str, Any], signal_provider: OracleSignalProvider, ) -> None: if not isinstance(signal_provider, OracleSignalProvider): raise OracleProgramRuntimeError( "signal_provider does not implement OracleSignalProvider" ) try: # Always create a fresh immutable compilation bound to the exact # live adapter. Never retain caller-owned compiled mappings. self.program = compile_patch_program( ( program.to_document() if isinstance(program, CompiledPatchProgram) else program ), adapter_signal_specs=signal_provider.signal_specs, ) except PatchProgramError as exc: raise OracleProgramRuntimeError(str(exc)) from exc expected_action_space = self.program.action_space.to_document() if dict(signal_provider.action_space) != expected_action_space: raise OracleProgramRuntimeError( "program action space does not match the live task adapter" ) maximum_action_delta = tuple(signal_provider.maximum_action_delta) if ( len(maximum_action_delta) != self.program.action_space.dimension or any( isinstance(value, bool) or not isinstance(value, (int, float)) for value in maximum_action_delta ) or any( not math.isfinite(float(value)) or float(value) < 0.0 for value in maximum_action_delta ) or any( candidate > allowed for candidate, allowed in zip( self.program.limits.max_action_delta, maximum_action_delta ) ) ): raise OracleProgramRuntimeError( "program action-delta authority exceeds the live task adapter" ) authored_from = self.program.to_document().get("authored_from") if ( not isinstance(authored_from, Mapping) or authored_from.get("semantics_digest") != signal_provider.semantics_digest ): raise OracleProgramRuntimeError( "program semantics identity does not match the live task adapter" ) self._component_norms = tuple( copy.deepcopy(dict(item)) for item in signal_provider.component_norms ) for item in self._component_norms: if set(item) != {"id", "indices", "maximum"}: raise OracleProgramRuntimeError("live component norm schema is invalid") indices = item["indices"] maximum = item["maximum"] if ( not isinstance(indices, (list, tuple)) or not indices or tuple(sorted(indices)) != tuple(indices) or len(set(indices)) != len(indices) or any( isinstance(index, bool) or not isinstance(index, int) or index < 0 or index >= self.program.action_space.dimension for index in indices ) or isinstance(maximum, bool) or not isinstance(maximum, (int, float)) or not math.isfinite(float(maximum)) or maximum <= 0 or not isinstance(item["id"], str) or re.fullmatch(r"[A-Za-z][A-Za-z0-9_.-]{0,127}", item["id"]) is None ): raise OracleProgramRuntimeError("live component norm schema is invalid") self.signal_provider = signal_provider self._batch_size: int | None = None self._runtimes: list[Any] = [] self._trace: list[dict[str, torch.Tensor]] = [] self._phase_indices = { name: index for index, name in enumerate(self.program.phases) } @property def provenance(self) -> dict[str, Any]: return { "schema_version": "sim_oracle_program_runtime.v1", "runtime": "simulator_oracle", "sim_only": True, "deployment_eligible": False, "metric_estimators_used": False, "arbitrary_authored_code": False, "program_id": self.program.id, "program_sha256": self.program.sha256, "program": self.program.to_document(), "signal_provider": dict(self.signal_provider.provenance), } def bind_environment(self, env: Any) -> None: self.signal_provider.bind_environment(env) def reset(self, batch_size: int) -> None: if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size < 1: raise OracleProgramRuntimeError("batch_size must be a positive integer") self._batch_size = None self._runtimes = [] self._trace = [] self.signal_provider.reset(batch_size) runtimes = [self.program.start_episode() for _ in range(batch_size)] self._batch_size = batch_size self._runtimes = runtimes def _normalize_signals( self, signals: Mapping[str, torch.Tensor], *, batch_size: int, ) -> dict[str, torch.Tensor]: if not isinstance(signals, Mapping): raise OracleProgramRuntimeError("signal provider returned a non-mapping") result: dict[str, torch.Tensor] = {} for name, spec in self.program.signals.items(): value = signals.get(name) if not isinstance(value, torch.Tensor): raise OracleProgramRuntimeError( f"signal provider did not return tensor {name!r}" ) expected = (batch_size,) if spec.width == 1 else (batch_size, spec.width) if tuple(value.shape) != expected: raise OracleProgramRuntimeError( f"signal {name!r} has shape {tuple(value.shape)}, expected {expected}" ) if spec.value_type == "boolean": if value.dtype != torch.bool: raise OracleProgramRuntimeError( f"signal {name!r} must have Boolean dtype" ) elif not value.dtype.is_floating_point or not torch.isfinite(value).all(): raise OracleProgramRuntimeError( f"signal {name!r} must have finite floating dtype" ) result[name] = value return result def apply( self, *, proposed_policy_action: torch.Tensor, robot_qpos: torch.Tensor | None = None, robot_qvel: torch.Tensor | None = None, step: int, **_: Any, ) -> torch.Tensor: if self._batch_size is None or len(self._runtimes) != self._batch_size: raise OracleProgramRuntimeError("program patcher must be reset before apply") if ( proposed_policy_action.ndim != 2 or proposed_policy_action.shape[0] != self._batch_size or proposed_policy_action.shape[1] != self.program.action_space.dimension or not proposed_policy_action.dtype.is_floating_point or not torch.isfinite(proposed_policy_action).all() ): raise OracleProgramRuntimeError( "proposed action does not match the compiled action space" ) observed = self.signal_provider.observe( proposed_policy_action=proposed_policy_action, robot_qpos=robot_qpos, robot_qvel=robot_qvel, step=step, ) signals = self._normalize_signals(observed, batch_size=self._batch_size) policy_cpu = proposed_policy_action.detach().cpu().numpy() signal_cpu = { name: value.detach().cpu().numpy() for name, value in signals.items() } results = [] try: for row_index, runtime in enumerate(self._runtimes): row_signals = { name: value[row_index] for name, value in signal_cpu.items() } results.append( runtime.step( policy_cpu[row_index], row_signals, step_index=step, ) ) except PatchProgramError as exc: raise OracleProgramRuntimeError(str(exc)) from exc executed = torch.as_tensor( [result.action.tolist() for result in results], device=proposed_policy_action.device, dtype=proposed_policy_action.dtype, ) additive_selected = torch.as_tensor( [result.trace["additive_selected"] for result in results], device=executed.device, dtype=torch.bool, ) replacement_selected = torch.as_tensor( [result.trace["replacement_selected"] for result in results], device=executed.device, dtype=torch.bool, ) replacement_owned = torch.as_tensor( [result.trace["replacement_owned"] for result in results], device=executed.device, dtype=torch.bool, ) if torch.any(replacement_owned & ~replacement_selected): raise OracleProgramRuntimeError( "program trace owns a replacement without selecting one" ) canonical_lower = torch.as_tensor( self.program.action_space.lower, device=executed.device, dtype=torch.float64, ) canonical_upper = torch.as_tensor( self.program.action_space.upper, device=executed.device, dtype=torch.float64, ) canonical_max_delta = torch.as_tensor( self.program.limits.max_action_delta, device=executed.device, dtype=torch.float64, ) replacement_anchor = ( (canonical_lower + canonical_upper) * 0.5 ).to(dtype=executed.dtype) requested_coordinates = additive_selected | replacement_selected additive_owned = additive_selected & ~replacement_owned def authority_values(current: torch.Tensor) -> torch.Tensor: delta = current.to(dtype=torch.float64) - proposed_policy_action.to( dtype=torch.float64 ) return torch.where( replacement_owned, current.to(dtype=torch.float64), torch.where(additive_owned, delta, torch.zeros_like(delta)), ) # The scalar interpreter computes in float64. Casting either an # additive delta or an explicit replacement endpoint back to float32 # can round one ULP outside the canonical authority interval. Move # only patch-owned coordinates inward. Additive edits move toward the # incumbent action; replacements move toward the envelope midpoint. for _ in range(8): executed_canonical = executed.to(dtype=torch.float64) proposed_canonical = proposed_policy_action.to(dtype=torch.float64) authority = authority_values(executed) value_excess = requested_coordinates & ( (authority < canonical_lower) | (authority > canonical_upper) ) delta_excess = additive_owned & ( torch.abs(executed_canonical - proposed_canonical) > canonical_max_delta ) rounded_excess = value_excess | delta_excess if not torch.any(rounded_excess): break target = torch.where( replacement_owned & value_excess, replacement_anchor.expand_as(executed), proposed_policy_action, ) executed = torch.where( rounded_excess, torch.nextafter(executed, target), executed, ) executed_canonical = executed.to(dtype=torch.float64) proposed_canonical = proposed_policy_action.to(dtype=torch.float64) authority = authority_values(executed) rounded_excess = requested_coordinates & ( (authority < canonical_lower) | (authority > canonical_upper) | ( additive_owned & ( torch.abs(executed_canonical - proposed_canonical) > canonical_max_delta ) ) ) executed = torch.where( rounded_excess, proposed_policy_action, executed, ) conversion_authority_clipped = torch.any(rounded_excess, dim=1) # A failed conversion hands that coordinate back to the policy. A # numerically unchanged but otherwise legal replacement retains # ownership and remains part of its absolute component envelope. replacement_owned &= ~rounded_excess modified_coordinates = ( executed != proposed_policy_action ) & requested_coordinates additive_owned &= modified_coordinates authority_coordinates = replacement_owned | additive_owned executed_canonical = executed.to(dtype=torch.float64) proposed_canonical = proposed_policy_action.to(dtype=torch.float64) authority = authority_values(executed) if ( not torch.isfinite(executed).all() or torch.any(authority_coordinates & (authority < canonical_lower)) or torch.any(authority_coordinates & (authority > canonical_upper)) or torch.any( additive_owned & ( torch.abs(executed_canonical - proposed_canonical) > canonical_max_delta ) ) ): raise OracleProgramRuntimeError( "executed action is invalid after conversion to the live action dtype" ) component_authority_clipped = torch.zeros( executed.shape[0], device=executed.device, dtype=torch.bool ) for item in self._component_norms: indices = torch.as_tensor(item["indices"], device=executed.device) component_active = torch.any( authority_coordinates.index_select(1, indices), dim=1 ) # As with scalar endpoints, a vector exactly on a canonical norm # boundary can round one ULP outward in the live dtype. Normalize # representational excess inward along program-owned coordinates. for _ in range(8): authority = authority_values(executed) norm_excess = component_active & ( torch.linalg.vector_norm( authority.index_select(1, indices), dim=1, ) > float(item["maximum"]) ) if not torch.any(norm_excess): break current = executed.index_select(1, indices) baseline = proposed_policy_action.index_select(1, indices) owned = authority_coordinates.index_select(1, indices) # Representation normalization may refine a real patch edit, # but it must never turn a selected numerical no-op into a new # intervention merely to shrink an absolute component vector. modifiable = modified_coordinates.index_select(1, indices) replacement = replacement_owned.index_select(1, indices) inward_target = torch.where( replacement, replacement_anchor.index_select(0, indices).expand_as(current), baseline, ) inward = torch.nextafter(current, inward_target) inward_canonical = inward.to(dtype=torch.float64) baseline_canonical = baseline.to(dtype=torch.float64) inward_authority = torch.where( replacement, inward_canonical, inward_canonical - baseline_canonical, ) scalar_conformant = (~owned) | ( ( inward_authority >= canonical_lower.index_select(0, indices) ) & ( inward_authority <= canonical_upper.index_select(0, indices) ) & ( replacement | ( torch.abs(inward_canonical - baseline_canonical) <= canonical_max_delta.index_select(0, indices) ) ) ) current = torch.where( norm_excess[:, None] & modifiable & scalar_conformant, inward, current, ) executed[:, indices] = current modified_coordinates = ( executed != proposed_policy_action ) & requested_coordinates additive_owned = ( additive_selected & ~replacement_owned & modified_coordinates ) authority_coordinates = replacement_owned | additive_owned component_active = torch.any( authority_coordinates.index_select(1, indices), dim=1 ) # Component envelopes may overlap. Abandoning a material edit in a # later component can restore an out-of-envelope baseline coordinate # and thereby invalidate a component checked earlier. Resolve that # dependency to a fixed point. Every nonterminal pass removes at # least one program-owned coordinate, so the action dimension is a # strict deterministic convergence bound. for _ in range(self.program.action_space.dimension): modified_coordinates = ( executed != proposed_policy_action ) & requested_coordinates additive_owned = ( additive_selected & ~replacement_owned & modified_coordinates ) authority_coordinates = replacement_owned | additive_owned authority = authority_values(executed) abandon_coordinates = torch.zeros_like(authority_coordinates) violating_rows = torch.zeros( executed.shape[0], device=executed.device, dtype=torch.bool ) for item in self._component_norms: indices = torch.as_tensor(item["indices"], device=executed.device) owned = authority_coordinates.index_select(1, indices) norm_excess = torch.any(owned, dim=1) & ( torch.linalg.vector_norm( authority.index_select(1, indices), dim=1, ) > float(item["maximum"]) ) if torch.any(norm_excess): violating_rows |= norm_excess abandon_coordinates[:, indices] |= norm_excess[:, None] & owned if not torch.any(violating_rows): break before = int(authority_coordinates.sum().item()) executed = torch.where( abandon_coordinates, proposed_policy_action, executed, ) replacement_owned &= ~abandon_coordinates component_authority_clipped |= violating_rows modified_after = ( executed != proposed_policy_action ) & requested_coordinates additive_after = ( additive_selected & ~replacement_owned & modified_after ) after = int((replacement_owned | additive_after).sum().item()) if after >= before: raise OracleProgramRuntimeError( "component-norm fixed point made no conservative progress" ) modified_coordinates = ( executed != proposed_policy_action ) & requested_coordinates additive_owned = additive_selected & ~replacement_owned & modified_coordinates authority_coordinates = replacement_owned | additive_owned executed_canonical = executed.to(dtype=torch.float64) proposed_canonical = proposed_policy_action.to(dtype=torch.float64) authority = authority_values(executed) if ( torch.any(authority_coordinates & (authority < canonical_lower)) or torch.any(authority_coordinates & (authority > canonical_upper)) or torch.any( additive_owned & ( torch.abs(executed_canonical - proposed_canonical) > canonical_max_delta ) ) ): raise OracleProgramRuntimeError( "component normalization violated canonical scalar authority" ) for item in self._component_norms: indices = torch.as_tensor(item["indices"], device=executed.device) remaining_excess = torch.any( authority_coordinates.index_select(1, indices), dim=1 ) & ( torch.linalg.vector_norm( authority.index_select(1, indices), dim=1, ) > float(item["maximum"]) ) if torch.any(remaining_excess): raise OracleProgramRuntimeError( f"executed action violates live component norm {item['id']!r}" ) modified = torch.any(executed != proposed_policy_action, dim=1) scalar_modified = torch.as_tensor( [bool(result.intervened) for result in results], device=executed.device, dtype=torch.bool, ) if torch.any(modified & ~scalar_modified): raise OracleProgramRuntimeError( "live authority normalization created an undeclared intervention" ) for runtime, was_modified, remains_modified in zip( self._runtimes, scalar_modified.tolist(), modified.tolist() ): if was_modified and not remains_modified: if runtime.interventions < 1: raise OracleProgramRuntimeError( "runtime intervention accounting underflowed" ) runtime.interventions -= 1 synchronized_counts = torch.as_tensor( [runtime.interventions for runtime in self._runtimes], device=executed.device, dtype=torch.int64, ) self._trace.append( { "modified": modified.detach().clone(), "safety_clipped": torch.as_tensor( [bool(result.trace["safety_clipped"]) for result in results], device=executed.device, dtype=torch.bool, ), "authority_clipped": torch.as_tensor( [bool(result.trace["authority_clipped"]) for result in results], device=executed.device, dtype=torch.bool, ) | component_authority_clipped | conversion_authority_clipped, "additive_selected": additive_selected.detach().clone(), "replacement_selected": replacement_selected.detach().clone(), "replacement_owned": replacement_owned.detach().clone(), "phase_before": torch.as_tensor( [self._phase_indices[result.phase_before] for result in results], device=executed.device, dtype=torch.int64, ), "phase_after": torch.as_tensor( [self._phase_indices[result.phase_after] for result in results], device=executed.device, dtype=torch.int64, ), "transitioned": torch.as_tensor( [result.transition is not None for result in results], device=executed.device, dtype=torch.bool, ), "intervention_count": synchronized_counts, "proposed_action": proposed_policy_action.detach().clone(), "executed_action": executed.detach().clone(), } ) return executed def stacked_trace(self) -> dict[str, torch.Tensor]: if not self._trace: raise OracleProgramRuntimeError("no program trace has been recorded") return { name: torch.stack([row[name] for row in self._trace], dim=0) for name in self._trace[0] } __all__ = [ "OracleProgramRuntimeError", "OracleSignalProvider", "SimOracleProgramPatcher", ]