# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-write-span-as-committed-only-after-the-write-is-durably-observable-to-a-later-read-span-rather-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-write-span-as-committed-only-after-the-write-is-durably-observable-to-a-later-read-span-rather-t.warrant.json
# Markdown SHA-256:   0b0137325143b9a29b76360174fc9951e72fb25527aa5bcbac740b1ffcd4c09e
# Code AST SHA-256:   22b51e07cf548ed202e4725ce6c27978ab741621f0a1f60a05ce329b26b95a64
# Verified Classes:   MemoryCommitViolation, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class MemoryCommitViolation(RuntimeError):
    """Raised when a write span is treated as committed without an observing read span."""
    pass


@dataclass
class Span:
    name: str
    start: float
    end: Optional[float] = None
    status: str = "UNSET"
    payload_hash: Optional[str] = None
    observed_hashes: tuple = ()


def payload_hash(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()


def assert_committed(
    write_span: Span,
    read_span: Span,
    backend_p99_index_lag_s: float,
) -> None:
    if write_span.status != "OK":
        raise MemoryCommitViolation(f"write span {write_span.name} not OK: {write_span.status}")
    if read_span.start - write_span.end < backend_p99_index_lag_s:
        raise MemoryCommitViolation(
            f"read opened {read_span.start - write_span.end:.3f}s after write end, "
            f"below p99 index lag {backend_p99_index_lag_s:.3f}s; "
            f"result is INCONCLUSIVE, not ABSENT"
        )
    if write_span.payload_hash not in read_span.observed_hashes:
        raise MemoryCommitViolation(
            f"write payload_hash {write_span.payload_hash[:12]} not observed by read; "
            f"stale or unindexed — do not branch on this read"
        )


def commit_barrier(write_span: Span, probe_read: Span, lag: float) -> None:
    assert_committed(write_span, probe_read, lag)
    write_span.status = "COMMITTED"
