# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-optimistic-speculative-write-during-multi-agent-baton-passing-and-how-does-the-conflict-resolving-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-optimistic-speculative-write-during-multi-agent-baton-passing-and-how-does-the-conflict-resolving-commit.warrant.json
# Markdown SHA-256:   df4a6e4c18f800d6d5627604fe4f29361902923c2765168d66d9ba2ef92abccf
# Code AST SHA-256:   2906c439e4b69a0242eb18699d45b07a14a8f3e70912cca8722ce46d6bcc88c3
# Verified Classes:   ProvenanceLaunderingError, GhostAncestryError, Version, SpeculativeWrite
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a speculative write claims a committed base its content was not derived from."""


class GhostAncestryError(ProvenanceLaunderingError):
    """Raised when provenance names a version that was rolled back / never committed."""


@dataclass
class Version:
    id: str
    content: bytes
    committed: bool


@dataclass
class SpeculativeWrite:
    result_hash: str
    provenance: dict          # version_id -> content_hash at read time
    side_effects_fired: bool
    read_fields: set = field(default_factory=set)


def _hash(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def commit_or_reject(write: SpeculativeWrite, store: dict, committed_head: str) -> str:
    # C2: ghost ancestry — any provenance version must be committed.
    ghosts = [v for v in write.provenance if v not in store or not store[v].committed]
    if ghosts:
        raise GhostAncestryError(
            f"provenance names uncommitted/rolled-back versions {ghosts}; "
            f"rebase is unsound, re-execute from {committed_head}"
        )

    # C1: provenance integrity — claimed base must hash-match the committed content.
    for vid, claimed in write.provenance.items():
        actual = _hash(store[vid].content)
        if claimed != actual:
            raise ProvenanceLaunderingError(
                f"provenance for {vid} claims {claimed[:12]} but committed content is "
                f"{actual[:12]}; content was not derived from claimed base"
            )

    # Non-idempotent side effects on a stale base cannot be rebased safely.
    if write.side_effects_fired and committed_head != max(write.provenance, default=committed_head):
        raise ProvenanceLaunderingError(
            "side effects fired against non-head base; rebase would double-fire; "
            "reject and compensate"
        )

    return write.result_hash


if __name__ == "__main__":
    store = {
        "v6": Version("v6", b'{"plan": "alpha"}', committed=True),
        "v7": Version("v7", b'{"plan": "beta"}', committed=False),  # rolled back
    }
    # E speculatively derived from v7, then rebase re-stamped provenance to v6.
    forged = SpeculativeWrite(
        result_hash="deadbeef",
        provenance={"v6": _hash(b'{"plan": "beta"}')},  # hash of v7 content, labeled v6
        side_effects_fired=True,
    )
    commit_or_reject(forged, store, committed_head="v6")  # raises ProvenanceLaunderingError
