File size: 27,292 Bytes
97eb21c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
"""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",
]