# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-branch-reconciliation-when-a-divergent-side-effect-has-escaped-the-rollback-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-branch-reconciliation-when-a-divergent-side-effect-has-escaped-the-rollback-envelope.warrant.json
# Markdown SHA-256:   765cb16769063e6d14004565a2fa56e346815b8dda3ddd077652d03e3c91b51f
# Code AST SHA-256:   59b99574c3a88f7e517393ee586125e5fc35816208d136a27ed5763e50a1796b
# Verified Classes:   UnsoundRollbackError, EffectKind
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsoundRollbackError(RuntimeError):
    """Raised when a losing branch's effects escaped the rollback envelope."""

    def __init__(self, branch_id: str, reason: str, escaped_effects: list[str]):
        self.branch_id = branch_id
        self.reason = reason
        self.escaped_effects = escaped_effects
        super().__init__(
            f"branch {branch_id} rollback unsound: {reason}; "
            f"escaped effects: {escaped_effects}"
        )


class EffectKind:
    CONTAINED = "contained"
    OUTBOUND_IRREVERSIBLE = "outbound_irreversible"
    IN_PLACE_UNSNAPSHOTTED = "in_place_unsnapshotted"


def reconcile_speculative_branches(
    branches: dict[str, list[dict]],
    winner_id: str,
) -> str:
    """
    branches: branch_id -> list of effect records, each:
        {"kind": EffectKind.*, "resource_id": str | None, "prior_state": dict | None}
    Returns the decision: "rollback" | "escalate" | "reconcile_with_repair" | "reorder_rollbacks".
    """
    for branch_id, effects in branches.items():
        if branch_id == winner_id:
            continue

        outbound = [e for e in effects if e["kind"] == EffectKind.OUTBOUND_IRREVERSIBLE]
        unsnapshotted = [
            e for e in effects if e["kind"] == EffectKind.IN_PLACE_UNSNAPSHOTTED
        ]
        unclassified = [
            e for e in effects
            if e["kind"] not in (
                EffectKind.CONTAINED,
                EffectKind.OUTBOUND_IRREVERSIBLE,
                EffectKind.IN_PLACE_UNSNAPSHOTTED,
            )
        ]

        if unclassified:
            raise UnsoundRollbackError(
                branch_id,
                "unclassified effect; containment unknown",
                [e.get("resource_id", "?") for e in unclassified],
            )

        if unsnapshotted:
            # Compensation would delete rather than restore; worse than doing nothing.
            raise UnsoundRollbackError(
                branch_id,
                "in-place mutation without prior-state snapshot",
                [e["resource_id"] for e in unsnapshotted],
            )

        if outbound:
            # Rollback cannot retract an emitted event; must repair against it.
            return "reconcile_with_repair"

    # Cross-branch precondition check (C4) omitted for brevity; if it fails,
    # return "reorder_rollbacks" instead of "rollback".
    return "rollback"
