# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-branch-only-to-replay-it-into-the-same-poisoned-state-idempotency-key-aliasing-across-speculative-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-branch-only-to-replay-it-into-the-same-poisoned-state-idempotency-key-aliasing-across-speculative-forks.warrant.json
# Markdown SHA-256:   45ca7c27ba884e27b47891be70e308fdfbd8147c2a1f437a9a4ba1bd46baedf6
# Code AST SHA-256:   58c1fcc75365760c41c60ee1e0b4877a09847b6cdda641d401c5fff1821a7112
# Verified Classes:   SpeculativeEffectAliasingError, Branch, EffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SpeculativeEffectAliasingError(RuntimeError):
    """Raised when a side-effecting tool call on a speculative branch would
    alias its idempotency key with a sibling branch's effect."""
    pass


@dataclass
class Branch:
    branch_id: str
    committed: bool = False


@dataclass
class EffectLedger:
    # key -> (branch_id, record_id)
    _cache: dict = field(default_factory=dict)

    def commit(self, key: str, branch_id: str, record_id: str) -> None:
        self._cache[key] = (branch_id, record_id)

    def lookup(self, key: str) -> Optional[tuple]:
        return self._cache.get(key)


def derive_key(task_id: str, branch_id: str, step: int, lineage_keyed: bool) -> str:
    if lineage_keyed:
        raw = f"{task_id}::{branch_id}::{step}"
    else:
        raw = f"{task_id}::{step}"
    return hashlib.sha256(raw.encode()).hexdigest()


def guarded_write(
    ledger: EffectLedger,
    task_id: str,
    branch: Branch,
    step: int,
    winning_branch_id: str,
    lineage_keyed: bool,
    payload: dict,
) -> str:
    """Perform a side-effecting write under reconciliation guardrails.

    Raises if the call is made on an uncommitted non-winning branch under
    prefix-keying, or if the dedup cache returns an effect authored by a
    different branch than the caller.
    """
    if not lineage_keyed and not branch.committed and branch.branch_id != winning_branch_id:
        raise SpeculativeEffectAliasingError(
            f"branch {branch.branch_id} attempted side-effecting write at step {step} "
            f"under prefix-keying while uncommitted; effect would alias winner {winning_branch_id}"
        )

    key = derive_key(task_id, branch.branch_id, step, lineage_keyed)
    prior = ledger.lookup(key)

    if prior is not None:
        author_branch, record_id = prior
        if author_branch != branch.branch_id:
            raise SpeculativeEffectAliasingError(
                f"dedup hit for key {key[:12]} authored by branch {author_branch} "
                f"but requested by branch {branch.branch_id}; refusing foreign effect"
            )
        return record_id

    record_id = f"rec_{hashlib.sha256(str(payload).encode()).hexdigest()[:6]}"
    ledger.commit(key, branch.branch_id, record_id)
    return record_id


if __name__ == "__main__":
    ledger = EffectLedger()
    winner = Branch("A", committed=True)
    loser = Branch("B", committed=False)

    # Loser emits first under prefix-keying -> must be blocked by guardrail.
    try:
        guarded_write(ledger, "task-1", loser, step=0, winning_branch_id="A",
                      lineage_keyed=False, payload={"schema": "v2", "x": 1})
    except SpeculativeEffectAliasingError as e:
        print("blocked:", e)

    # Winner writes cleanly.
    rid = guarded_write(ledger, "task-1", winner, step=0, winning_branch_id="A",
                        lineage_keyed=False, payload={"schema": "v1", "x": 1})
    print("winner record:", rid)
