# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-demote-a-dynamic-taint-label-when-a-tool-output-is-re-derived-from-a-trusted-recomputation-and-why-label-monotonici.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-demote-a-dynamic-taint-label-when-a-tool-output-is-re-derived-from-a-trusted-recomputation-and-why-label-monotonici.warrant.json
# Markdown SHA-256:   99178ac6014afb9e443848710b1f1f149c93383df79dd03c9e0bfb99ef5eba84
# Code AST SHA-256:   e96702dbe0ea78cec58275932f3bf9f09522ab1b9cac1a7b3f41fb6f3582cc42
# Verified Classes:   TaintDemotionError, Segment, ToolResult, DemotionRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TaintDemotionError(RuntimeError):
    """Raised when a demotion is attempted without satisfying the validity conditions."""
    pass


@dataclass
class Segment:
    seg_id: str
    content: bytes
    tainted_by: Optional[str] = None  # taint id, or None if clean


@dataclass
class ToolResult:
    value: bytes
    accessed_segments: list  # segment ids the tool actually read
    recompute_of: Optional[str] = None  # value hash this recomputes, if any


@dataclass
class DemotionRecord:
    value_hash: str
    from_label: str
    evidence: dict
    timestamp: float


def _hash(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def demote(
    tainted_value: bytes,
    taint_id: str,
    recompute: ToolResult,
    context: dict,
    now: float,
) -> DemotionRecord:
    # Condition 1: input closure -- recompute must not have read the tainted segment.
    if taint_id in recompute.accessed_segments:
        raise TaintDemotionError(
            f"recompute observed tainted segment {taint_id}; demotion invalid"
        )
    # Condition 1b: no other tainted segment among inputs.
    for seg_id in recompute.accessed_segments:
        seg = context.get(seg_id)
        if seg is not None and seg.tainted_by is not None:
            raise TaintDemotionError(
                f"recompute read tainted segment {seg_id} ({seg.tainted_by})"
            )
    # Condition 2: value identity -- bytes must match the clean recompute.
    if _hash(recompute.value) != _hash(tainted_value):
        raise TaintDemotionError(
            "recompute produced a different value; treat as new value, not demotion"
        )
    # Condition 3: no unrecorded downstream dependence is checked by caller.
    return DemotionRecord(
        value_hash=_hash(tainted_value),
        from_label=taint_id,
        evidence={
            "accessed_segments": list(recompute.accessed_segments),
            "recompute_of": recompute.recompute_of,
        },
        timestamp=now,
    )


def resume_with_checkpoint(record: DemotionRecord, stored_label: str) -> str:
    # Guardrail: a demotion record must override a stale tainted label on resume.
    if stored_label == record.from_label and record.value_hash:
        return "clean"  # demotion survives checkpoint
    raise TaintDemotionError(
        f"checkpoint label {stored_label} not covered by demotion record"
    )
