# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-its-rollback-barrier-commits-and-what-breaks-when-the-barrier-is-a-shared-mut.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-its-rollback-barrier-commits-and-what-breaks-when-the-barrier-is-a-shared-mut.warrant.json
# Markdown SHA-256:   89fbb15d2316615b516ec9172f61f3330c040364347d84f7eec31a650866702e
# Code AST SHA-256:   2e7947e93705475ab1b9a062831c207148de8de344766eef00a6eb0a7b1dd72c
# Verified Classes:   UnobservedAbortViolation, EffectVisibility, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnobservedAbortViolation(RuntimeError):
    """Raised when a speculative branch attempts a clean rollback
    while one or more of its effects have already been observed."""
    pass


class EffectVisibility:
    ISOLATED = "ISOLATED"        # private delta, never visible to peers
    OBSERVABLE = "OBSERVABLE"    # shared resource, peers may read
    IRREVERSIBLE = "IRREVERSIBLE"  # external, cannot be recalled


class SpeculativeBranch:
    def __init__(self, branch_id: str):
        self.branch_id = branch_id
        self.effects = []  # list of (effect_id, visibility, observers:set, compensation)

    def emit_effect(self, effect_id: str, visibility: str, compensation=None):
        if visibility == EffectVisibility.IRREVERSIBLE and compensation is None:
            raise UnobservedAbortViolation(
                f"branch {self.branch_id}: irreversible effect {effect_id} "
                f"registered without a compensation handler"
            )
        self.effects.append(
            {"id": effect_id, "vis": visibility, "observers": set(), "comp": compensation}
        )

    def record_observation(self, effect_id: str, observer: str):
        for e in self.effects:
            if e["id"] == effect_id:
                e["observers"].add(observer)
                return
        raise UnobservedAbortViolation(
            f"branch {self.branch_id}: observation of unknown effect {effect_id}"
        )

    def abort(self) -> str:
        # Classify the abort before doing anything.
        observed = [e for e in self.effects if e["observers"]]
        irreversible_observed = [
            e for e in observed if e["vis"] == EffectVisibility.IRREVERSIBLE
        ]
        if irreversible_observed:
            # Cannot roll back; must commit forward and reconcile.
            return "COMMIT_FORWARD"
        if not observed:
            # Free abort: nothing escaped.
            self.effects.clear()
            return "CLEAN_ROLLBACK"
        # Compensating abort: run compensations in reverse emission order.
        for e in reversed(observed):
            if e["comp"] is None:
                raise UnobservedAbortViolation(
                    f"branch {self.branch_id}: observed effect {e['id']} "
                    f"has no compensation; abort cannot proceed cleanly"
                )
            e["comp"]()
        return "COMPENSATING_ABORT"
