# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-consensus-log-ordering-with-local-wall-clock-ordering-when-heterogeneous-agent-runtimes-share-memory-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-consensus-log-ordering-with-local-wall-clock-ordering-when-heterogeneous-agent-runtimes-share-memory-state.warrant.json
# Markdown SHA-256:   3fbb8f00951dfeba52ce4533fc6773319e649eb0cb968b16dd17434fae38a9a6
# Code AST SHA-256:   2fb46e456dc0060c7047ebb5269d1fe6be0ec22965299b33a000ac828ee8bbff
# Verified Classes:   ObservationOrderViolation, IndexedStateView
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ObservationOrderViolation(RuntimeError):
    """Raised when a runtime attempts to act on a state transition whose
    log index is not the maximum it has observed, i.e. when local
    observation order disagrees with consensus log order."""
    pass


class IndexedStateView:
    """A view of shared memory that refuses to let application logic act on
    out-of-order observations. All staleness decisions are keyed on log index,
    never on wall-clock or arrival order."""

    def __init__(self, runtime_id: str):
        self.runtime_id = runtime_id
        self.max_observed_index = -1
        self.local_state = None

    def observe(self, log_index: int, state):
        # Record the highest index this runtime has ordered, regardless of
        # the order in which observations arrive from the transport.
        if log_index > self.max_observed_index:
            self.max_observed_index = log_index
            self.local_state = state

    def act_on(self, log_index: int, action: str):
        # A runtime may only act on the transition it believes is current IF
        # that transition is the maximum it has ordered. Acting on an earlier
        # index after a later one has been observed is the phantom-write bug.
        if log_index < self.max_observed_index:
            raise ObservationOrderViolation(
                f"runtime {self.runtime_id} attempted '{action}' on index "
                f"{log_index} after already ordering index "
                f"{self.max_observed_index}; refusing to act on a "
                f"superseded observation"
            )
        if log_index > self.max_observed_index:
            raise ObservationOrderViolation(
                f"runtime {self.runtime_id} attempted '{action}' on index "
                f"{log_index} which it has not yet ordered "
                f"(max ordered = {self.max_observed_index}); re-read from "
                f"consensus before acting"
            )
        return self.local_state
