# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-optimistic-speculative-tool-call-execution-and-force-a-compensating-rollback-barrier.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-optimistic-speculative-tool-call-execution-and-force-a-compensating-rollback-barrier.warrant.json
# Markdown SHA-256:   174b6f842de2608df3eee6586ab581bfa7311c4ee86938d8b327e1812999e109
# Code AST SHA-256:   471e2045bc89664e00f9d4199ebdffe1e9646e57bf28678b7a2a36d07e44a13a
# Verified Classes:   SpeculationInvariantViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculationInvariantViolation(RuntimeError):
    """Raised when a speculative tool call is dispatched in violation of
    effect-independence, compensation ordering, or belief-invalidation parity."""
    pass


TOMBSTONE_CHANNEL = "context.tombstones"


def dispatch_speculative(predecessor, successor, orchestrator, ctx):
    # I1: successor arguments must not derive from predecessor's unconfirmed output
    if successor.args_derived_from(predecessor.output_schema):
        raise SpeculationInvariantViolation(
            f"successor {successor.name} consumes unconfirmed output of "
            f"{predecessor.name}; speculation illegal, serialize instead"
        )

    # I3: a delivery path for the rollback tombstone must exist in context
    if not orchestrator.has_channel(TOMBSTONE_CHANNEL):
        raise SpeculationInvariantViolation(
            f"no tombstone channel for {predecessor.name}; "
            "rollback would not invalidate agent belief"
        )

    # I4: successor must be idempotent or hold a dedup key across rollback
    if not (successor.is_idempotent or orchestrator.holds_dedup_key(successor)):
        raise SpeculationInvariantViolation(
            f"successor {successor.name} is non-idempotent and lacks dedup key; "
            "re-derivation after rollback would double-apply"
        )

    result = successor.invoke()
    if not predecessor.committed():
        # Two-write compensation: external effect AND belief tombstone.
        orchestrator.compensate(predecessor)          # external write
        orchestrator.emit(TOMBSTONE_CHANNEL, {       # belief write
            "retract": predecessor.id,
            "reason": "predecessor rolled back post-speculation",
        })
        # Barrier: no successor dispatch or re-plan until both acknowledged.
        orchestrator.await_ack(predecessor.id, TOMBSTONE_CHANNEL)
    return result
