# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-a-long-horizon-session-and-the-summary-silently-drops-the-discriminator-that-a-later-tool-call-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-a-long-horizon-session-and-the-summary-silently-drops-the-discriminator-that-a-later-tool-call-depends-on.warrant.json
# Markdown SHA-256:   ccc98f583a9f618f361a74e873d6c861ed1ae79ad7960c895ea9f1556c3dda80
# Code AST SHA-256:   328eaff1949354131ffc94827d09a916a62e87c7d9b16f5a8ebce3fcd30a0505
# Verified Classes:   DiscriminatorLossError, PinnedToken, CompactionRequest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

"""Compaction guard: refuse to summarize a span whose discriminators are
load-bearing for a deferred future action, and refuse to reconstruct a
discriminator from a summary mention. Re-fetch is the only legal recovery."""

from dataclasses import dataclass, field
from typing import Optional


class DiscriminatorLossError(RuntimeError):
    """Raised when compaction would evict a token a future action keys on,
    or when an action attempts to reconstruct a token from a summary."""


@dataclass(frozen=True)
class PinnedToken:
    key: str                 # e.g. "replica_service_id"
    value: str               # e.g. "svc-a7f4"  -- verbatim, never summarized
    source_turn: int
    provenance_ts: float


@dataclass
class CompactionRequest:
    span_id: str
    summary: str
    pinned_consumers: dict[str, set[str]]   # key -> pending action ids
    pin_store: dict[str, PinnedToken] = field(default_factory=dict)


def authorize_compaction(req: CompactionRequest) -> None:
    """Compaction is legal only if every pinned key with a non-empty
    future-consumer set is present verbatim in the pin store."""
    for key, consumers in req.pinned_consumers.items():
        if not consumers:
            continue
        if key not in req.pin_store:
            raise DiscriminatorLossError(
                f"span {req.span_id!r}: key {key!r} has live consumers "
                f"{sorted(consumers)} but is absent from pin store; "
                f"summarizing would force reconstruction from summary."
            )


def resolve_for_action(
    key: str,
    requested_value: str,
    pin_store: dict[str, PinnedToken],
    current_source_value: Optional[str],
) -> PinnedToken:
    """Resolve a token for a deferred action. Rejects reconstructed values,
    and detects world-drift between pin time and action time."""
    pin = pin_store.get(key)
    if pin is None:
        raise DiscriminatorLossError(
            f"key {key!r} not pinned; cannot resolve. Re-fetch raw value "
            f"before proceeding -- do not infer from summary."
        )
    if requested_value != pin.value:
        raise DiscriminatorLossError(
            f"key {key!r}: action requested {requested_value!r} but pinned "
            f"value is {pin.value!r} (source_turn={pin.source_turn}). "
            f"Value appears reconstructed from summary mention."
        )
    if current_source_value is not None and current_source_value != pin.value:
        raise DiscriminatorLossError(
            f"key {key!r}: source drifted since turn {pin.source_turn} "
            f"(pinned {pin.value!r}, now {current_source_value!r}); "
            f"dependent action must halt and re-plan."
        )
    return pin


# --- failure trace from the observed run, replayed ---
if __name__ == "__main__":
    pins = {
        "primary_service_id": PinnedToken("primary_service_id", "svc-a7f3", 11, 0.0),
        # replica token was NOT pinned -- compactor summarized it away
    }
    req = CompactionRequest(
        span_id="turn-11-registry-read",
        summary="confirmed primary and replica (svc-a7f3 family)",
        pinned_consumers={"replica_service_id": {"rollback-replica"}},
        pin_store=pins,
    )
    try:
        authorize_compaction(req)          # -> raises: replica not pinned
    except DiscriminatorLossError as e:
        print("compaction blocked:", e)

    try:
        resolve_for_action(
            "replica_service_id", "svc-a7f3-replica", pins, None
        )                                  # -> raises: reconstructed token
    except DiscriminatorLossError as e:
        print("action blocked:", e)
