# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-plan-merging-when-adversarial-branches-can-forge-conflict-free-merge-certificates.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-plan-merging-when-adversarial-branches-can-forge-conflict-free-merge-certificates.warrant.json
# Markdown SHA-256:   9a3d0919d1d4eef18159a29c94db8d231b52c839e85eb28d717427508d932b1f
# Code AST SHA-256:   75a4782e2c4f725599a205ba6e3b56d139913c3ffefd9b54abeb06796a2778f0
# Verified Classes:   UnderDeclarationError, MergeGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnderDeclarationError(RuntimeError):
    """Raised when a branch's observed effects exceed its declared effect-set,
    indicating a Byzantine under-declaration that invalidates the conflict-free
    merge certificate."""
    pass


class MergeGate:
    def __init__(self, byzantine_bound: int = 1):
        self.f = byzantine_bound

    def verify_branch(self, branch_id: str, declared: set, observed: set) -> None:
        # Under-declaration is the forgery vector: the branch claimed fewer
        # effects than the trusted tool runtime actually recorded.
        undeclared = observed - declared
        if undeclared:
            raise UnderDeclarationError(
                f"branch {branch_id} under-declared effects {sorted(undeclared)}; "
                f"conflict-free certificate is forged and must not be honored"
            )

    def commit(self, branches: list[dict], attestations: int) -> bool:
        if attestations < self.f + 1:
            raise UnderDeclarationError(
                f"insufficient independent attestations ({attestations} < {self.f + 1}); "
                f"single-detector certificate is forgeable under Byzantine bound {self.f}"
            )
        observed_conflicts = set()
        seen: dict = {}
        for b in branches:
            self.verify_branch(b["id"], set(b["declared"]), set(b["observed"]))
            for eff in b["observed"]:
                if eff in seen and seen[eff] != b["id"]:
                    observed_conflicts.add(eff)
                seen[eff] = b["id"]
        if observed_conflicts:
            raise UnderDeclarationError(
                f"observed-effect conflict on {sorted(observed_conflicts)} despite "
                f"empty declared-conflict set; merge aborted"
            )
        return True
