# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branches-when-a-parent-agent-commits-a-rollback-mid-speculation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branches-when-a-parent-agent-commits-a-rollback-mid-speculation.warrant.json
# Markdown SHA-256:   6043d4975e388f18f0aaa08ad6bdf69a79edfdf4239fdf7632ee28a3c5d80e63
# Code AST SHA-256:   e0d5ebab8f3fa15e51835cd40dca0e3384f220fe1a74d0697cee13aa7d515bba
# Verified Classes:   SpeculationBaseInvalidated, Substrate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import FrozenSet


class SpeculationBaseInvalidated(RuntimeError):
    """Raised when a speculative child tries to commit against a tombstoned base version."""

    def __init__(self, child_id: str, base_version: int, head: int, tombstoned: FrozenSet[int]):
        self.child_id = child_id
        self.base_version = base_version
        self.head = head
        self.tombstoned = tombstoned
        super().__init__(
            f"child {child_id} base v{base_version} not live on lineage "
            f"(head=v{head}, tombstoned={sorted(tombstoned)})"
        )


@dataclass
class Substrate:
    head: int = 0
    generation: int = 0
    tombstoned: set[int] = field(default_factory=set)
    store: dict[str, object] = field(default_factory=dict)

    def rollback(self, to_version: int) -> None:
        # Tombstone every version above the rollback target and bump generation.
        for v in range(to_version + 1, self.head + 1):
            self.tombstoned.add(v)
        self.head = to_version
        self.generation += 1

    def apply(
        self,
        key: str,
        value: object,
        *,
        child_id: str,
        base_version: int,
        ancestor_set: FrozenSet[int],
        observed_generation: int,
    ) -> None:
        # Atomic re-check: generation, lineage, and ancestor liveness.
        if observed_generation != self.generation:
            raise SpeculationBaseInvalidated(
                child_id, base_version, self.head, frozenset(self.tombstoned)
            )
        if base_version in self.tombstoned or base_version not in self._ancestors(self.head):
            raise SpeculationBaseInvalidated(
                child_id, base_version, self.head, frozenset(self.tombstoned)
            )
        if any(a in self.tombstoned for a in ancestor_set):
            raise SpeculationBaseInvalidated(
                child_id, base_version, self.head, frozenset(self.tombstoned)
            )
        self.store[key] = value

    def _ancestors(self, version: int) -> set[int]:
        return set(range(0, version + 1))


def speculative_commit(
    substrate: Substrate,
    child_id: str,
    key: str,
    value: object,
    base_version: int,
    ancestor_set: FrozenSet[int],
    observed_generation: int,
) -> None:
    try:
        substrate.apply(
            key,
            value,
            child_id=child_id,
            base_version=base_version,
            ancestor_set=ancestor_set,
            observed_generation=observed_generation,
        )
    except SpeculationBaseInvalidated:
        # Orphaned speculation: surface to orchestrator, do not retry blindly.
        raise
    # If we reach here without raising, the write is lineage-valid.
