# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-rollback-when-a-sibling-branch-s-committed-writes-intersect-its-own-speculative-read-set.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-rollback-when-a-sibling-branch-s-committed-writes-intersect-its-own-speculative-read-set.warrant.json
# Markdown SHA-256:   c1e80e39415162786fea1cb1528866abff201e6c106080fa5c9342075a7d86e0
# Code AST SHA-256:   d7e9f5e6e3826138f03afec876655e66a57fca4600edb8d0472f5054863f6c0f
# Verified Classes:   SpeculativeRollbackUnsafe, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeRollbackUnsafe(RuntimeError):
    """Raised when a speculative branch cannot be safely rolled back because
    its read-set was invalidated by a sibling commit or it emitted live side effects."""
    pass


class Branch:
    def __init__(self, branch_id, read_set, write_set, side_effects):
        self.branch_id = branch_id
        self.read_set = read_set          # dict: key -> version observed
        self.write_set = write_set        # dict: key -> value
        self.side_effects = side_effects  # list of emitted external actions


def reconcile(branch: Branch, shared_versions: dict, sibling_commits: dict):
    # sibling_commits: key -> version committed by any sibling since branch start
    dirty_keys = [
        k for k, v in branch.read_set.items()
        if k in sibling_commits and sibling_commits[k] > v
    ]

    if dirty_keys and branch.side_effects:
        raise SpeculativeRollbackUnsafe(
            f"branch {branch.branch_id} cannot be rolled back: read-set invalidated "
            f"on {dirty_keys} by sibling commits, and "
            f"{len(branch.side_effects)} live side effect(s) already emitted. "
            f"Quarantine required; rollback would orphan external actions."
        )

    if dirty_keys:
        # No side effects: safe to re-derive from current state, not roll back.
        return {"action": "re_derive", "stale_keys": dirty_keys}

    # Read-set clean: commit is safe.
    for k, v in branch.write_set.items():
        shared_versions[k] = shared_versions.get(k, 0) + 1
    return {"action": "commit", "committed": list(branch.write_set)}
