# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-fold-a-peer-s-attestation-into-its-local-reputation-state-to-preserve-sybil-resistance.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-fold-a-peer-s-attestation-into-its-local-reputation-state-to-preserve-sybil-resistance.warrant.json
# Markdown SHA-256:   7073d3b7ecc9620e52a6ad99d4e8af51dfd85ca702ee59763b2d33d7edea7754
# Code AST SHA-256:   16e2e89daff930d7baa35b2308f5448e9940177ac9ea092fae93b43206617ac7
# Verified Classes:   UngroundedAttestationError, Attestation, ReputationState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class UngroundedAttestationError(RuntimeError):
    """Raised when an attestation cannot be folded without laundering weight
    through an ungrounded or cyclic reputation path."""
    pass


@dataclass
class Attestation:
    attester: str
    subject: str
    delta: float
    signature: str
    timestamp: float


@dataclass
class ReputationState:
    # score[peer] = aggregate score used for allocation decisions
    score: Dict[str, float] = field(default_factory=dict)
    # grounded[peer] = score recomputable from root-seeded observations only
    grounded: Dict[str, float] = field(default_factory=dict)
    # positive-contribution edges: (attester, subject)
    edges: Set[Tuple[str, str]] = field(default_factory=set)
    # root-verified nodes: seeded by this instance's own direct observation
    roots: Set[str] = field(default_factory=set)
    # quarantined attestations awaiting grounding
    quarantine: list = field(default_factory=list)


def _reachable_without(state: ReputationState, src: str,
                       forbidden: Set[str]) -> Set[str]:
    """Nodes reachable from src over positive edges, never entering forbidden."""
    seen: Set[str] = set()
    stack = [src]
    while stack:
        node = stack.pop()
        if node in seen or node in forbidden:
            continue
        seen.add(node)
        for (a, s) in state.edges:
            if a == node and s not in forbidden:
                stack.append(s)
    return seen


def _has_grounded_path(state: ReputationState, peer: str) -> bool:
    if peer in state.roots:
        return True
    for root in state.roots:
        if peer in _reachable_without(state, root, forbidden=set()):
            return True
    return False


def _would_create_cycle(state: ReputationState, attester: str,
                        subject: str) -> bool:
    # adding attester -> subject creates a cycle iff subject reaches attester
    return attester in _reachable_without(state, subject, forbidden=set())


def fold_attestation(state: ReputationState, att: Attestation,
                     verify_signature) -> None:
    if not verify_signature(att):
        raise UngroundedAttestationError(
            f"signature invalid for {att.attester}->{att.subject}")

    # 1. Attester must have a grounded path that does not route through subject.
    reach = _reachable_without(state, att.attester, forbidden={att.subject})
    grounded_ok = att.attester in state.roots or any(
        r in reach or r == att.attester for r in state.roots)
    if not grounded_ok:
        state.quarantine.append(att)
        raise UngroundedAttestationError(
            f"attester {att.attester} has no grounded path excluding "
            f"subject {att.subject}; quarantined, not folded")

    # 2. No positive-weight cycle may be introduced.
    if _would_create_cycle(state, att.attester, att.subject):
        state.quarantine.append(att)
        raise UngroundedAttestationError(
            f"edge {att.attester}->{att.subject} would close a positive-weight "
            f"cycle; quarantined, not folded")

    # 3. Weight is capped by grounded score, never aggregate score.
    w = max(0.0, min(1.0, state.grounded.get(att.attester, 0.0)))
    if w == 0.0:
        state.quarantine.append(att)
        raise UngroundedAttestationError(
            f"grounded score of {att.attester} is zero; weight would be zero, "
            f"aggregate score is not a valid substitute")

    state.score[att.subject] = state.score.get(att.subject, 0.0) + w * att.delta
    state.edges.add((att.attester, att.subject))


def replay_quarantine(state: ReputationState, verify_signature) -> None:
    """Re-evaluate quarantined attestations after any new root observation."""
    pending, state.quarantine = state.quarantine, []
    for att in pending:
        try:
            fold_attestation(state, att, verify_signature)
        except UngroundedAttestationError:
            pass  # remains quarantined; fold_attestation re-appended it
