# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-cache-poisoning-from-committing-divergent-side-effects-across-a-consensus-committed-agent-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-cache-poisoning-from-committing-divergent-side-effects-across-a-consensus-committed-agent-swarm.warrant.json
# Markdown SHA-256:   fb510420e1197d23ccdf5feed7c7eee1a55e955caf3233e02bc5960970efe24b
# Code AST SHA-256:   23a3bbf4e61ff42e2bccb4ebc1b312406087b3c59612f8f5374bc78a8bd633e9
# Verified Classes:   SpeculativeCommitDivergence, QuarantineViolation, ResultEnvelope, SpeculativeCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class SpeculativeCommitDivergence(RuntimeError):
    """Raised when a speculative cache entry would commit an envelope that
    diverges in effect from other speculative results for the same logical call."""
    pass


class QuarantineViolation(RuntimeError):
    """Raised when a branch attempts to emit a side effect while its
    dependency is still provisional (uncommitted)."""
    pass


@dataclass
class ResultEnvelope:
    status: str
    tx_id: str | None
    replica_id: str
    replica_epoch: int

    def digest(self) -> str:
        payload = json.dumps(
            {"status": self.status, "tx_id": self.tx_id}, sort_keys=True
        )
        return hashlib.sha256(payload.encode()).hexdigest()

    def effect_key(self) -> str:
        # Two OK envelopes with different tx_ids are effect-equivalent;
        # OK vs ALREADY_CHARGED are not.
        return self.status


@dataclass
class SpeculativeCache:
    entries: dict[str, list[ResultEnvelope]] = field(default_factory=dict)
    committed: dict[str, ResultEnvelope] = field(default_factory=dict)

    def key(self, tool: str, args: dict, idem: str) -> str:
        return hashlib.sha256(
            json.dumps({"t": tool, "a": args, "i": idem}, sort_keys=True).encode()
        ).hexdigest()

    def record(self, key: str, env: ResultEnvelope) -> None:
        self.entries.setdefault(key, []).append(env)

    def reconcile_and_commit(self, key: str) -> ResultEnvelope:
        candidates = self.entries.get(key, [])
        if not candidates:
            raise SpeculativeCommitDivergence(f"no speculative results for {key}")

        effects = {c.effect_key() for c in candidates}
        if len(effects) > 1:
            # Divergent effect: must escalate to serialized reconciliation.
            raise SpeculativeCommitDivergence(
                f"effect divergence for {key}: {sorted(effects)}; "
                f"envelopes={[c.digest()[:8] for c in candidates]}"
            )

        # Effect-equivalent but possibly envelope-divergent: pick highest epoch,
        # and this choice MUST be broadcast to all branches before dependents emit.
        winner = max(candidates, key=lambda c: c.replica_epoch)
        self.committed[key] = winner
        return winner

    def assert_committed(self, key: str, branch_key: str) -> ResultEnvelope:
        if key not in self.committed:
            raise QuarantineViolation(
                f"branch {branch_key} tried to emit dependent side effect on "
                f"provisional result {key}"
            )
        return self.committed[key]


def emit_compensation(cache: SpeculativeCache, key: str, branch_key: str,
                      tx_id: str) -> str:
    env = cache.assert_committed(key, branch_key)
    if env.tx_id != tx_id:
        raise SpeculativeCommitDivergence(
            f"branch {branch_key} compensating tx {tx_id} but committed tx is "
            f"{env.tx_id}; branch re-anchor required"
        )
    return f"refund:{tx_id}"
