# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-litmus-safety-benchmark-task-instances-as-non-composable-when-gating-adversarial-agent-regressions.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-litmus-safety-benchmark-task-instances-as-non-composable-when-gating-adversarial-agent-regressions.warrant.json
# Markdown SHA-256:   ec04ebdd1a74cc09b020f05eddcf7e454c18d2050cc7a4a7b3acb530d37bb8b7
# Code AST SHA-256:   abfcf5cfdc434c2fb713e2753e98cb4e2f83eaa5e8866fe6f3fbcc59b1a2118e
# Verified Classes:   NonComposableInstanceError, StateDomain, LitmusInstance, ComposabilityGate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class NonComposableInstanceError(RuntimeError):
    """Raised when a LITMUS instance would run on contaminated or unproven state."""
    pass


@dataclass
class StateDomain:
    domain_id: str
    dirty_surfaces: Set[str] = field(default_factory=set)   # surfaces written since last flush
    validated_clean: bool = False

    def flush(self, surfaces: Set[str]) -> None:
        self.dirty_surfaces -= surfaces
        # A flush only *permits* revalidation; it does not assert cleanliness.
        self.validated_clean = False


@dataclass
class LitmusInstance:
    instance_id: str
    attack_family: str
    declared_surfaces: Set[str]          # every mutable surface this instance touches
    asserts_path_traversed: bool         # must be True for a pass to count


class ComposabilityGate:
    def __init__(self) -> None:
        self._domains: Dict[str, StateDomain] = {}
        self._verdicts: Dict[str, Dict[str, bool]] = {}  # order_id -> {instance_id: passed}

    def _domain_for(self, instance: LitmusInstance, order_id: str) -> StateDomain:
        # Domains are keyed by (family, order) so cross-family residue cannot leak.
        key = f"{instance.attack_family}::{order_id}"
        return self._domains.setdefault(key, StateDomain(domain_id=key))

    def schedule(self, instance: LitmusInstance, order_id: str) -> StateDomain:
        domain = self._domain_for(instance, order_id)
        overlap = instance.declared_surfaces & domain.dirty_surfaces
        if overlap:
            raise NonComposableInstanceError(
                f"instance {instance.instance_id} would run on dirty surfaces {sorted(overlap)} "
                f"in domain {domain.domain_id}; flush and revalidate before scheduling"
            )
        if not domain.validated_clean and domain.dirty_surfaces:
            raise NonComposableInstanceError(
                f"domain {domain.domain_id} has unvalidated residue; refusing to schedule "
                f"{instance.instance_id}"
            )
        return domain

    def record(self, instance: LitmusInstance, order_id: str, passed: bool, path_traversed: bool) -> None:
        if passed and not path_traversed:
            # A refusal that never encountered the attack surface is a false pass.
            raise NonComposableInstanceError(
                f"instance {instance.instance_id} reported pass without traversing the "
                f"adversarial path; verdict is non-composable"
            )
        self._verdicts.setdefault(order_id, {})[instance.instance_id] = passed
        domain = self._domain_for(instance, order_id)
        domain.dirty_surfaces |= instance.declared_surfaces
        domain.validated_clean = False

    def assert_permutation_invariant(self) -> None:
        orders = list(self._verdicts.values())
        if len(orders) < 2:
            raise NonComposableInstanceError(
                "need >=2 orderings to validate permutation invariance; single-order "
                "aggregate stability is not evidence of validity"
            )
        base = orders[0]
        for other in orders[1:]:
            if base != other:
                diff = {k for k in base if base.get(k) != other.get(k)}
                raise NonComposableInstanceError(
                    f"per-instance verdict vector is order-dependent on {sorted(diff)}; "
                    f"aggregate gate is invalid regardless of aggregate stability"
                )
