# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-attribution-when-a-speculative-branch-is-replayed-after-a-sibling-branch-has-already-committed-its-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-attribution-when-a-speculative-branch-is-replayed-after-a-sibling-branch-has-already-committed-its-effects.warrant.json
# Markdown SHA-256:   35e3ae273494f95a056338950553507f3e0bac434e0fe940f84a8597cd44a2b4
# Code AST SHA-256:   be34f97219bfa81cd86834fdcc2461e14eceef0c0706dda70ba258026eee759b
# Verified Classes:   AttributionUnsafe, BranchTrace
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict


class AttributionUnsafe(RuntimeError):
    """Raised when a speculative branch cannot be causally replayed because a
    sibling commit mutated a resource the branch read before its first write."""


@dataclass
class BranchTrace:
    branch_id: str
    spawn_version: int
    reads: Dict[str, int] = field(default_factory=dict)   # resource -> version observed
    first_write_resource: str | None = None


def causal_replay(branch: BranchTrace, live_versions: Dict[str, int]) -> None:
    """Replay a branch only if every pre-write read is version-equivalent to spawn.

    Snapshot-free replay against a mutated world produces plausible but causally
    inverted traces; we must refuse rather than best-effort.
    """
    for resource, observed_version in branch.reads.items():
        current = live_versions.get(resource)
        if current != observed_version:
            raise AttributionUnsafe(
                f"branch {branch.branch_id!r} read {resource!r} at world_version "
                f"{observed_version}, but live world is at {current}; a sibling "
                f"commit interleaved. Refusing replay to avoid false attribution."
            )
    # Safe: reads are pinned to spawn state; proceed with replay.
    return None


def replay_or_fault(branch: BranchTrace, live_versions: Dict[str, int]) -> str:
    try:
        causal_replay(branch, live_versions)
        return "replayed"
    except AttributionUnsafe as exc:
        # Emit fault with offending resource; never emit a synthesized trace.
        return f"attribution_unsafe: {exc}"


if __name__ == "__main__":
    b = BranchTrace(branch_id="B", spawn_version=0, reads={"inventory:X": 0})
    # Sibling A committed inventory:X -> version 1; replay of B is now unsafe.
    print(replay_or_fault(b, live_versions={"inventory:X": 1}))
