# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-effects-that-were-committed-but-never-reconciled-against-the-intent-log.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-effects-that-were-committed-but-never-reconciled-against-the-intent-log.warrant.json
# Markdown SHA-256:   7dce58ca2834ae194a21801c680cf82c5674cd2885cfbfb6914ef0655c1f6a68
# Code AST SHA-256:   10dd0ef31395781f07fdc52cdba6ece3100c59a5d8293455ec167a2e8ab33a4f
# Verified Classes:   UnreconcilableSpeculationError, IdempotencyKeyMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnreconcilableSpeculationError(RuntimeError):
    """Raised when a speculative effect cannot be reconciled against durable intent."""
    pass


class IdempotencyKeyMismatch(UnreconcilableSpeculationError):
    """Key regenerated on resume differs from the key written before dispatch."""
    pass


def reconcile_pending(intent_log, provider) -> None:
    """
    Close the speculation gap: for every pending key, confirm the effect
    landed or is safe to (re)dispatch under the SAME key.

    Invariant enforced: each intent maps to exactly one idempotency key,
    and that key is durable before dispatch.
    """
    for intent in intent_log.iter_pending():
        durable_key = intent.idempotency_key
        if durable_key is None:
            # Key was never written before dispatch -> branch-local speculation.
            raise UnreconcilableSpeculationError(
                f"intent {intent.id} has no durable idempotency key; "
                f"speculative effect may have landed unrecorded"
            )

        regenerated = intent.derive_key_from_durable_intent()
        if regenerated != durable_key:
            raise IdempotencyKeyMismatch(
                f"intent {intent.id}: durable key {durable_key} != "
                f"regenerated {regenerated}; resume would duplicate effect"
            )

        lookup = provider.lookup_effect(durable_key)
        if lookup.state == "exists":
            intent_log.mark_committed(intent.id, effect_id=lookup.effect_id)
        elif lookup.state == "absent":
            provider.dispatch(intent.tool_call, idempotency_key=durable_key)
            intent_log.mark_dispatched(intent.id)
        else:
            # Provider cannot answer -> hard stop, do not retry blind.
            raise UnreconcilableSpeculationError(
                f"provider cannot resolve key {durable_key} for intent "
                f"{intent.id}; refusing to dispatch"
            )
