# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-otel-span-s-absence-as-evidence-rather-than-as-a-gap-distinguishing-compaction-suppressed-memory-writes-from-genuine-me.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-otel-span-s-absence-as-evidence-rather-than-as-a-gap-distinguishing-compaction-suppressed-memory-writes-from-genuine-me.warrant.json
# Markdown SHA-256:   9138640ce022c639b463993d5c8bb1d2762f21063eac15440a8965e1fa5e9ae2
# Code AST SHA-256:   295590d097d06982fb0aa51d291fe41c7fbb00ae9c1cf2f045752bc399451f3d
# Verified Classes:   CompactionAttestationError, AbsenceClass, CompactSpan, WriteSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CompactionAttestationError(RuntimeError):
    """Raised when a missing memory.write span cannot be attributed to an attested compaction suppression."""
    pass


class AbsenceClass(Enum):
    SUPPRESSED_ATTESTED = "suppressed_attested"
    UNATTESTED_ABSENCE = "unattested_absence"
    TRUE_MISSING_WRITE = "true_missing_write"


@dataclass
class CompactSpan:
    window_start: int
    window_end: int
    suppressed_ops: Optional[dict] = None      # key -> content_hash, or None if manifest absent
    summarize_output_hash: Optional[str] = None
    status: str = "OK"


@dataclass
class WriteSpan:
    key: str
    source_range: tuple[int, int]
    content_hash: str


def classify_absence(
    missing_key: str,
    source_range: tuple[int, int],
    writes: list[WriteSpan],
    compacts: list[CompactSpan],
) -> AbsenceClass:
    # If a write span actually exists, this is not an absence at all.
    for w in writes:
        if w.key == missing_key:
            raise CompactionAttestationError(
                f"key {missing_key!r} has a write span; classify_absence is inapplicable"
            )

    covering = [
        c for c in compacts
        if c.window_start <= source_range[0] and c.window_end >= source_range[1]
    ]
    if not covering:
        return AbsenceClass.TRUE_MISSING_WRITE

    # A compact span with status=OK but no manifest is NOT admissible evidence.
    for c in covering:
        if c.suppressed_ops is None:
            raise CompactionAttestationError(
                f"compact span covering {source_range} has null suppressed_ops; "
                f"absence of {missing_key!r} is unattested, not suppressed"
            )
        if c.summarize_output_hash is None:
            raise CompactionAttestationError(
                f"compact span covering {source_range} lacks summarize_output_hash; "
                f"cannot verify {missing_key!r} survives in summary"
            )
        if missing_key in c.suppressed_ops:
            expected = c.suppressed_ops[missing_key]
            if expected != _hash_key(missing_key):
                raise CompactionAttestationError(
                    f"manifest hash mismatch for {missing_key!r}: "
                    f"summary claims {expected}, expected {_hash_key(missing_key)}"
                )
            return AbsenceClass.SUPPRESSED_ATTESTED

    # Covered by a compact but not listed in any manifest -> unattested.
    return AbsenceClass.UNATTESTED_ABSENCE


def _hash_key(key: str) -> str:
    return hashlib.sha256(key.encode()).hexdigest()[:16]


def audit_gate(
    missing_key: str,
    source_range: tuple[int, int],
    writes: list[WriteSpan],
    compacts: list[CompactSpan],
) -> AbsenceClass:
    result = classify_absence(missing_key, source_range, writes, compacts)
    if result is AbsenceClass.UNATTESTED_ABSENCE:
        raise CompactionAttestationError(
            f"unattested absence for {missing_key!r}: compaction covered the source "
            f"range but no manifest entry accounts for it; escalation required"
        )
    return result
