# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-speculative-commit-horizon-when-concurrent-branches-share-a-side-effecting-tool-and-how-does-a-late-rollback-poison-si.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-speculative-commit-horizon-when-concurrent-branches-share-a-side-effecting-tool-and-how-does-a-late-rollback-poison-si.warrant.json
# Markdown SHA-256:   2904337d01bed28ac9970a415d7d3b35f25ac4dac19d5adf80d5ccb8f950385d
# Code AST SHA-256:   aa91da1c321447facbd080e4ad8c6f984bd177dc503454a0f3b4503ea2db0600
# Verified Classes:   SpeculativeOwnershipViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeOwnershipViolation(RuntimeError):
    """Raised when a rollback would cancel an effect not exclusively owned
    by the branch being rolled back, or when a promotion would commit a
    branch whose effects have unresolved shared provenance."""


def rollback_branch(branch_id: str, ledger: dict) -> list:
    """Cancel effects owned by branch_id. Refuses to proceed if any effect
    attributed to the branch is a dedup alias of a live sibling branch."""
    cancelled = []
    for effect_id, record in ledger.items():
        if record["owner"] != branch_id:
            continue
        if record["provenance"] != branch_id:
            # Effect was deduplicated against a sibling's earlier call.
            # Deleting it would poison that sibling.
            raise SpeculativeOwnershipViolation(
                f"branch {branch_id} cannot roll back effect {effect_id}: "
                f"provenance is {record['provenance']}, a dedup alias of a "
                f"live sibling; downgrade to shared-retention instead"
            )
        cancelled.append(effect_id)
    return cancelled


def promote_branch(branch_id: str, ledger: dict) -> None:
    """Promote branch to committed only if every claimed effect has
    exclusive provenance or an explicit shared-retention record."""
    for effect_id, record in ledger.items():
        if record["owner"] != branch_id:
            continue
        if record["provenance"] != branch_id and not record.get("shared_retention"):
            raise SpeculativeOwnershipViolation(
                f"branch {branch_id} cannot be promoted: effect {effect_id} "
                f"has provenance {record['provenance']} with no shared-retention "
                f"record; commit would orphan the surviving owner's reference"
            )
