# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-been-silently-invalidated-by-a-sibling-s-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-been-silently-invalidated-by-a-sibling-s-rollback.warrant.json
# Markdown SHA-256:   af96291c8b211bb119ddf262771d9b45824dbefb82ab06200c75bac173d70114
# Code AST SHA-256:   1376e490224c23d8c4d125407ba19d26d8f88ce1f5bdd5ce5f9afd774c3f90dc
# Verified Classes:   SpeculativeBranchInvalidated, Snapshot, Branch, Lineage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SpeculativeBranchInvalidated(RuntimeError):
    """Raised when a branch's base content hash no longer matches the live lineage."""
    pass


@dataclass
class Snapshot:
    version: str
    content: bytes

    def content_hash(self) -> str:
        return hashlib.sha256(self.content).hexdigest()


@dataclass
class Branch:
    branch_id: str
    base_version: str
    base_content_hash: str
    committed: bool = False
    invalidated: bool = False


@dataclass
class Lineage:
    snapshots: dict = field(default_factory=dict)  # version -> Snapshot
    branches: dict = field(default_factory=dict)    # branch_id -> Branch
    parent_of: dict = field(default_factory=dict)   # version -> parent version

    def is_ancestor(self, candidate: str, of: str) -> bool:
        cur = of
        while cur is not None:
            if cur == candidate:
                return True
            cur = self.parent_of.get(cur)
        return False

    def rollback(self, version: str, restored: Snapshot) -> list:
        """Roll back `version` to `restored`. Returns branch_ids invalidated.

        A branch is invalidated iff the restored pointer is NOT an ancestor of the
        branch's base version AND the restored content hash differs from the
        branch's recorded base content hash. Pointer equality alone is insufficient.
        """
        new_hash = restored.content_hash()
        self.snapshots[restored.version] = restored
        invalidated = []
        for b in self.branches.values():
            if b.committed or b.invalidated:
                continue
            ancestor_ok = self.is_ancestor(restored.version, b.base_version)
            hash_ok = (new_hash == b.base_content_hash)
            if not ancestor_ok and not hash_ok:
                b.invalidated = True
                invalidated.append(b.branch_id)
        return invalidated

    def commit(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        if b.invalidated:
            # Guardrail: refuse to commit a branch whose base content was rewound.
            raise SpeculativeBranchInvalidated(
                f"branch {branch_id} base={b.base_version}"
                f" hash={b.base_content_hash[:12]} was rewound by sibling rollback;"
                f" revalidate against live lineage before commit"
            )
        live_hash = self.snapshots[b.base_version].content_hash()
        if live_hash != b.base_content_hash:
            b.invalidated = True
            raise SpeculativeBranchInvalidated(
                f"branch {branch_id} base content drifted under stable pointer"
                f" {b.base_version}: {b.base_content_hash[:12]} -> {live_hash[:12]}"
            )
        b.committed = True


def reconcile(lineage: Lineage, branch_id: str) -> None:
    """Commit a branch, forcing revalidation if a sibling rollback touched its base."""
    b = lineage.branches[branch_id]
    if b.invalidated:
        raise SpeculativeBranchInvalidated(
            f"reconciliation blocked for {branch_id}: speculative precondition"
            f" invalidated by sibling rollback; re-execute tool calls on restored base"
        )
    lineage.commit(branch_id)


# --- trace of the observed failure ---
lin = Lineage()
lin.snapshots["v41"] = Snapshot("v41", b"auth_module_v1")
lin.parent_of["v41"] = None

a = Branch("A", "v41", lin.snapshots["v41"].content_hash())
b = Branch("B", "v41", lin.snapshots["v41"].content_hash())
c = Branch("C", "v41", lin.snapshots["v41"].content_hash())
for br in (a, b, c):
    lin.branches[br.branch_id] = br

# A speculatively writes v42a, then fails post-condition and is rolled back.
lin.snapshots["v42a"] = Snapshot("v42a", b"auth_module_refactored")
lin.parent_of["v42a"] = "v41"

# Rollback restores v41 but with content that was NOT the base B and C forked from
# (simulating leakage: the speculative write mutated the shared draft slot).
restored = Snapshot("v41", b"auth_module_refactored_partial")
invalidated = lin.rollback("v41", restored)  # -> ['A','B','C'] via content-hash check

# C's retrieval silently substituted the restored content; reconcile must catch it.
try:
    reconcile(lin, "C")
except SpeculativeBranchInvalidated as e:
    print("caught:", e)
