# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-level-provenance-from-surviving-a-compaction-boundary-between-prompt-inputs-and-side-effecting-actions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-level-provenance-from-surviving-a-compaction-boundary-between-prompt-inputs-and-side-effecting-actions.warrant.json
# Markdown SHA-256:   24098f0dfbc808cc87ebf89f84cad69faa84660fce735126a592660c520a6579
# Code AST SHA-256:   bacc63c80339ee0fdb0f7ac14026b9050d90e62f3f91b46fb50021026894796a
# Verified Classes:   ProvenanceInvariantViolation, TraceNode, ContextWindow, SideEffect
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceInvariantViolation(RuntimeError):
    """Raised when a side-effecting action cannot be bound to the bytes
    actually consumed by the model at emission time."""


@dataclass
class TraceNode:
    node_id: str
    content: bytes
    derived_from: Optional[str] = None

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.content).hexdigest()


@dataclass
class ContextWindow:
    """Mutable context window. Every mutation MUST re-bind provenance."""
    nodes: list[TraceNode] = field(default_factory=list)
    _consumed_hash: Optional[str] = None

    def present(self, node: TraceNode) -> None:
        self.nodes.append(node)
        self._consumed_hash = self._hash_window()

    def _hash_window(self) -> str:
        h = hashlib.sha256()
        for n in self.nodes:
            h.update(n.content_hash.encode())
        return h.hexdigest()

    def compact(self, summary: TraceNode) -> None:
        """Collapse the window into a summary. This MUTATES the consumed bytes.

        The summary must declare derived_from so the trace retains a walkable
        edge back to the original bytes. Without this edge, provenance is
        severed and any subsequent action inherits fabricated attribution.
        """
        if summary.derived_from is None:
            raise ProvenanceInvariantViolation(
                "compaction produced a summary with no derived_from edge; "
                "consumed-bytes invariant cannot be verified post-hoc"
            )
        self.nodes = [summary]
        self._consumed_hash = self._hash_window()

    @property
    def consumed_hash(self) -> str:
        if self._consumed_hash is None:
            raise ProvenanceInvariantViolation(
                "context window has no consumed hash; cannot bind action"
            )
        return self._consumed_hash


@dataclass
class SideEffect:
    action: str
    payload: dict
    bound_hash: str


def emit_side_effect(
    window: ContextWindow,
    action: str,
    payload: dict,
    observed_hash: str,
) -> SideEffect:
    """Emit a side-effecting action, binding it to the consumed bytes.

    observed_hash is the hash captured when the action's triggering input was
    first observed. If the window was mutated (compaction, reorder, re-fetch)
    between observation and emission, observed_hash != window.consumed_hash
    and the binding is invalid.
    """
    if observed_hash != window.consumed_hash:
        raise ProvenanceInvariantViolation(
            f"provenance divergence: action {action!r} was conditioned on "
            f"bytes {observed_hash[:12]} but window now holds "
            f"{window.consumed_hash[:12]}; compaction or reorder occurred "
            f"without a re-bind"
        )
    return SideEffect(action=action, payload=payload, bound_hash=observed_hash)


def _demo() -> None:
    policy = TraceNode("D2", b"refund policy: permits refunds up to 30 days")
    window = ContextWindow()
    window.present(policy)
    observed = window.consumed_hash  # captured at observation

    # Runtime compacts under pressure; summarizer drops the "30 days" bound.
    lossy_summary = TraceNode(
        "summary_0x9f",
        b"policy permits refunds",
        derived_from="D2",
    )
    window.compact(lossy_summary)

    # Emission against the stale observed hash must fail loudly.
    emit_side_effect(
        window,
        action="issue_refund",
        payload={"amount": 420, "order_age_days": 44},
        observed_hash=observed,
    )


if __name__ == "__main__":
    _demo()
