# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-warrant-provenance-when-the-model-itself-authors-the-eviction-policy-that-rewrites-its-own-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-warrant-provenance-when-the-model-itself-authors-the-eviction-policy-that-rewrites-its-own-context-window.warrant.json
# Markdown SHA-256:   33b02c2801e83870e6c6a992307964f67d80719496d477be32f5fb5e1aa612a7
# Code AST SHA-256:   1fcb2b046e08c2afa07cdcd35198fd896256b3c9fe2948dad3d8eee8f72951ac
# Verified Classes:   ProvenanceContinuityError, Warrant, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceContinuityError(RuntimeError):
    """Raised when a model-authored rewrite breaks the warrant derivation chain."""
    pass


@dataclass
class Warrant:
    origin_call_id: str
    signer: str
    issued_at: float
    derivation_parents: tuple = ()


@dataclass
class Span:
    span_id: str
    content: str
    warrant: Warrant


def apply_model_rewrite(targets: list[Span], model_payload: dict,
                        rewriting_instance_id: str) -> Span:
    """
    Enforce the provenance-continuity invariant: the model supplies content
    only; the runtime computes and inherits the warrant. If the model tried
    to author warrant fields, reject the rewrite rather than trust them.
    """
    if "warrant" in model_payload:
        raise ProvenanceContinuityError(
            f"instance {rewriting_instance_id} attempted to author warrant "
            f"fields on a derived span; provenance plane is runtime-owned"
        )

    if not targets:
        raise ProvenanceContinuityError("rewrite has no target spans to derive from")

    # Deterministic parent union — never model-generated.
    parent_ids: list[str] = []
    signers: set[str] = set()
    for t in targets:
        parent_ids.extend(t.warrant.derivation_parents)
        parent_ids.append(t.span_id)
        signers.add(t.warrant.signer)

    if len(signers) != 1:
        raise ProvenanceContinuityError(
            f"rewrite merges spans from multiple signers {signers}; "
            f"warrant cannot be re-anchored to a single authority"
        )

    inherited_signer = next(iter(signers))
    if inherited_signer == rewriting_instance_id:
        raise ProvenanceContinuityError(
            "signer would be re-authored to the rewriting instance; "
            "warrant signer must be inherited from origin"
        )

    derived_warrant = Warrant(
        origin_call_id=targets[0].warrant.origin_call_id,
        signer=inherited_signer,
        issued_at=min(t.warrant.issued_at for t in targets),
        derivation_parents=tuple(sorted(set(parent_ids))),
    )
    return Span(
        span_id=f"derived-{rewriting_instance_id}-{len(parent_ids)}",
        content=model_payload["content"],
        warrant=derived_warrant,
    )
