# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-its-own-pruning-decisions-as-untrusted-evidence-after-a-context-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-its-own-pruning-decisions-as-untrusted-evidence-after-a-context-rewrite.warrant.json
# Markdown SHA-256:   f1505a24509b5d4740a73b21a08194ff3b04e75f37e217b7392c3afab29139bc
# Code AST SHA-256:   9deaef553a902a068c044be8c6ec3e045942f7d2e5d74320812855219b73af76
# Verified Classes:   PrunedPreconditionError, Conclusion, EvidenceTier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class PrunedPreconditionError(RuntimeError):
    """Raised when an action depends on a conclusion whose invalidation
    condition was itself pruned, making the conclusion unauditable."""
    pass


@dataclass
class Conclusion:
    text: str
    evidence_refs: list[str]          # pointers into the evidence tier
    invalidated_by: Optional[str]     # event/condition that would falsify it
    valid: bool = True


@dataclass
class EvidenceTier:
    store: dict[str, str] = field(default_factory=dict)

    def put(self, span: str) -> str:
        ref = "ev:" + hashlib.sha256(span.encode()).hexdigest()[:12]
        self.store[ref] = span
        return ref

    def resolve(self, ref: str) -> Optional[str]:
        return self.store.get(ref)


def check_conclusion_usable(
    c: Conclusion, evidence: EvidenceTier, current_events: set[str]
) -> None:
    """A self-generated conclusion may only be used as a premise if its
    supporting evidence is still addressable AND its invalidation condition
    is not present in the current event set."""
    for ref in c.evidence_refs:
        if evidence.resolve(ref) is None:
            raise PrunedPreconditionError(
                f"conclusion {c.text!r} cites {ref} which was pruned; "
                f"cannot premise on an unauditable verdict"
            )
    if c.invalidated_by is not None and c.invalidated_by in current_events:
        raise PrunedPreconditionError(
            f"conclusion {c.text!r} invalidated by event "
            f"{c.invalidated_by!r} now in context; must re-derive"
        )


def guarded_write(
    conclusion: Conclusion,
    evidence: EvidenceTier,
    current_events: set[str],
    idempotency_key: str,
) -> str:
    # The write is only safe if the prior "verified" verdict is still audit-
    # able; otherwise we risk a duplicate side effect on a stale premise.
    check_conclusion_usable(conclusion, evidence, current_events)
    return f"write committed under key {idempotency_key}"


# --- trace of the observed failure, now bounded ---
ev = EvidenceTier()
ref_409 = ev.put("409 Conflict on write, idempotency key derived from K")
ref_retry = ev.put("retry 200 using idempotency key derived from K")

# The rewriter pruned the 409 span; because we keep the evidence tier,
# the pointer survives even though the working-tier text is gone.
conclusion = Conclusion(
    text="write path verified",
    evidence_refs=[ref_409, ref_retry],
    invalidated_by="duplicate-write-attempt",
)

# Turn 31: a new write attempt arrives; the invalidation condition fires.
current_events = {"duplicate-write-attempt"}
try:
    guarded_write(conclusion, ev, current_events, idempotency_key="K2")
except PrunedPreconditionError as e:
    # Correct behavior: re-fetch the 409 evidence and re-derive the key
    # from K before writing, instead of promoting the stale verdict.
    _ = ev.resolve(ref_409)
    raise PrunedPreconditionError(
        f"halting write: {e}; re-derive idempotency key from preserved evidence"
    ) from e
