# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculatively-pre-executed-tool-call-when-its-effect-sandbox-diverges-from-the-committed-world-state.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculatively-pre-executed-tool-call-when-its-effect-sandbox-diverges-from-the-committed-world-state.warrant.json
# Markdown SHA-256:   5a6f0cbc3089d6deb16f95c77d487c8443ca05bb4d9595eaac66225e167f0726
# Code AST SHA-256:   31900630e71dd297cb951a9b8d8a60f74fc5e14e24af5848ef0c46e3a4cf191a
# Verified Classes:   WarrantClosureViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class WarrantClosureViolation(RuntimeError):
    """Raised when a speculative call would commit with an uncommitted warrant premise."""
    pass


def reconcile(speculations, committed_effects, warrant_graph, fence):
    """
    speculations: dict[id -> Speculation]
    committed_effects: dict[id -> bool]  # effect_replay_matches under `fence`
    warrant_graph: dict[id -> set[id]]   # ids of sibling conclusions cited in authorization
    fence: serialization handle; all reads below occur inside it
    """
    with fence:
        # Phase 1: effect-replay commit candidates.
        committed = {sid for sid, ok in committed_effects.items() if ok}

        # Phase 2: warrant-closure fixpoint. Remove any candidate whose
        # warrant set is not fully committed, until stable.
        changed = True
        while changed:
            changed = False
            for sid in list(committed):
                missing = warrant_graph.get(sid, set()) - committed
                if missing:
                    committed.discard(sid)
                    changed = True

        # Phase 3: verify the invariant; a violation is a bug, not a race.
        for sid in committed:
            missing = warrant_graph.get(sid, set()) - committed
            if missing:
                raise WarrantClosureViolation(
                    f"speculation {sid} committed with uncommitted warrant "
                    f"premises {sorted(missing)}"
                )

        aborted = set(speculations) - committed
        return {"commit": committed, "abort_and_redispatch": aborted}
