# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-latency-span-as-invalid-when-context-compaction-rewrites-the-retrieval-that-produced-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-latency-span-as-invalid-when-context-compaction-rewrites-the-retrieval-that-produced-it.warrant.json
# Markdown SHA-256:   65bd11698a12c108d8c853933419da0d0d90e75096804d552a6d0aeac9f074a9
# Code AST SHA-256:   f365f4e26881e7521dfdd5a2c5dd4d570a8f65d1e1524342f05f442115cb0a3c
# Verified Classes:   RetrievalAttributionError, RetrievalSpan, CompactionSpan, GenerationSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class RetrievalAttributionError(RuntimeError):
    """Raised when a memory-retrieval span cannot be causally tied to the
    generation span that consumed its output, because the chunk set was
    rewritten without an accounting compaction span."""


@dataclass
class RetrievalSpan:
    span_id: str
    end_ts: float
    top_k: int
    chunk_ids: list[str]
    duration_ms: float

    def digest(self) -> str:
        joined = "|".join(self.chunk_ids)
        return hashlib.sha256(joined.encode()).hexdigest()


@dataclass
class CompactionSpan:
    span_id: str
    start_ts: float
    parent_retrieval_id: str
    dropped_chunk_ids: list[str]
    output_chunk_ids: list[str]
    duration_ms: float


@dataclass
class GenerationSpan:
    span_id: str
    start_ts: float
    input_chunk_ids: list[str]

    def digest(self) -> str:
        joined = "|".join(self.input_chunk_ids)
        return hashlib.sha256(joined.encode()).hexdigest()


def validate_retrieval_attribution(
    retrieval: RetrievalSpan,
    generation: GenerationSpan,
    compactions: list[CompactionSpan],
) -> str:
    """Return 'authoritative', 'compacted', or raise on integrity failure."""
    if retrieval.end_ts > generation.start_ts:
        raise RetrievalAttributionError(
            f"retrieval {retrieval.span_id} ends after generation "
            f"{generation.span_id} starts; causal order violated"
        )

    digests_match = retrieval.digest() == generation.digest()
    if digests_match:
        return "authoritative"

    explaining = [
        c for c in compactions
        if c.parent_retrieval_id == retrieval.span_id
        and retrieval.end_ts <= c.start_ts <= generation.start_ts
    ]
    if explaining:
        # Verify the compaction actually accounts for the difference.
        expected = set(retrieval.chunk_ids) - set(explaining[-1].dropped_chunk_ids)
        if set(generation.input_chunk_ids) != expected:
            raise RetrievalAttributionError(
                f"compaction {explaining[-1].span_id} does not account for "
                f"generation input for retrieval {retrieval.span_id}; "
                f"expected {sorted(expected)}, got "
                f"{sorted(generation.input_chunk_ids)}"
            )
        return "compacted"

    raise RetrievalAttributionError(
        f"chunk-set digest mismatch between retrieval {retrieval.span_id} "
        f"and generation {generation.span_id} with no compaction span "
        f"explaining it; context was rewritten without instrumentation"
    )
