# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-merge-has-silently-accepted-a-byzantine-fork.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-merge-has-silently-accepted-a-byzantine-fork.warrant.json
# Markdown SHA-256:   0a4b285090d379b824b13e7069ddaac82be809568a9459ad2052e6f9a8c84cfa
# Code AST SHA-256:   045c887641327f79ab948b91ed0f496619ae3df554b8e77b57fa67fd7cb180ef
# Verified Classes:   UnverifiableReadSetError, Delta
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnverifiableReadSetError(RuntimeError):
    """Raised when a speculative delta's read-set cannot be confirmed against the merger's checkpoint."""


@dataclass
class Delta:
    peer_id: str
    read_set: dict          # key -> value the peer claims it read at the fork point
    write_set: dict         # key -> value the peer proposes
    read_witness: dict = field(default_factory=dict)  # key -> digest of (key, value) at fork point


def _digest(key: str, value) -> str:
    return hashlib.sha256(f"{key}={value!r}".encode()).hexdigest()


def admit_delta(delta: Delta, base_checkpoint: dict, require_witness: bool = True) -> None:
    """
    Gate a delta into the conflict graph. Must run BEFORE value-diffing.
    Under Byzantine assumptions, require_witness must be True: a claimed read-set
    without a witness is an unverifiable negative and is rejected outright.
    """
    if require_witness and not delta.read_witness:
        raise UnverifiableReadSetError(
            f"peer {delta.peer_id}: delta carries no read-set witness; "
            f"cannot confirm absence of conflict under Byzantine fault model"
        )

    for key, claimed_value in delta.read_set.items():
        if key not in base_checkpoint:
            raise UnverifiableReadSetError(
                f"peer {delta.peer_id}: claims to read absent key {key!r} at fork point"
            )
        actual = base_checkpoint[key]
        if claimed_value != actual:
            raise UnverifiableReadSetError(
                f"peer {delta.peer_id}: read-set mismatch on {key!r}: "
                f"claimed {claimed_value!r}, checkpoint has {actual!r}"
            )
        if require_witness:
            expected = _digest(key, actual)
            if delta.read_witness.get(key) != expected:
                raise UnverifiableReadSetError(
                    f"peer {delta.peer_id}: witness digest mismatch on {key!r}"
                )

    # Cross-check: a write to a key the peer claims to have read must be
    # consistent with the read-set transition, else the delta smuggles a
    # non-conflicting mutation through an uncontested key.
    for key, new_value in delta.write_set.items():
        if key in delta.read_set and delta.read_set[key] == new_value:
            continue  # no-op write, benign
        if key in delta.read_set and key not in base_checkpoint:
            raise UnverifiableReadSetError(
                f"peer {delta.peer_id}: writes {key!r} it claims not to have read"
            )
    return None


def merge_speculative(base_checkpoint: dict, deltas: list[Delta]) -> dict:
    """Admit all deltas under witness verification, THEN value-diff for conflicts."""
    admitted = []
    for d in deltas:
        admit_delta(d, base_checkpoint, require_witness=True)  # raises on Byzantine forgery
        admitted.append(d)

    merged = dict(base_checkpoint)
    seen: dict[str, object] = {}
    for d in admitted:
        for key, val in d.write_set.items():
            if key in seen and seen[key] != val:
                raise UnverifiableReadSetError(
                    f"genuine conflict on {key!r} between admitted deltas"
                )
            seen[key] = val
            merged[key] = val
    return merged


# Trace of the observed incident:
cp_7 = {"plan.step": 3, "plan.next_action": "call_fetch"}
byzantine_c = Delta(
    peer_id="C",
    read_set={"plan.step": 3, "plan.next_action": "call_fetch"},
    write_set={"plan.next_action": "call_delete_index", "plan.step": 4},  # smuggled step advance
    read_witness={},  # no witness -> unverifiable negative
)
try:
    merge_speculative(cp_7, [byzantine_c])
except UnverifiableReadSetError as e:
    print(f"BLOCKED before conflict graph: {e}")
