# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reconcile-a-trace-s-span-clock-against-its-memory-op-wall-clock-before-trusting-a-correlated-incident-timeline.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reconcile-a-trace-s-span-clock-against-its-memory-op-wall-clock-before-trusting-a-correlated-incident-timeline.warrant.json
# Markdown SHA-256:   bb23083741a7621e6b669c7a9743432c7d679925a6334f60764e264f921444f7
# Code AST SHA-256:   3f490f44bfccbaaab190fedf9960ae24278a6cc6916591ac04059ff1e1846c41
# Verified Classes:   CorrelationOrderingError, MemoryEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CorrelationOrderingError(RuntimeError):
    """Raised when a correlation engine attempts to order events that are
    concurrent under the system's commit-lag resolution floor."""


@dataclass
class MemoryEvent:
    kind: str                       # "write" | "retrieve"
    span_ts: float                  # tracer monotonic-derived, seconds
    commit_ts: Optional[float]      # store wall clock, None for retrieve spans
    commit_id: Optional[str]        # returned by write, carried by retrieve
    required_version: Optional[str] # retrieve's session last-seen version
    read_satisfied: Optional[bool]  # store assertion for retrieve


def order_write_then_read(
    write: MemoryEvent,
    read: MemoryEvent,
    resolution_floor_s: float,
) -> str:
    """Return 'write_precedes_read', 'concurrent', or 'undetermined'.

    Never orders by span timestamp across clock domains. Uses causal tokens
    first; falls back to a resolution-floor check; refuses to guess otherwise.
    """
    if write.kind != "write" or read.kind != "retrieve":
        raise CorrelationOrderingError(
            f"expected write/retrieve, got {write.kind}/{read.kind}"
        )

    # Path 1: causal token present on both sides.
    if write.commit_id is not None and read.required_version is not None:
        if read.read_satisfied is True:
            return "write_precedes_read"
        if read.read_satisfied is False:
            # Read did not see the committed write: this is a real
            # read-after-write violation, not a timestamp artifact.
            return "undetermined"  # caller must escalate as store-consistency bug
        raise CorrelationOrderingError(
            "causal token present but store did not assert read_satisfied"
        )

    # Path 2: no token. Only order if commit lag is below the resolution floor.
    if write.commit_ts is None:
        raise CorrelationOrderingError(
            "write span has no commit_ts; cannot bound emission-to-commit lag"
        )
    commit_lag = write.commit_ts - write.span_ts
    if commit_lag < 0:
        # Clock-domain inversion (Δo): commit appears before emission.
        raise CorrelationOrderingError(
            f"negative commit lag {commit_lag:.3f}s indicates clock-domain "
            f"offset; timestamps are not comparable"
        )
    if commit_lag > resolution_floor_s:
        # The write's visibility is later than the query can resolve.
        return "concurrent"

    # Commit lag is small enough that span order is a defensible proxy.
    return "write_precedes_read" if write.span_ts < read.span_ts else "concurrent"


def build_incident_timeline(
    events: list[MemoryEvent],
    resolution_floor_s: float,
) -> list[str]:
    """Correlate a write/retrieve sequence, refusing invalid orderings."""
    findings: list[str] = []
    last_write: Optional[MemoryEvent] = None
    for ev in events:
        if ev.kind == "write":
            last_write = ev
            continue
        if ev.kind == "retrieve":
            if last_write is None:
                findings.append(f"retrieve@{ev.span_ts:.3f}: no prior write")
                continue
            verdict = order_write_then_read(
                last_write, ev, resolution_floor_s
            )
            if verdict == "concurrent":
                # Honest: refuse to assert a stale-read race.
                findings.append(
                    f"retrieve@{ev.span_ts:.3f}: CONCURRENT with prior write "
                    f"(commit lag exceeds resolution floor; not a race)"
                )
            elif verdict == "undetermined":
                findings.append(
                    f"retrieve@{ev.span_ts:.3f}: UNDETERMINED — store did not "
                    f"assert read_satisfied; escalate as consistency bug"
                )
            else:
                findings.append(
                    f"retrieve@{ev.span_ts:.3f}: write_precedes_read confirmed"
                )
    return findings
