# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-reconcile-a-speculative-branch-after-a-sibling-branch-s-rollback-has-already-mutated-shared-external-stat.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-reconcile-a-speculative-branch-after-a-sibling-branch-s-rollback-has-already-mutated-shared-external-stat.warrant.json
# Markdown SHA-256:   c5f2716c19abc692c153dfd2c72c97a4c51fb4d8fe3b52e707e1739b97c9ebb7
# Code AST SHA-256:   ab19674604709dc4e87ea1bbfd6547650ad7f2e893205367b870a79668a49683
# Verified Classes:   SpeculativeReconciliationError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeReconciliationError(RuntimeError):
    """Raised when a speculative branch cannot be reconciled because a
    sibling observed an effect that a rolled-back branch has retracted."""
    pass


class Branch:
    def __init__(self, name, write_set, read_set, invertible_surfaces):
        self.name = name
        self.write_set = write_set          # {surface: timestamp}
        self.read_set = read_set            # {surface: timestamp}
        self.invertible_surfaces = invertible_surfaces


def reconcile(rolled_back, survivors, budget_remaining, rederive_cost):
    """Attempt to reconcile survivors after `rolled_back` was aborted.

    Enforces the causal-consistency invariant: no live sibling may be
    reconciled if its read-set intersects a non-invertible write by the
    rolled-back branch that occurred before the sibling's read.
    """
    contaminated = []
    for sib in survivors:
        for surface, write_ts in rolled_back.write_set.items():
            read_ts = sib.read_set.get(surface)
            if read_ts is None:
                continue
            if read_ts > write_ts and surface not in rolled_back.invertible_surfaces:
                contaminated.append((sib.name, surface, write_ts, read_ts))

    if contaminated:
        if rederive_cost > budget_remaining:
            raise SpeculativeReconciliationError(
                f"cannot reconcile: {len(contaminated)} sibling(s) observed "
                f"retracted non-invertible effects and re-derivation cost "
                f"{rederive_cost} exceeds remaining budget {budget_remaining}; "
                f"contamination={contaminated}"
            )
        return {"action": "rederive", "targets": [c[0] for c in contaminated],
                "charge": rederive_cost}

    return {"action": "reconcile", "targets": [s.name for s in survivors]}
