# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-self-corrupt-when-model-driven-segment-rewriting-outlives-the-relevance-scores-that-justified-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-self-corrupt-when-model-driven-segment-rewriting-outlives-the-relevance-scores-that-justified-it.warrant.json
# Markdown SHA-256:   056294c0bdae71633a4604ea8fd1d8a3d600a358c48d6d29edd59b9677129e52
# Code AST SHA-256:   31b407de940e4e2686d47335bd98c35ce9e35325fde503d23d21c0f971c0b5c4
# Verified Classes:   ScoreOrphanError, ProvenanceIncompleteError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence

class ScoreOrphanError(RuntimeError):
    """Raised when a model-authored merge outranks its own sources."""
    pass

class ProvenanceIncompleteError(RuntimeError):
    """Raised when a merge drops verifiable claims carried by its inputs."""
    pass

@dataclass
class Segment:
    id: str
    content: str
    score: float
    provenance: frozenset[str] = field(default_factory=frozenset)

def decide_merge(
    merged: Segment,
    inputs: Sequence[Segment],
    query_id: str,
    scored_query_id: str,
    provenance_complete: bool,
) -> str:
    if query_id != scored_query_id:
        # Scores are incommensurable across a query change; refuse to evict.
        return "reject_and_rescore"

    if not provenance_complete or not merged.provenance.issuperset(
        frozenset().union(*(s.provenance for s in inputs))
    ):
        raise ProvenanceIncompleteError(
            f"merge {merged.id} dropped provenance from inputs "
            f"{[s.id for s in inputs]}"
        )

    ceiling = max(s.score for s in inputs)
    if merged.score > ceiling:
        ratio = merged.score / ceiling if ceiling > 0 else float("inf")
        if ratio > 1.0:
            raise ScoreOrphanError(
                f"merge {merged.id} scored {merged.score:.2f} vs input ceiling "
                f"{ceiling:.2f} (ratio {ratio:.2f}); sources must be retained"
            )

    return "retain_and_evict_sources"
