# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-context-window-splice-as-a-policy-renegotiation-rather-than-a-cache-miss.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-context-window-splice-as-a-policy-renegotiation-rather-than-a-cache-miss.warrant.json
# Markdown SHA-256:   702dfd5dd84f53f924f7d73a8df30fe458a48db69f554ecd68df2373e5f50560
# Code AST SHA-256:   f87e6a152dad08049fe017b4b7890c2301fa269b683099cc04d54ecb8e96406c
# Verified Classes:   StalePolicySpliceError, PolicyStore, FederatedFragment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StalePolicySpliceError(RuntimeError):
    """Raised when a federated fragment would be spliced under a policy
    generation older than the current negotiated generation."""
    pass


class PolicyStore:
    def __init__(self):
        self._gen = {}  # (peer_org, policy_id) -> current generation

    def current_generation(self, peer_org, policy_id):
        return self._gen.get((peer_org, policy_id), 0)

    def revise(self, peer_org, policy_id, new_gen):
        key = (peer_org, policy_id)
        if new_gen <= self._gen.get(key, 0):
            raise StalePolicySpliceError(
                f"non-monotonic revision for {key}: {new_gen} <= {self._gen.get(key, 0)}"
            )
        self._gen[key] = new_gen


class FederatedFragment:
    def __init__(self, fragment_id, peer_org, policy_id, envelope_gen, payload, externally_effectful):
        self.fragment_id = fragment_id
        self.peer_org = peer_org
        self.policy_id = policy_id
        self.envelope_gen = envelope_gen
        self.payload = payload
        self.externally_effectful = externally_effectful


def splice(fragment: FederatedFragment, store: PolicyStore, *, revalidate_gate: bool):
    current = store.current_generation(fragment.peer_org, fragment.policy_id)
    if fragment.envelope_gen != current:
        # A cache hit on payload is NOT a hit on policy. Renegotiate.
        raise StalePolicySpliceError(
            f"fragment {fragment.fragment_id} envelope_gen={fragment.envelope_gen} "
            f"< current_gen={current} for ({fragment.peer_org},{fragment.policy_id}); "
            f"renegotiate before splice"
        )
    if fragment.externally_effectful and not revalidate_gate:
        # Generation matched at check time, but effect is irreversible:
        # require a second read immediately before the effect.
        raise StalePolicySpliceError(
            f"fragment {fragment.fragment_id} is externally effectful; "
            f"revalidation gate required"
        )
    return fragment.payload
