# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compresses-its-own-context-and-the-decompression-oracle-is-the-same-model-that-wrote-the-compressor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compresses-its-own-context-and-the-decompression-oracle-is-the-same-model-that-wrote-the-compressor.warrant.json
# Markdown SHA-256:   5c4fc16dcbb2835e1bc9c7fe3fea7f911da0414d7399d7bd4a7ccbae18085cc4
# Code AST SHA-256:   c2387379ea0d0a9505c53e949f583d94ba3b312ba07d61a6f994b7471b4d009f
# Verified Classes:   ReconstructionFidelityViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ReconstructionFidelityViolation(RuntimeError):
    """Raised when a compressed span's reconstruction is used to authorize
    an irreversible action without dereferencing the raw source."""
    pass


IRREVERSIBLE_ACTIONS = {"send_request", "commit_write", "spend_budget", "retry"}


def authorize_action(action: str, span_ref: dict, reconstruction: dict) -> bool:
    """
    span_ref: {"raw_available": bool, "obligation": set[str], "critical_fields": set[str]}
    reconstruction: {"confidence": float, "fields_present": set[str], "source": str}
    """
    if action not in IRREVERSIBLE_ACTIONS:
        return True

    # Invariant: irreversible actions require a dereferenced raw span,
    # not a model-generated reconstruction.
    if reconstruction["source"] != "raw_dereference":
        raise ReconstructionFidelityViolation(
            f"action={action!r} authorized from reconstruction source="
            f"{reconstruction['source']!r}; raw span not dereferenced. "
            f"Confidence {reconstruction['confidence']:.2f} is not admissible "
            f"evidence for irreversible actions."
        )

    if action in span_ref["obligation"] and not span_ref["raw_available"]:
        raise ReconstructionFidelityViolation(
            f"action={action!r} carries a dereference obligation but raw span "
            f"is unavailable; cannot bound omission-type loss."
        )

    missing = span_ref["critical_fields"] - reconstruction["fields_present"]
    if missing:
        raise ReconstructionFidelityViolation(
            f"reconstruction is missing critical fields {sorted(missing)}; "
            f"omission-type loss detected against raw source."
        )

    return True


def canary_check(oracle, plant_field: str = "idempotency_scope") -> None:
    """Nightly canary: the fidelity oracle MUST fail on a planted omission.
    If it does not, it is a fluency meter, not a fidelity check."""
    synthetic_span = {"retry_after": 47, plant_field: "per_tenant"}
    summary = "rate-limit encountered; backoff applied"  # drops plant_field
    verdict = oracle(summary=summary, state={}, span=synthetic_span)
    if verdict["confidence"] > 0.8 and plant_field not in verdict.get("fields_present", set()):
        raise ReconstructionFidelityViolation(
            f"fidelity oracle returned confidence {verdict['confidence']:.2f} on a "
            f"reconstruction that omits planted field {plant_field!r}. "
            f"Oracle is self-referential and must be demoted to fluency meter; "
            f"enforce dereference-before-act for all irreversible actions."
        )
