# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-liability-attribution-collapse-in-cross-org-agent-federations-when-audit-trails-diverge-by-one-non-idempotent-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-liability-attribution-collapse-in-cross-org-agent-federations-when-audit-trails-diverge-by-one-non-idempotent-retry.warrant.json
# Markdown SHA-256:   ff82036225f1d2f4c7166e112c5ad5ff33f433319b1efde7ed32e5e8f2326287
# Code AST SHA-256:   fe0ae225f293347727c33aa1588547e6d06808b575f9611314b1e1f034c1baa7
# Verified Classes:   AttributionUndecidableError, Warrant, Effect, ExecutorState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttributionUndecidableError(RuntimeError):
    """Raised when a cross-org audit divergence cannot be attributed from logs alone."""


@dataclass
class Warrant:
    warrant_id: str
    principal: str
    amount: int
    chain_id: Optional[str] = None       # MUST be present for retry-safe federations
    retry_seq: int = 0


@dataclass
class Effect:
    effect_id: str
    warrant_id: str
    amount: int
    chain_id: Optional[str] = None
    retry_seq: Optional[int] = None


@dataclass
class ExecutorState:
    effects: list = field(default_factory=list)
    cumulative_by_chain: dict = field(default_factory=dict)


def execute_with_ceiling(warrant: Warrant, state: ExecutorState) -> Effect:
    if warrant.chain_id is None:
        # No chain identity: cannot enforce cumulative ceiling across retries.
        raise AttributionUndecidableError(
            f"warrant {warrant.warrant_id} lacks chain_id; "
            "cumulative ceiling unenforceable on retry"
        )
    prior = state.cumulative_by_chain.get(warrant.chain_id, 0)
    if prior + warrant.amount > warrant.amount:
        # Ceiling is per-warrant, not per-attempt: any prior effect on this chain
        # means the ceiling is already consumed.
        raise AttributionUndecidableError(
            f"chain {warrant.chain_id} already consumed {prior}; "
            f"retry of {warrant.warrant_id} would exceed authority ceiling"
        )
    eff = Effect(
        effect_id=f"E-{len(state.effects) + 1}",
        warrant_id=warrant.warrant_id,
        amount=warrant.amount,
        chain_id=warrant.chain_id,
        retry_seq=warrant.retry_seq,
    )
    state.effects.append(eff)
    state.cumulative_by_chain[warrant.chain_id] = prior + warrant.amount
    return eff


def reconcile(warrants: list, effects: list) -> dict:
    """Join on (warrant_id, chain_id, retry_seq). Orphan effects are executor-side."""
    by_key = {(w.warrant_id, w.chain_id, w.retry_seq): w for w in warrants}
    attribution = {"orchestrator": [], "executor": [], "undecidable": []}
    for e in effects:
        key = (e.warrant_id, e.chain_id, e.retry_seq)
        if e.chain_id is None or e.retry_seq is None:
            attribution["undecidable"].append(e)
            continue
        if key in by_key:
            attribution["orchestrator"].append(e)
        else:
            attribution["executor"].append(e)
    if attribution["undecidable"]:
        raise AttributionUndecidableError(
            f"{len(attribution['undecidable'])} effects lack retry-chain identity; "
            "liability cannot be attributed from logs alone"
        )
    return attribution
