# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-outcome-that-a-sibling-agent-will-later-contradict.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-outcome-that-a-sibling-agent-will-later-contradict.warrant.json
# Markdown SHA-256:   b3f290398aaee7dda29305456bd608a493ba4432d13134ed32cdd9cb66d4281f
# Code AST SHA-256:   b3267d864a95e8d9ff22718f3170e7ec8626da0781a648531c27145c2ee0a59e
# Verified Classes:   SpeculativeRollbackViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeRollbackViolation(RuntimeError):
    """Raised when rollback of a provisional outcome would leave a dependent
    branch's committed state inconsistent (read-provenance not re-validated)."""
    pass


def rollback_outcome(outcome_id, store, dependents):
    # dependents: list of committed outcomes, each with a read_set of
    # (record_id, version) pairs consumed before commit.
    rolled_back = store.get(outcome_id)
    if rolled_back is None:
        raise SpeculativeRollbackViolation(
            f"outcome {outcome_id} already rolled back; double-rollback indicates "
            f"reconciler re-entry without idempotency guard"
        )

    # Find dependents that read the provisional record at the version being rolled back.
    affected = [
        d for d in dependents
        if (outcome_id, rolled_back.version) in d.read_set
    ]

    for dep in affected:
        if dep.has_irreversible_effect:
            # Cannot roll back a branch that already acted on the provisional value.
            raise SpeculativeRollbackViolation(
                f"dependent {dep.id} performed irreversible external effect after "
                f"reading provisional {outcome_id}@{rolled_back.version}; "
                f"neither cascading rollback nor re-validation is safe — escalate"
            )
        if not dep.replayable:
            raise SpeculativeRollbackViolation(
                f"dependent {dep.id} read provisional {outcome_id}@{rolled_back.version} "
                f"but is not replayable from its recorded read_set; "
                f"committed state would be inconsistent after rollback"
            )

    store.remove(outcome_id)
    for dep in affected:
        dep.invalidate()  # schedule re-validation with substituted winner
    return affected
