# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-compaction-span-as-forged-because-its-parent-context-window-span-was-already-closed.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-compaction-span-as-forged-because-its-parent-context-window-span-was-already-closed.warrant.json
# Markdown SHA-256:   ecae053442ad9f5d10d9972f7f872b941c10ef6eb44ba366ee83c6de234c8845
# Code AST SHA-256:   fe85e4a54e5315c0919acc5ceb87887e69b5a8b7b297df0dde0d524ca751d982
# Verified Classes:   CompactionAttributionError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional


class CompactionAttributionError(RuntimeError):
    """Raised when a memory-compaction span cannot be temporally anchored to a live parent."""


@dataclasses.dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    name: str
    start_time: float
    end_time: float
    attributes: dict


def reconcile_compaction_span(span: Span, parent: Optional[Span]) -> Span:
    """Re-anchor a memory.compact span to its temporal parent and validate attribution.

    Returns a span with a reconciled `memory.attribution` attribute, or raises
    CompactionAttributionError if the span is forged-attribution and cannot be repaired.
    """
    if span.name not in ("memory.compact", "memory.forget"):
        return span

    if parent is None:
        raise CompactionAttributionError(
            f"span {span.span_id} ({span.name}) declares parent "
            f"{span.parent_span_id} which is absent from the trace; "
            f"cannot anchor forgetting event to any turn"
        )

    deferred = span.attributes.get("memory.compaction.deferred", False)
    effective_turn = span.attributes.get("memory.compaction.effective_turn")

    # Case 1: ran after declared parent closed and did not self-declare as deferred.
    if span.start_time >= parent.end_time and not deferred:
        raise CompactionAttributionError(
            f"span {span.span_id} ({span.name}) started at {span.start_time} "
            f"but declared parent {parent.span_id} closed at {parent.end_time}; "
            f"undeclared deferred compaction — attribution is forged"
        )

    # Case 2: deferred but names an effective turn that is itself in the past.
    if deferred and effective_turn is not None:
        if span.start_time >= parent.end_time:
            # effective_turn must be a *future* turn relative to the closed parent
            # for the deferral to be meaningful; if it names the same closed parent's
            # turn, the attribution is circular.
            if effective_turn == parent.attributes.get("agent.turn.index"):
                raise CompactionAttributionError(
                    f"span {span.span_id} declares deferred compaction with "
                    f"effective_turn={effective_turn} but that turn's span closed "
                    f"at {parent.end_time} before compaction ran; circular attribution"
                )

    reconciled = dataclasses.replace(span)
    reconciled.attributes = dict(span.attributes)
    reconciled.attributes["memory.attribution"] = (
        "deferred" if deferred else "in_turn"
    )
    reconciled.attributes["memory.attribution.valid"] = True
    return reconciled


def dedupe_replay_spans(spans: list[Span]) -> list[Span]:
    """Collapse duplicate memory.compact spans emitted by checkpoint replay."""
    seen: dict[tuple, Span] = {}
    for s in spans:
        if s.name != "memory.compact":
            continue
        key = (
            s.parent_span_id,
            s.attributes.get("memory.compacted_tokens"),
            s.attributes.get("memory.retained_episodes"),
        )
        if key in seen:
            if s.attributes.get("replay.id") is None:
                raise CompactionAttributionError(
                    f"duplicate memory.compact span {s.span_id} shares key {key} "
                    f"with {seen[key].span_id} and carries no replay.id; "
                    f"cannot disambiguate live vs replayed forgetting event"
                )
            # keep earliest start_time as authoritative
            if s.start_time < seen[key].start_time:
                seen[key] = s
        else:
            seen[key] = s
    return list(seen.values())
