# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-summarization-compaction-as-a-lossy-transform-and-gate-retrieval-handoff-on-a-provenance-complet.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-summarization-compaction-as-a-lossy-transform-and-gate-retrieval-handoff-on-a-provenance-complet.warrant.json
# Markdown SHA-256:   8269a58003ea558bac829a18ca27096ed09f2d9c0f1f75cc1c4dad2292b7d330
# Code AST SHA-256:   fae3e9c96c76a221e375bf6a9766502d84b8921e20ee64f104dbc2d9ed29140f
# Verified Classes:   ProvenanceIncompleteError, RetrievalHit
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProvenanceIncompleteError(RuntimeError):
    """Raised when a retrieval hit cannot be traced to a verbatim source span."""


@dataclass
class RetrievalHit:
    artifact_id: str
    text: str
    relevance: float
    derived: bool
    source_span_ids: list[str]


def promote_to_fact(hit: RetrievalHit, leaf_store: dict[str, str]) -> str:
    """
    Promote a retrieval hit to a fact usable in a state transition.
    Only verbatim leaf spans may be promoted. Derived summaries are
    navigational only and must be resolved to leaves first.
    """
    if not hit.derived:
        # Already a verbatim leaf; confirm it exists in the store.
        if hit.artifact_id not in leaf_store:
            raise ProvenanceIncompleteError(
                f"leaf {hit.artifact_id} claimed verbatim but absent from store"
            )
        return leaf_store[hit.artifact_id]

    # Derived artifact: attempt to resolve to a single verbatim leaf.
    resolvable = [sid for sid in hit.source_span_ids if sid in leaf_store]
    if not resolvable:
        raise ProvenanceIncompleteError(
            f"derived artifact {hit.artifact_id} has no surviving leaf spans; "
            f"relevance={hit.relevance:.2f} is not provenance"
        )
    if len(resolvable) > 1:
        raise ProvenanceIncompleteError(
            f"derived artifact {hit.artifact_id} maps to {len(resolvable)} leaves; "
            f"cannot disambiguate which span grounds the needed predicate"
        )
    # Single surviving leaf: re-derive from verbatim source, not from summary.
    return leaf_store[resolvable[0]]


def rollback_replica_count(hit: RetrievalHit, leaf_store: dict[str, str]) -> int:
    fact = promote_to_fact(hit, leaf_store)
    # Fact must contain an explicit scalar; summaries that elided it fail here.
    for token in fact.split():
        if token.isdigit():
            return int(token)
    raise ProvenanceIncompleteError(
        f"promoted fact lacks an explicit scalar: {fact!r}; "
        f"refusing to infer a rollback target"
    )
