# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-branch-into-a-poisoned-checkpoint-when-its-verifier-is-cheaper-than-its-executor.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-branch-into-a-poisoned-checkpoint-when-its-verifier-is-cheaper-than-its-executor.warrant.json
# Markdown SHA-256:   f44cfb2f2af85b8e4b6963702adf0961d8316160b7efd5d7cac22b255cc031ed
# Code AST SHA-256:   923f9c3c158cdc186b23b7fef564523b2478028c923092e4f6caee1e401c8409
# Verified Classes:   StaleEvidenceError, Evidence, Branch, SpeculativeOrchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Set


class StaleEvidenceError(RuntimeError):
    """Raised when verifier evidence is consumed after its footprint was mutated."""
    pass


@dataclass
class Evidence:
    epoch: int
    footprint: Dict[str, str]  # resource_path -> sha256 at gather time


@dataclass
class Branch:
    name: str
    epoch: int
    mutation_footprint: Set[str]  # resources this branch's rollback would touch


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        self.epoch = 0
        self.evidence: Dict[str, Evidence] = {}
        self.live_branches: Dict[str, Branch] = {}

    def gather_evidence(self, branch: str, resources: Dict[str, bytes]) -> Evidence:
        footprint = {p: hashlib.sha256(b).hexdigest() for p, b in resources.items()}
        ev = Evidence(epoch=self.epoch, footprint=footprint)
        self.evidence[branch] = ev
        return ev

    def rollback(self, branch: str) -> None:
        b = self.live_branches.get(branch)
        if b is None:
            return
        # Invalidate any evidence whose footprint intersects the rollback footprint.
        for name, ev in list(self.evidence.items()):
            if ev.footprint.keys() & b.mutation_footprint:
                del self.evidence[name]
        # Conservative epoch bump: any rollback ends the evidence epoch.
        self.epoch += 1
        del self.live_branches[branch]

    def commit(self, branch: str, current_resources: Dict[str, bytes]) -> None:
        ev = self.evidence.get(branch)
        if ev is None:
            raise StaleEvidenceError(
                f"no valid evidence for branch {branch!r}; re-verify required"
            )
        if ev.epoch != self.epoch:
            raise StaleEvidenceError(
                f"evidence for {branch!r} from epoch {ev.epoch}, current {self.epoch}"
            )
        for path, expected_hash in ev.footprint.items():
            actual = hashlib.sha256(current_resources[path]).hexdigest()
            if actual != expected_hash:
                raise StaleEvidenceError(
                    f"resource {path!r} mutated since verification: "
                    f"expected {expected_hash[:12]}, got {actual[:12]}"
                )
        # Commit is safe: evidence footprint matches on-disk state at commit time.
