# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-execution-rollback-has-become-unreconcilable-in-a-multi-agent-pipeline.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-execution-rollback-has-become-unreconcilable-in-a-multi-agent-pipeline.warrant.json
# Markdown SHA-256:   d03956599c42bb2f2a761205a35ce9a860251339a434e18b05c1b37480d293d9
# Code AST SHA-256:   8f550e16ff5c0800f5c79a7cf691444c0172621886a0e633735a11181b9876e3
# Verified Classes:   UnreconcilableRollbackError, Effect
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class UnreconcilableRollbackError(RuntimeError):
    """Raised when a speculative branch's effect set cannot be fully inverted
    and the downstream contamination set cannot be safely bounded."""
    pass


@dataclass
class Effect:
    branch_id: str
    key: str
    compensable: bool
    consumers: set[str] = field(default_factory=set)


def reconcile_rollback(
    branch_id: str,
    effect_journal: list[Effect],
    revert_journal: set[str],
    committed_branches: set[str],
) -> list[str]:
    """Return the set of branch IDs that must be re-derived, or raise if
    the rollback is structurally unreconcilable."""
    branch_effects = [e for e in effect_journal if e.branch_id == branch_id]
    unreconciled = [e for e in branch_effects if e.key not in revert_journal]

    if not unreconciled:
        return []  # clean local rollback

    # Any non-compensable effect that escaped the revert journal is fatal:
    # we cannot invert it and cannot prove it did not propagate.
    for e in unreconciled:
        if not e.compensable:
            raise UnreconcilableRollbackError(
                f"branch {branch_id} emitted non-compensable effect {e.key!r} "
                f"outside revert journal; downstream contamination unbounded"
            )

    # BFS the consumer provenance graph. Any consumer with unknown commit
    # status makes the re-derivation set non-enumerable.
    downstream: set[str] = set()
    frontier = {c for e in unreconciled for c in e.consumers}
    while frontier:
        node = frontier.pop()
        if node in downstream:
            continue
        downstream.add(node)
        if node not in committed_branches:
            # Consumer is itself uncommitted and speculative: its own
            # effects may be interleaved with ours. Cannot safely replay.
            raise UnreconcilableRollbackError(
                f"branch {branch_id} rollback reaches uncommitted consumer "
                f"{node!r}; escalate to full re-derivation from global barrier"
            )
        frontier |= {c for e in effect_journal if e.branch_id == node for c in e.consumers}

    return sorted(downstream)
