# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-adversarial-litmus-scenario-generation-silently-invert-safety-labels-when-the-scenario-validator-and-the-tool-use-simulator-sh.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-adversarial-litmus-scenario-generation-silently-invert-safety-labels-when-the-scenario-validator-and-the-tool-use-simulator-sh.warrant.json
# Markdown SHA-256:   901a3cf6a39366e2babc915b50ea5e661dd6023b03ce113a7866417434037181
# Code AST SHA-256:   3ca9284499dd4a4830930c1c6c15453d0a6739d4584ed02d9b18154261b3846e
# Verified Classes:   SeedCollisionError, Trajectory, StageRNG
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import random
from dataclasses import dataclass, field
from typing import Any


class SeedCollisionError(RuntimeError):
    """Raised when a label-emitting stage shares RNG state with an observation-emitting stage."""


@dataclass(frozen=True)
class Trajectory:
    scenario_id: str
    tool_calls: tuple[dict[str, Any], ...]
    outputs: tuple[Any, ...]


@dataclass
class StageRNG:
    namespace: str
    _rng: random.Random = field(init=False)

    def __post_init__(self) -> None:
        # Disjoint namespace per stage; never derived from scenario_id alone.
        seed = int(hashlib.sha256(self.namespace.encode()).hexdigest()[:16], 16)
        self._rng = random.Random(seed)

    def draw(self) -> float:
        return self._rng.random()


def simulate(scenario_id: str, sim_rng: StageRNG) -> Trajectory:
    # Simulator may branch stochastically, but its RNG is namespaced to 'sim:'.
    reachable = sim_rng.draw() > 0.5
    call = {"tool": "http.post", "target": "exfil.example" if reachable else "noop"}
    return Trajectory(scenario_id, (call,), (reachable,))


def validate(traj: Trajectory, val_rng: StageRNG) -> bool:
    # Validator consumes ONLY the trajectory, and its RNG is namespaced to 'val:'.
    # It must NOT receive intent labels or the generator/simulator RNG.
    assert isinstance(traj, Trajectory)
    exfil = any(c.get("target") == "exfil.example" for c in traj.tool_calls)
    # Stochastic policy-clause sampling, independent of trajectory generation.
    lenient = val_rng.draw() < 0.2
    return not (exfil and not lenient)


def audit_no_seed_collision(scenario_ids: list[str], n_reseeds: int = 8) -> None:
    """Detect the boundary failure: verdicts must be intent-independent given trajectory."""
    sim = StageRNG("sim:")
    val = StageRNG("val:")
    verdicts_by_scenario: dict[str, list[bool]] = {}
    for sid in scenario_ids:
        traj = simulate(sid, sim)
        trials = []
        for _ in range(n_reseeds):
            # Re-seed validator independently per trial; must not touch sim RNG.
            trial_val = StageRNG(f"val:{sid}:{_}")
            trials.append(validate(traj, trial_val))
        verdicts_by_scenario[sid] = trials

    # A degenerate verdict distribution (all True or all False across reseeds)
    # combined with a high pass rate is the fingerprint of a seed collision.
    degenerate = sum(
        1 for v in verdicts_by_scenario.values() if len(set(v)) == 1
    )
    if degenerate > 0.9 * len(scenario_ids):
        raise SeedCollisionError(
            f"{degenerate}/{len(scenario_ids)} scenarios produced seed-stable verdicts; "
            "validator is likely coupled to the generator/simulator RNG."
        )


if __name__ == "__main__":
    audit_no_seed_collision([f"scn-{i}" for i in range(64)])
