# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-speculative-branch-be-discarded-rather-than-verified-rollback-vs-late-confidence-inversion-in-branch-and-verify-multi-agen.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-speculative-branch-be-discarded-rather-than-verified-rollback-vs-late-confidence-inversion-in-branch-and-verify-multi-agen.warrant.json
# Markdown SHA-256:   e8590b06008970ae0d287a986f5230eed4e166e15b9ff7b27daf2e4972f055e6
# Code AST SHA-256:   fe51df3fd30d6b8609a80fb01751ce0db9145d947a9f822d77655b0aa1918b5e
# Verified Classes:   LateConfidenceInversion, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class LateConfidenceInversion(RuntimeError):
    """Raised when a branch is rejected after verification has already
    consumed its speculative state, making rollback incomplete."""
    pass


class Branch:
    def __init__(self, branch_id, confidence, verification_started, write_set_closed):
        self.branch_id = branch_id
        self.confidence = confidence
        self.verification_started = verification_started
        self.write_set_closed = write_set_closed


def gate(branch: Branch, threshold: float = 0.7) -> str:
    if branch.confidence >= threshold:
        return "promote"

    # Rejection path: only safe if verification has not yet touched state
    # AND the verifier's stores are inside the checkpoint write set.
    if branch.verification_started and not branch.write_set_closed:
        raise LateConfidenceInversion(
            f"branch {branch.branch_id} rejected at confidence "
            f"{branch.confidence} after verification started with an "
            f"open write set; rollback would leave verifier-side state "
            f"visible to sibling branches"
        )

    return "rollback"


def run(branches, threshold=0.7):
    outcomes = {}
    for b in branches:
        outcomes[b.branch_id] = gate(b, threshold)
    return outcomes


if __name__ == "__main__":
    # The observed incident: C verified, scored 0.62, write set open.
    incident = [
        Branch("A", 0.81, verification_started=False, write_set_closed=True),
        Branch("C", 0.62, verification_started=True,  write_set_closed=False),
    ]
    run(incident)  # raises LateConfidenceInversion on branch C
