# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-branch-merge-divergence-in-speculative-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-branch-merge-divergence-in-speculative-multi-agent-rollback.warrant.json
# Markdown SHA-256:   09d6564b20956aff1df09d121afd6bf75754ebb85c1d7fed280ca9406fdd8e88
# Code AST SHA-256:   5b38a447df7ac50ae549ed6afcc03fcacacdb7da965dccebb62bdda893a1daf7
# Verified Classes:   StructuralDivergenceError, BranchResidue, MergeContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StructuralDivergenceError(RuntimeError):
    """Raised when a speculative branch merge passes value-equality but
    leaves structural residue observable to the committed branch."""


@dataclass
class BranchResidue:
    branch_id: str
    seq_range: tuple[int, int]
    idempotency_keys: set[str]
    evicted_cache_keys: set[str]


@dataclass
class MergeContext:
    committed_branch: str
    committed_seq_floor: int
    committed_keys: set[str]
    residues: list[BranchResidue] = field(default_factory=list)


def verify_structural_equivalence(ctx: MergeContext) -> None:
    gaps: list[str] = []
    key_collisions: list[str] = []
    unrestored_evictions: list[str] = []

    for r in ctx.residues:
        lo, hi = r.seq_range
        # A discarded branch consumed seq values below the committed floor;
        # if the committed branch observes history, that gap is a signal.
        if hi >= ctx.committed_seq_floor:
            gaps.append(f"{r.branch_id}: seq {lo}-{hi} overlaps committed floor "
                        f"{ctx.committed_seq_floor}")

        overlap = r.idempotency_keys & ctx.committed_keys
        if overlap:
            key_collisions.append(
                f"{r.branch_id}: keys {sorted(overlap)} reused by committed branch"
            )

        if r.evicted_cache_keys:
            unrestored_evictions.append(
                f"{r.branch_id}: {len(r.evicted_cache_keys)} evictions not reversed"
            )

    if gaps or key_collisions or unrestored_evictions:
        raise StructuralDivergenceError(
            "value-equality merge rejected: structural residue present | "
            f"seq_gaps={gaps} | key_collisions={key_collisions} | "
            f"unrestored_evictions={unrestored_evictions} | "
            "action=force_reobservation_or_abort"
        )


def branch_scoped_key(task_id: str, step_index: int, branch_nonce: str) -> str:
    if not branch_nonce:
        raise StructuralDivergenceError(
            f"task {task_id} step {step_index}: branch_nonce missing; "
            "task-scoped key would collide across speculative siblings"
        )
    return hashlib.sha256(
        f"{task_id}:{step_index}:{branch_nonce}".encode()
    ).hexdigest()


# --- exercise the guard with the observed failure ---
ctx = MergeContext(
    committed_branch="B",
    committed_seq_floor=4489,
    committed_keys={branch_scoped_key("recon-7", 2, "nonce-B")},
    residues=[
        BranchResidue("A", (4471, 4479),
                      {branch_scoped_key("recon-7", 2, "nonce-A")},
                      {"ledger:acct-42"}),
        BranchResidue("C", (4480, 4488), set(), set()),
    ],
)
# seq_range of A and C is below floor, but A evicted a cache key and A/B keys
# are namespaced here so no collision — the eviction alone must block commit.
try:
    verify_structural_equivalence(ctx)
except StructuralDivergenceError as e:
    print(f"BLOCKED: {e}")
