# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-rollback-invalidation-when-optimistic-concurrency-merges-silently-overwrite-sibling-writes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-rollback-invalidation-when-optimistic-concurrency-merges-silently-overwrite-sibling-writes.warrant.json
# Markdown SHA-256:   6713fc75f810d4b091fc8bd274a4f4824f281f48e8176248e9ee701b38cf26a2
# Code AST SHA-256:   ba0aa3859b2a1796119a7ada1177e7efb87166adca59aafc3e4fd06fff7cf3d4
# Verified Classes:   SpeculationWitnessError, SpeculativeWrite, MergeResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Literal

Disposition = Literal["applied", "superseded", "rewritten", "absent"]


class SpeculationWitnessError(RuntimeError):
    """Raised when a speculative write's witness fails to re-derive against merged state."""


@dataclass
class SpeculativeWrite:
    call_id: str
    region: str                      # content-addressable region, e.g. "fileB:line42:user_id"
    expected_value: str              # the value the agent intends to be present post-merge
    witness: Callable[[dict], bool]  # re-derivable predicate over merged state


@dataclass
class MergeResult:
    state: dict
    dispositions: dict[str, Disposition]   # call_id -> disposition
    resolution_log: list[str] = field(default_factory=list)


def verify_speculation(
    writes: list[SpeculativeWrite],
    merge: MergeResult,
    *,
    reconciler_is_probabilistic: bool = False,
) -> None:
    """
    Post-merge witness check. Must run before any completion assertion.
    Raises SpeculationWitnessError on the first unverifiable witness.
    """
    for w in writes:
        disp = merge.dispositions.get(w.call_id, "absent")

        if disp == "rewritten":
            # A reconciler mutated this write's effect (or a sibling's).
            # Witness cannot be trusted even if it currently evaluates true,
            # because the reconciler may have altered sibling state we cannot see.
            raise SpeculationWitnessError(
                f"call {w.call_id}: reconciler rewrote region {w.region}; "
                f"completion assertion invalid, sibling invalidation required"
            )

        if disp == "superseded":
            # Our write lost to a sibling. That may be correct, but we cannot
            # claim completion for this region.
            raise SpeculationWitnessError(
                f"call {w.call_id}: superseded on {w.region}; "
                f"re-enumerate region and re-issue or escalate to serialized"
            )

        if disp == "absent":
            raise SpeculationWitnessError(
                f"call {w.call_id}: merge layer returned no disposition for {w.region}; "
                f"cannot distinguish dropped-write from never-applied"
            )

        if not w.witness(merge.state):
            raise SpeculationWitnessError(
                f"call {w.call_id}: witness failed to re-derive on {w.region} "
                f"(expected {w.expected_value!r}); merged state does not contain our effect"
            )

        if reconciler_is_probabilistic and w.region in merge.state:
            # Belt-and-suspenders: probabilistic reconcilers can mutate sibling
            # writes in the same region without emitting a 'rewritten' disposition.
            # Force a full re-read of the region against the pre-merge enumeration.
            raise SpeculationWitnessError(
                f"call {w.call_id}: probabilistic reconciler touched {w.region}; "
                f"full post-merge re-read required before completion"
            )


# Example invocation that triggers the guard:
if __name__ == "__main__":
    writes = [
        SpeculativeWrite(
            call_id="rename-B",
            region="fileB:user_id",
            expected_value="account_id",
            witness=lambda s: "user_id" not in s.get("fileB", ""),
        )
    ]
    merged = MergeResult(
        state={"fileB": "account_id = 1\nuser_id = 2\n"},  # auditor's insert survived
        dispositions={"rename-B": "rewritten"},
        resolution_log=["theirs-wins on overlap at fileB:user_id"],
    )
    try:
        verify_speculation(writes, merged, reconciler_is_probabilistic=True)
    except SpeculationWitnessError as e:
        print(f"BLOCKED completion: {e}")
