# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-policy-renegotiation-that-arrives-mid-episode-and-how-does-the-policy-epoch-fence-prevent-retroa.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-policy-renegotiation-that-arrives-mid-episode-and-how-does-the-policy-epoch-fence-prevent-retroa.warrant.json
# Markdown SHA-256:   0d13ce314df7f6081973b8e4407c08c8efaaa63134b166de995d019925e37043
# Code AST SHA-256:   7792c160ed67dfb091fac719706b65595c62426caa9be02335d4b5f856cb69f5
# Verified Classes:   PolicyFenceViolation, RenegotiationFrame, InstanceState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class PolicyFenceViolation(RuntimeError):
    """Raised when a renegotiation cannot be fenced against in-flight commits."""
    pass


@dataclass(frozen=True)
class RenegotiationFrame:
    policy_id: str
    effective_from: int          # logical timestamp / LSN
    audit_rebase: bool
    signature_valid: bool


@dataclass(frozen=True)
class InstanceState:
    current_epoch: str
    commit_watermark: int        # watermark of last DURABLY FLUSHED commit
    unflushed_commits: int       # commits written but not yet flushed


def adjudicate_renegotiation(
    state: InstanceState, frame: RenegotiationFrame
) -> str:
    # Step 1: content/signature validity is necessary but NOT sufficient.
    if not frame.signature_valid:
        raise PolicyFenceViolation(
            f"signature chain invalid for {frame.policy_id}"
        )

    # Step 2: the fence predicate. This is the whole game.
    rebases_before_watermark = (
        frame.audit_rebase and frame.effective_from < state.commit_watermark
    )
    effective_before_watermark = frame.effective_from < state.commit_watermark

    if rebases_before_watermark or effective_before_watermark:
        # Valid frame, but unfenceable against in-flight state.
        raise PolicyFenceViolation(
            f"cannot fence {frame.policy_id}: effective_from="
            f"{frame.effective_from} precedes commit_watermark="
            f"{state.commit_watermark} (unflushed={state.unflushed_commits}); "
            f"renegotiation would retroactively re-scope committed actions"
        )

    # Step 3: fence holds. Forward-only application.
    if state.unflushed_commits > 0:
        return "DEFER_TO_QUIESCENT_CHECKPOINT"
    return "ACCEPT_IN_PLACE"


def apply_forward_only(state: InstanceState, frame: RenegotiationFrame) -> InstanceState:
    decision = adjudicate_renegotiation(state, frame)
    if decision != "ACCEPT_IN_PLACE":
        raise PolicyFenceViolation(
            f"cannot apply {frame.policy_id} now; decision={decision}"
        )
    return InstanceState(
        current_epoch=frame.policy_id,
        commit_watermark=state.commit_watermark,
        unflushed_commits=state.unflushed_commits,
    )
