# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-memory-writes-before-retrieval-time-poisoning-propagates-across-a-shared-store.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-memory-writes-before-retrieval-time-poisoning-propagates-across-a-shared-store.warrant.json
# Markdown SHA-256:   0a7b13086e3059ca2168597f26bddd18eb50db5d22cdca31297527b75f723f7e
# Code AST SHA-256:   274759ab267ee0ccda1bcf2cadecff4061e95d35db8baff59ba451237844cec1
# Verified Classes:   UnverifiedProvenanceError, ContaminatedDerivedWriteError, Memory, ExternalAttestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class UnverifiedProvenanceError(RuntimeError):
    """Raised when a memory's lineage cannot be re-established against an
    external source independent of the retrieval index."""
    pass


class ContaminatedDerivedWriteError(RuntimeError):
    """Raised when a derived memory would be written from a context that
    incorporated an unverified retrieval."""
    pass


@dataclass(frozen=True)
class Memory:
    memory_id: str
    content: str
    provenance_tag: str          # advisory only; NOT a binding
    embedding: tuple[float, ...]


@dataclass(frozen=True)
class ExternalAttestation:
    memory_id: str
    signer_id: str
    signature: bytes             # verifiable against signer's public key


def reestablish_provenance(
    memory: Memory,
    attestation: Optional[ExternalAttestation],
    trusted_signers: dict[str, bytes],
) -> bool:
    """Provenance must be re-derived from a source OUTSIDE the retrieval index.

    A schema-conformant provenance_tag is insufficient: it is advisory
    metadata that any writer can forge. The attestation must be signed by a
    trusted signer whose key the writing instance cannot unilaterally control.
    """
    if attestation is None:
        raise UnverifiedProvenanceError(
            f"memory {memory.memory_id}: no external attestation; "
            f"provenance_tag={memory.provenance_tag!r} is advisory only"
        )
    if attestation.memory_id != memory.memory_id:
        raise UnverifiedProvenanceError(
            f"memory {memory.memory_id}: attestation is for "
            f"{attestation.memory_id!r}, not this memory"
        )
    if attestation.signer_id not in trusted_signers:
        raise UnverifiedProvenanceError(
            f"memory {memory.memory_id}: signer {attestation.signer_id!r} "
            f"is not in the trusted signer set"
        )
    expected = trusted_signers[attestation.signer_id]
    if not _verify_signature(memory.content, attestation.signature, expected):
        raise UnverifiedProvenanceError(
            f"memory {memory.memory_id}: signature does not bind to content"
        )
    return True


def _verify_signature(content: str, signature: bytes, public_key: bytes) -> bool:
    # Placeholder for actual signature verification (e.g., Ed25519).
    digest = hashlib.sha256(content.encode()).digest()
    return signature[:32] == digest[:32] and bool(public_key)


def incorporate_into_context(
    retrieved: list[Memory],
    attestations: dict[str, ExternalAttestation],
    trusted_signers: dict[str, bytes],
) -> list[Memory]:
    """Retrieval must not enter working context until every item's
    provenance is re-established against an external source.

    Neighborhood poisoning means the retrieval set is itself suspect:
    a single poisoned write shifts k-NN results for unrelated queries.
    Content plausibility is NOT a valid acceptance criterion.
    """
    accepted: list[Memory] = []
    for mem in retrieved:
        reestablish_provenance(
            mem,
            attestations.get(mem.memory_id),
            trusted_signers,
        )
        accepted.append(mem)
    return accepted


def write_derived_memory(
    derived: Memory,
    source_context: list[Memory],
    context_attestations: dict[str, ExternalAttestation],
    trusted_signers: dict[str, bytes],
) -> None:
    """Derived writes inherit contamination from their source context.

    An instance must quarantine its OWN writes when it cannot prove the
    context it reasoned from was uncontaminated. Self-quarantine is
    required because the instance cannot distinguish its own reasoning
    from a poisoned premise it absorbed.
    """
    for src in source_context:
        try:
            reestablish_provenance(
                src,
                context_attestations.get(src.memory_id),
                trusted_signers,
            )
        except UnverifiedProvenanceError as exc:
            raise ContaminatedDerivedWriteError(
                f"refusing to write derived memory {derived.memory_id}: "
                f"source context contains unverified memory "
                f"{src.memory_id} ({exc})"
            ) from exc
