# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-s-rollback-watermark-has-been-silently-invalidated-by-a-sibling-s-committed-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-s-rollback-watermark-has-been-silently-invalidated-by-a-sibling-s-committed-side-effect.warrant.json
# Markdown SHA-256:   53d393ff1030ebae845b79f6bb1543ab10e63faee702f274135d195e403813f9
# Code AST SHA-256:   2a8402cf0ba190f49afa1544c6fbcf20bc81a9a56958f34403deeb6776018a1f
# Verified Classes:   StaleRollbackWatermark, WriteRecord, Store, Watermark
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class StaleRollbackWatermark(RuntimeError):
    """Raised when a speculative branch's rollback watermark can no longer be
    applied without clobbering a sibling's committed write."""
    pass


@dataclass
class WriteRecord:
    key: str
    version: int
    writer: str          # branch id or watermark owner id
    committed: bool


@dataclass
class Store:
    version: int = 0
    # per-key ordered history of writes, newest last
    history: Dict[str, List[WriteRecord]] = field(default_factory=dict)

    def record(self, key: str, writer: str, committed: bool) -> int:
        self.version += 1
        self.history.setdefault(key, []).append(
            WriteRecord(key, self.version, writer, committed)
        )
        return self.version

    def last_committed_writer(self, key: str):
        for rec in reversed(self.history.get(key, [])):
            if rec.committed:
                return rec.writer
        return None


@dataclass
class Watermark:
    owner: str
    mint_version: int
    snapshot: Dict[str, object]   # key -> pre-image value at mint time


def safe_rollback(store: Store, wm: Watermark, branch_id: str,
                  branch_write_log: Set[str]) -> List[str]:
    """Apply a rollback ONLY over keys the branch itself wrote, and only if
    no sibling committed to those keys after the watermark was minted.

    Returns the list of keys actually restored. Raises if the watermark is
    structurally invalidated.
    """
    # Restore set must be actor-scoped, not watermark-diff-scoped.
    restore_set = set(wm.snapshot.keys()) & branch_write_log

    widened = set(wm.snapshot.keys()) - branch_write_log
    if widened:
        # Watermark diff includes keys this branch never wrote: sibling or
        # implicit writes. Applying would revert someone else's work.
        raise StaleRollbackWatermark(
            f"watermark {wm.owner}@{wm.mint_version} widened beyond branch "
            f"{branch_id} write log; offending keys={sorted(widened)}"
        )

    for key in restore_set:
        last = store.last_committed_writer(key)
        if last is None:
            continue
        if last not in (wm.owner, branch_id):
            # A sibling committed to this key after mint; watermark is
            # causally stale for this key.
            raise StaleRollbackWatermark(
                f"watermark {wm.owner}@{wm.mint_version} stale for key "
                f"'{key}': last committed writer is '{last}', not "
                f"'{wm.owner}' or '{branch_id}'"
            )

    for key in restore_set:
        store.record(key, writer=branch_id, committed=True)
    return sorted(restore_set)


def reconcile(store: Store, wm: Watermark, branch_id: str,
              branch_write_log: Set[str]) -> List[str]:
    try:
        return safe_rollback(store, wm, branch_id, branch_write_log)
    except StaleRollbackWatermark as exc:
        # Refuse the abort. Preserve sibling commits. Escalate.
        raise StaleRollbackWatermark(
            f"abort refused for branch {branch_id}; sibling commit preserved: {exc}"
        ) from exc
