# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-pre-fetch-contamination-when-a-speculative-tool-execution-commits-side-effects-before-its-parent-hypothesis-is.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-pre-fetch-contamination-when-a-speculative-tool-execution-commits-side-effects-before-its-parent-hypothesis-is.warrant.json
# Markdown SHA-256:   e59b49afd600b7990e2a25b8234fab397e2672d3e009f45f65e72e4546c6c3fa
# Code AST SHA-256:   4827a7d4eb8b26be0e3f3619abe8922bf38e5e5b05a93702b2717e941f299feb
# Verified Classes:   EffectClass, SpeculationContamination, Effect, PlanGraph, Ledgers
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Optional


class EffectClass(Enum):
    READ = "read"
    STAGED_WRITE = "staged_write"
    WRITE = "write"  # must never be speculatively executed


class SpeculationContamination(RuntimeError):
    """Raised when a real-ledger effect has no committed plan node parent,
    or a write-class tool was speculatively fired without quarantine."""


@dataclass
class Effect:
    effect_id: str
    tool: str
    resource_id: str
    parent_node_id: Optional[str]
    hypothesis_hash: str
    effect_class: EffectClass
    staged: bool


@dataclass
class PlanGraph:
    committed_nodes: Dict[str, str] = field(default_factory=dict)  # node_id -> hypothesis_hash

    def commit(self, node_id: str, hypothesis_hash: str) -> None:
        self.committed_nodes[node_id] = hypothesis_hash

    def is_live(self, hypothesis_hash: str) -> bool:
        return hypothesis_hash in self.committed_nodes.values()


@dataclass
class Ledgers:
    quarantine: Dict[str, Effect] = field(default_factory=dict)
    real: Dict[str, Effect] = field(default_factory=dict)

    def stage(self, eff: Effect) -> None:
        if eff.effect_class is EffectClass.WRITE and not eff.staged:
            raise SpeculationContamination(
                f"write-class tool {eff.tool!r} fired speculatively without quarantine"
            )
        self.quarantine[eff.effect_id] = eff

    def promote(self, effect_id: str, plan: PlanGraph) -> None:
        eff = self.quarantine.get(effect_id)
        if eff is None:
            raise SpeculationContamination(f"promote of unknown effect {effect_id!r}")
        if eff.hypothesis_hash not in plan.committed_nodes.values():
            raise SpeculationContamination(
                f"cannot promote {effect_id!r}: hypothesis {eff.hypothesis_hash} not committed"
            )
        self.real[effect_id] = self.quarantine.pop(effect_id)

    def abort_stale(self, plan: PlanGraph) -> int:
        stale = [eid for eid, e in self.quarantine.items()
                 if not plan.is_live(e.hypothesis_hash)]
        for eid in stale:
            del self.quarantine[eid]
        return len(stale)

    def assert_no_orphans(self, plan: PlanGraph) -> None:
        for eid, eff in self.real.items():
            if eff.parent_node_id is None or eff.parent_node_id not in plan.committed_nodes:
                raise SpeculationContamination(
                    f"real-ledger effect {eid!r} ({eff.tool} on {eff.resource_id}) "
                    f"has parent {eff.parent_node_id!r} absent from committed plan graph"
                )


def h(tool: str, args: str) -> str:
    return hashlib.sha256(f"{tool}|{args}".encode()).hexdigest()[:16]


def reconcile(plan: PlanGraph, ledgers: Ledgers) -> None:
    ledgers.abort_stale(plan)
    ledgers.assert_no_orphans(plan)
