# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-trace-ledger-correlation-break-when-memory-mutations-and-safety-events-share-no-causal-clock.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-trace-ledger-correlation-break-when-memory-mutations-and-safety-events-share-no-causal-clock.warrant.json
# Markdown SHA-256:   a5cbc24e68edf688deafceb8e5b2dc09b875e74449b7ce6d652d4fac5c803fdb
# Code AST SHA-256:   75e93541aee3a19a03a4adcb0b574f8ab3ef2e870ba43780f2c89f9da6284b72
# Verified Classes:   LedgerCorrelationError, Record
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LedgerCorrelationError(RuntimeError):
    """Raised when a ledger entry cannot be assigned a defensible causal order."""


@dataclass
class Record:
    kind: str                      # "trace" | "mutation" | "safety"
    causal_token: Optional[str]    # minted at agent action boundary
    producer_ts: float             # stamp at inference/commit, NOT flush
    content_hash: Optional[str] = None
    instance_ts: Optional[float] = None


def build_ledger_entry(records: list[Record]) -> dict:
    tokens = {r.causal_token for r in records if r.causal_token is not None}
    missing = [r.kind for r in records if r.causal_token is None]

    if len(tokens) > 1:
        raise LedgerCorrelationError(
            f"conflicting causal tokens across streams: {tokens}"
        )

    if len(tokens) == 1 and not missing:
        ordered = sorted(records, key=lambda r: r.producer_ts)
        return {"ordering_confidence": "causal", "order": [r.kind for r in ordered]}

    # Temporal-only join: must verify monotonicity before downgrading.
    safety = [r for r in records if r.kind == "safety"]
    mutations = [r for r in records if r.kind == "mutation"]

    for s in safety:
        matched = [m for m in mutations if m.content_hash == s.content_hash]
        if len(matched) > 1:
            raise LedgerCorrelationError(
                f"safety verdict {s.content_hash} matched {len(matched)} "
                f"mutation instances; ordering indeterminate (fan-out)"
            )
        for m in matched:
            if s.producer_ts > m.producer_ts:
                raise LedgerCorrelationError(
                    f"monotonicity violation: safety verdict at {s.producer_ts} "
                    f"postdates mutation commit at {m.producer_ts}; "
                    f"likely classifier flush-time restamp"
                )

    return {
        "ordering_confidence": "temporal_only",
        "missing_causal_token": missing,
        "quarantine": True,
    }
