# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-honor-a-scoped-retention-write-when-the-write-s-provenance-chain-crosses-a-tombstoned-memory-key.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-honor-a-scoped-retention-write-when-the-write-s-provenance-chain-crosses-a-tombstoned-memory-key.warrant.json
# Markdown SHA-256:   dace808bc0269d545db0d62d35ae9cd573be617633884a4a7761c6decd202ee9
# Code AST SHA-256:   9d805198959306a953ac560c32e4e5657651baef46f448c72404cee8862477e5
# Verified Classes:   ProvenanceTombstoneViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceTombstoneViolation(RuntimeError):
    """Raised when a memory write derives from a tombstoned key."""
    pass


def adjudicate_write(
    key: str,
    value: str,
    provenance: list[str],
    live_tombstones: set[str],
    tombstone_descendant_hashes: set[str],
    derivation_fn,
) -> str:
    if not provenance:
        return "accept"

    hits = [p for p in provenance if p in live_tombstones]
    if not hits:
        return "accept"

    # Try redaction: re-derive from surviving ancestors only.
    surviving = [p for p in provenance if p not in live_tombstones]
    if surviving:
        redacted_value = derivation_fn(surviving)
        if redacted_value == value:
            return f"accept_redacted:{','.join(hits)}"

    # Contaminated or sole-ancestor case: refuse and escalate.
    raise ProvenanceTombstoneViolation(
        f"write to {key!r} derives from tombstoned keys {hits}; "
        f"redaction from surviving ancestors {surviving} does not "
        f"reproduce the value. Escalate to warrant issuer."
    )


def guarded_write(store, key, value, provenance, derivation_fn):
    tombstones = store.live_tombstones()  # authoritative, not snapshot
    descendant_hashes = store.tombstone_descendant_hashes()
    verdict = adjudicate_write(
        key, value, provenance, tombstones, descendant_hashes, derivation_fn
    )
    if verdict.startswith("accept_redacted:"):
        redacted = verdict.split(":", 1)[1].split(",")
        provenance = [p for p in provenance if p not in redacted]
        store.record_erasure_redaction(key, redacted)
    return store.write(key, value, provenance)
