# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-span-to-decision-correlation-when-its-own-memory-writes-mutate-the-trace-it-is-emitting.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-span-to-decision-correlation-when-its-own-memory-writes-mutate-the-trace-it-is-emitting.warrant.json
# Markdown SHA-256:   b8d1e4f410e7e4e7f25b63a01d905bf0fd6ef33f1cfc4e228399adbfa1c60d01
# Code AST SHA-256:   1406bf5a5f65b429f4f0767286969b91e29f1fc30c2661be7ea8926f0838cf64
# Verified Classes:   UnverifiedCausalEdgeError, MemoryWrite, MemoryRead
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class UnverifiedCausalEdgeError(RuntimeError):
    """Raised when a correlator attempts to emit a causal edge from temporal adjacency alone."""


@dataclass
class MemoryWrite:
    key: str
    decision_id: str
    pre_write_hash: str
    post_write_hash: str
    readers_of_prior: frozenset[str] = field(default_factory=frozenset)


@dataclass
class MemoryRead:
    key: str
    decision_id: str
    observed_hash: str
    store_version: int
    cache_populated_by: Optional[str] = None


def correlate_read_to_writer(
    read: MemoryRead,
    writes: list[MemoryWrite],
    *,
    allow_inferred: bool = False,
) -> tuple[str, str]:
    """
    Returns (writer_decision_id, edge_kind) where edge_kind is 'causal' or 'inferred'.
    Raises UnverifiedCausalEdgeError if the only evidence is temporal adjacency
    and inferred edges are not permitted for this join.
    """
    matching = [w for w in writes if w.key == read.key and w.post_write_hash == read.observed_hash]
    if len(matching) == 1 and read.decision_id in matching[0].readers_of_prior:
        # Explicit read-set membership: the writer recorded that this decision
        # was a known reader of the prior value. This is a causal edge.
        return matching[0].decision_id, "causal"

    if read.cache_populated_by is not None:
        # Cache hit: the span reflects the cache, not the store. Any writer
        # inferred from post_write_hash would be attributing the cache's
        # population to the wrong decision.
        raise UnverifiedCausalEdgeError(
            f"read of {read.key} by {read.decision_id} served from cache "
            f"populated_by={read.cache_populated_by}; store writer is not "
            f"causally attributable from this span"
        )

    if not matching:
        raise UnverifiedCausalEdgeError(
            f"read of {read.key} by {read.decision_id} observed hash "
            f"{read.observed_hash} which no emitted write produced; "
            f"trace is missing a write span or the store mutated out-of-band"
        )

    if len(matching) > 1:
        raise UnverifiedCausalEdgeError(
            f"read of {read.key} by {read.decision_id} matches {len(matching)} "
            f"writes with identical post_write_hash; provenance is ambiguous "
            f"and must not be resolved by temporal order"
        )

    if not allow_inferred:
        raise UnverifiedCausalEdgeError(
            f"read of {read.key} by {read.decision_id} has a single hash match "
            f"({matching[0].decision_id}) but that writer did not record this "
            f"decision as a reader of the prior value; edge is inferred, not causal"
        )
    return matching[0].decision_id, "inferred"


def build_decision_graph(
    reads: list[MemoryRead],
    writes: list[MemoryWrite],
) -> dict[str, list[tuple[str, str]]]:
    graph: dict[str, list[tuple[str, str]]] = {}
    for r in reads:
        try:
            writer, kind = correlate_read_to_writer(r, writes)
        except UnverifiedCausalEdgeError:
            # Unverified reads are dropped from the causal graph rather than
            # promoted to inferred edges. Root-cause ranking must not consume them.
            continue
        graph.setdefault(r.decision_id, []).append((writer, kind))
    return graph
