# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-write-to-a-memory-tool-whose-retention-policy-conflicts-with-the-redaction-warrant-attached-to-the-pay.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-write-to-a-memory-tool-whose-retention-policy-conflicts-with-the-redaction-warrant-attached-to-the-pay.warrant.json
# Markdown SHA-256:   8dc29e08e75619c8a8056a2fd6dc21fea13515fa45cd5301d8ec15d27c8c6d12
# Code AST SHA-256:   1a14bf3d7298c0662d6cd551777c4912c6174deb3de6eb0ae3d0d2cf2ad4eb4d
# Verified Classes:   WarrantRetentionConflict, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantRetentionConflict(RuntimeError):
    """Raised when a memory write cannot satisfy both its retention TTL
    and the redaction warrant attached to the payload."""
    pass


@dataclass
class Warrant:
    spans: list[str]
    expires_at: float          # epoch seconds
    supported: bool = True     # tool schema can redact every span type


def guarded_write(memory_tool, payload: str, retention_s: float,
                  warrant: Optional[Warrant]) -> str:
    """Write payload to a retention-bearing slot, refusing if the
    redaction/retention invariant cannot be guaranteed."""

    if warrant is None:
        return memory_tool.write(payload, ttl=retention_s)

    # Invariant 1: tool must be able to redact every warranted span type.
    if not warrant.supported:
        raise WarrantRetentionConflict(
            f"tool cannot redact span types {warrant.spans}; "
            "refusing durable write"
        )

    # Invariant 2: TTL cannot outlive the warrant's own authorization.
    clamped_ttl = min(retention_s, max(0.0, warrant.expires_at - _now()))
    if clamped_ttl <= 0:
        raise WarrantRetentionConflict(
            "warrant already expired; no retention authorized"
        )

    slot = memory_tool.write(payload, ttl=clamped_ttl, redact=warrant.spans)

    # Invariant 3: verify redaction actually landed before trusting the slot.
    readback = memory_tool.read(slot)
    for span_type in warrant.spans:
        if _contains_span(readback, span_type):
            memory_tool.forget(slot)  # bound the leak
            raise WarrantRetentionConflict(
                f"residual {span_type} in slot {slot} after redaction; "
                "slot reclaimed, write rejected"
            )
    return slot


def _now() -> float:
    import time
    return time.time()


def _contains_span(text: str, span_type: str) -> bool:
    # Placeholder detector; real impl matches the warrant's span grammar.
    markers = {"email": "@", "bearer_token": "Bearer "}
    return markers.get(span_type, "\x00") in text
