# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-branch-whose-read-set-was-invalidated-by-a-sibling-s-rollback-the-orphaned-write-hazard-in-parallel-plan-dra.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-branch-whose-read-set-was-invalidated-by-a-sibling-s-rollback-the-orphaned-write-hazard-in-parallel-plan-dra.warrant.json
# Markdown SHA-256:   58af95551080789446b34731175254c7abac3730821fb34a1e2aa38aed2a6880
# Code AST SHA-256:   8d37e42e0c0d2612d6188d1471bd1b4dc23ce01e79852d842fbe5c6ea83ffbe4
# Verified Classes:   GhostDependencyError, WriteRecord, SpeculativeStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GhostDependencyError(RuntimeError):
    """Raised when a speculative branch's read-set traces to a rolled-back sibling."""
    pass


class WriteRecord:
    def __init__(self, producer_branch: str, commit_epoch: int, value, version: int):
        self.producer_branch = producer_branch
        self.commit_epoch = commit_epoch          # monotonic; increments on COMMIT only
        self.value = value
        self.version = version                    # per-object; may be restored by rollback


class SpeculativeStore:
    def __init__(self):
        self._data: dict[str, WriteRecord] = {}
        self._rolled_back: set[str] = set()
        self._commit_epoch = 0

    def commit_epoch(self) -> int:
        return self._commit_epoch

    def write(self, branch: str, key: str, value, version: int) -> None:
        # Speculative writes carry the *current* commit epoch; they do not advance it.
        self._data[key] = WriteRecord(branch, self._commit_epoch, value, version)

    def read(self, key: str):
        rec = self._data.get(key)
        return (rec.value, rec.version, rec.producer_branch, rec.commit_epoch) if rec else (None, None, None, None)

    def rollback(self, branch: str, prior: dict[str, WriteRecord]) -> None:
        # Compensating rollback: restores prior value AND prior version token.
        # This is exactly what erases the evidence a naive validator relies on.
        self._rolled_back.add(branch)
        for key, rec in prior.items():
            self._data[key] = rec

    def commit(self) -> None:
        self._commit_epoch += 1


def validate_and_commit(store: SpeculativeStore, branch: str, read_set: dict[str, tuple]) -> None:
    base_epoch = read_set["__base_epoch__"]
    for key, (value, version, producer, epoch) in read_set.items():
        if key == "__base_epoch__":
            continue
        cur = store.read(key)
        cur_value, cur_version, cur_producer, cur_epoch = cur

        # (a) value/version check — necessary but NOT sufficient.
        if cur_version != version or cur_value != value:
            raise GhostDependencyError(
                f"branch {branch}: value/version drift on {key!r} "
                f"(expected v{version}, saw v{cur_version})"
            )
        # (b) lineage check — the invariant that catches compensating-rollback ghosts.
        if cur_producer in store._rolled_back:
            raise GhostDependencyError(
                f"branch {branch}: read-set key {key!r} produced by rolled-back "
                f"branch {cur_producer!r} — ghost dependency"
            )
        # (c) epoch check — catches transitive speculation beyond the base world.
        if cur_epoch > base_epoch:
            raise GhostDependencyError(
                f"branch {branch}: read-set key {key!r} written at commit_epoch "
                f"{cur_epoch} > base {base_epoch} — uncommitted lineage"
            )
    store.commit()
