# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-branch-when-its-rollback-journal-is-not-causally-closed-across-peer-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-branch-when-its-rollback-journal-is-not-causally-closed-across-peer-agents.warrant.json
# Markdown SHA-256:   da2681007be7be6399d8b6dfbd75d6462a8e507870de06766cb74eb3380af044
# Code AST SHA-256:   f15d7fe41105f5d8d76b78e70480c6b53626b319f37d8bf6bb4b770d85360923
# Verified Classes:   CausallyOpenRollbackError, SpeculatorJournal
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CausallyOpenRollbackError(RuntimeError):
    """Raised when a speculative branch's journal is compensable but not causally closed."""
    pass


class SpeculatorJournal:
    def __init__(self, speculator_id: str):
        self.speculator_id = speculator_id
        self.writes = []          # (key, old_value, new_value)
        self.read_edges = []      # (peer_id, key) observed reads of our writes

    def record_write(self, key: str, old, new, key_class: str):
        self.writes.append({"key": key, "old": old, "new": new, "class": key_class})

    def record_peer_read(self, peer_id: str, key: str):
        self.read_edges.append((peer_id, key))

    def assert_rollback_safe(self):
        """A branch may roll back only if every SHARED write was never observed,
        or every observing peer's derived writes are journaled and compensable."""
        for w in self.writes:
            if w["class"] != "SHARED":
                continue
            observers = [peer for (peer, k) in self.read_edges if k == w["key"]]
            if observers:
                raise CausallyOpenRollbackError(
                    f"speculator {self.speculator_id} wrote SHARED key {w['key']!r} "
                    f"observed by peers {observers} before commit; journal is "
                    f"compensable but not causally closed — abort branch before first write"
                )


def fork_speculative_branch(journal: SpeculatorJournal, planned_writes):
    for key, old, new, key_class in planned_writes:
        journal.record_write(key, old, new, key_class)
        # Admission check runs on the first SHARED write, before side effect lands.
        journal.assert_rollback_safe()
    return journal
