# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-benchmark-task-grading-as-a-safety-critical-oracle-rather-than-a-passive-eval-metric.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-benchmark-task-grading-as-a-safety-critical-oracle-rather-than-a-passive-eval-metric.warrant.json
# Markdown SHA-256:   9ca4dc54703570fcd3eba301dad6997fe85958837cbf3a9d460cbbe185a69dda
# Code AST SHA-256:   5b2b6fdfd9675f1293d4bdb729d14e48101f3218f9d6dd37a255f00b80df9c59
# Verified Classes:   PartialOracleAuthorizationError, GraderManifest, Execution
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field


class PartialOracleAuthorizationError(RuntimeError):
    """Raised when a LITMUS grader's PASS is used to authorize a plan
    despite the grader being a partial oracle (terminal-state-only or
    incomplete observable surface)."""


@dataclass
class GraderManifest:
    name: str
    observable_surface: set  # channels the grader actually inspects
    evaluates_transitions: bool


@dataclass
class Execution:
    plan_id: str
    effect_log: dict = field(default_factory=dict)  # channel -> list of events
    terminal_state: dict = field(default_factory=dict)


def authorize_plan(
    execution: Execution,
    grader_results: dict,
    manifests: dict,
    hazardous_channels: set,
) -> bool:
    # 1. All graders must pass.
    if not all(grader_results.values()):
        return False

    # 2. Every hazardous channel must be inside at least one grader's
    #    observable surface, otherwise PASS is unsound for authorization.
    covered = set()
    for m in manifests.values():
        covered |= m.observable_surface
    uncovered = hazardous_channels - covered
    if uncovered:
        raise PartialOracleAuthorizationError(
            f"plan {execution.plan_id}: hazardous channels {sorted(uncovered)} "
            f"are not observed by any grader; PASS cannot authorize acceptance"
        )

    # 3. Graders that only sample terminal state cannot detect a
    #    compensating transition (e.g. cancel-then-restore).
    if not all(m.evaluates_transitions for m in manifests.values()):
        for channel in hazardous_channels:
            events = execution.effect_log.get(channel, [])
            if len(events) > 1:
                raise PartialOracleAuthorizationError(
                    f"plan {execution.plan_id}: channel {channel!r} shows "
                    f"{len(events)} transitions but grader is terminal-state-only; "
                    f"compensating-action hazard is unobservable"
                )

    # 4. Reject if any effect occurred on a channel outside the manifest.
    for channel, events in execution.effect_log.items():
        if events and channel not in covered:
            raise PartialOracleAuthorizationError(
                f"plan {execution.plan_id}: effect on unmanifested channel "
                f"{channel!r} ({len(events)} events); PASS is partial-oracle evidence only"
            )

    return True


def accept_first_passing_plan(
    plans,
    execute_fn,
    grade_fn,
    manifests,
    hazardous_channels,
):
    for plan in plans:
        execution = execute_fn(plan)
        results = grade_fn(execution)
        try:
            if authorize_plan(execution, results, manifests, hazardous_channels):
                return plan
        except PartialOracleAuthorizationError as e:
            # Do NOT silently skip and retry — that is the amplification path.
            # Escalate; a partial-oracle PASS must not drive the retry loop.
            raise PartialOracleAuthorizationError(
                f"refusing to accept plan under partial oracle: {e}"
            ) from e
    return None
