# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-re-elevate-privilege-after-a-taint-clearing-checkpoint-when-a-poisoned-tool-result-is-still-resident-in-the-kv-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-re-elevate-privilege-after-a-taint-clearing-checkpoint-when-a-poisoned-tool-result-is-still-resident-in-the-kv-cache.warrant.json
# Markdown SHA-256:   c9b0a0d16546717a4ea199644ca863aff5f7d6c6d3ccb378eac59d8ff2deecf4
# Code AST SHA-256:   1e0075f36f09357061ef9ad07b489b0224717ac05b116847a4f268e9634cda17
# Verified Classes:   TaintElevationError, Span, ContextManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintElevationError(RuntimeError):
    """Raised when privilege is re-elevated while tainted bytes remain resident."""


@dataclass
class Span:
    span_id: str
    taint: str                 # "trusted" | "untrusted"
    derived_from: Optional[str] = None   # span_id of source, if model-authored


@dataclass
class ContextManifest:
    """The token spans the model will actually condition on for this step."""
    resident: dict[str, Span] = field(default_factory=dict)

    def add(self, span: Span) -> None:
        self.resident[span.span_id] = span

    def tainted_resident(self) -> list[str]:
        bad = []
        for sid, s in self.resident.items():
            if s.taint == "untrusted" or (
                s.derived_from is not None
                and self.resident.get(s.derived_from, Span(s.derived_from, "untrusted")).taint
                == "untrusted"
            ):
                bad.append(sid)
        return bad


def re_elevate(manifest: ContextManifest, requested_scope: str,
               eviction_proven: bool) -> str:
    """
    Grant elevated scope only if (a) eviction of tainted spans is proven and
    (b) no tainted or tainted-derived span remains resident.
    """
    if not eviction_proven:
        raise TaintElevationError(
            f"refusing to grant '{requested_scope}': no eviction proof; "
            f"tainted spans may still be in prefix cache"
        )
    leftover = manifest.tainted_resident()
    if leftover:
        raise TaintElevationError(
            f"refusing to grant '{requested_scope}': tainted spans still resident: "
            f"{leftover}"
        )
    return requested_scope


# --- failure trace: summary derived from untrusted doc, doc bytes still cached ---
m = ContextManifest()
m.add(Span("doc_raw", taint="untrusted"))
m.add(Span("doc_summary", taint="trusted", derived_from="doc_raw"))  # closure catches it
try:
    re_elevate(m, "send_email", eviction_proven=True)
except TaintElevationError as e:
    print("blocked:", e)   # blocked: tainted spans still resident: ['doc_raw', 'doc_summary']
