# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-pre-executes-a-tool-call-whose-shadow-sandbox-commit-is-later-rejected-by-a-verification-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-pre-executes-a-tool-call-whose-shadow-sandbox-commit-is-later-rejected-by-a-verification-quorum.warrant.json
# Markdown SHA-256:   61ec19b27bfbd7e2b897312693024ffebffe402987b49b71a0bcccbaada80f3f
# Code AST SHA-256:   0ec064fe760382afb3dfbdda73fc483ddf0ce2947d4d725812429585cbf31e7b
# Verified Classes:   SpeculativeContextLeak, SpeculativeBuffer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeContextLeak(RuntimeError):
    """Raised when the reasoning loop dereferences an uncommitted speculative value."""
    pass


class SpeculativeBuffer:
    def __init__(self):
        self._pending = {}   # call_id -> value, readable only by commit-check
        self._committed = set()
        self._invalidated = set()

    def stage(self, call_id, value):
        self._pending[call_id] = value

    def read_for_commit_check(self, call_id):
        return self._pending.get(call_id)

    def commit(self, call_id):
        if call_id in self._invalidated:
            raise SpeculativeContextLeak(
                f"commit attempted on invalidated call {call_id}"
            )
        self._committed.add(call_id)
        return self._pending.pop(call_id)

    def invalidate_branch(self, call_id, dependents):
        self._invalidated.add(call_id)
        for dep in dependents:
            self._invalidated.add(dep)
            self._pending.pop(dep, None)
        self._pending.pop(call_id, None)


def reasoning_loop_read(buffer, call_id):
    if call_id not in buffer._committed:
        raise SpeculativeContextLeak(
            f"reasoning loop attempted to read uncommitted speculative value "
            f"{call_id}; quarantine violated, branch must be invalidated"
        )
    return buffer.read_for_commit_check(call_id)


def on_quorum_reject(buffer, call_id, dependents):
    buffer.invalidate_branch(call_id, dependents)
    # Force serial re-execution; do not surface as retryable error.
    return {"action": "serial_retry", "invalidated": [call_id, *dependents]}
