# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-speculative-execution-when-a-federated-verifier-s-committed-plan-diverges-from-its-local-speculative-branch-and-how-is-the.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-speculative-execution-when-a-federated-verifier-s-committed-plan-diverges-from-its-local-speculative-branch-and-how-is-the.warrant.json
# Markdown SHA-256:   3ed8eb882cd2a6d9738bcfd57faee30ff9b43045c636067d78b0c039b2c9519d
# Code AST SHA-256:   0d1bf12d131813ab603bee7189f92aac859b86a9a0b94089d9ad431a5192ed6c
# Verified Classes:   DivergenceHalt, TraceEntry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DivergenceHalt(RuntimeError):
    """Raised when a speculative trace diverges from the committed trace."""
    pass


@dataclass(frozen=True)
class TraceEntry:
    step_id: str
    effect_hash: str
    chain_hash: str  # H(step_id || effect_hash || prev_chain_hash)


def chain(entries):
    prev = "GENESIS"
    out = []
    for step_id, effect_hash in entries:
        h = hashlib.sha256(
            f"{step_id}|{effect_hash}|{prev}".encode()
        ).hexdigest()
        out.append(TraceEntry(step_id, effect_hash, h))
        prev = h
    return out


def detect_divergence(local_entries, committed_entries, watermark):
    """Return the first index where local diverges from committed prefix.

    watermark = number of committed steps the verifier has attested.
    Speculation is only valid within [0, watermark).
    """
    local = chain(local_entries)
    committed = chain(committed_entries)

    for i in range(min(watermark, len(local), len(committed))):
        if local[i].chain_hash != committed[i].chain_hash:
            return i
    if len(local) > watermark and len(committed) <= watermark:
        # Speculated past the attested horizon: unsound ground.
        return watermark
    return None


def speculative_step(local_entries, committed_entries, watermark, next_step):
    idx = detect_divergence(local_entries, committed_entries, watermark)
    if idx is not None:
        raise DivergenceHalt(
            f"Speculative branch orphaned at index {idx}; "
            f"local step {next_step!r} would execute on unverified prefix. "
            f"Truncate to committed prefix and rejoin before resuming."
        )
    return next_step


if __name__ == "__main__":
    committed = [("s1", "e1"), ("s2", "e2"), ("s3", "e3"), ("s5", "e5")]
    local = [("s1", "e1"), ("s2", "e2"), ("s3", "e3"), ("s4", "e4"), ("s5", "e5")]

    try:
        speculative_step(local, committed, watermark=4, next_step="s5")
    except DivergenceHalt as exc:
        print(f"HALT: {exc}")
