# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-it-would-reject-on-reread-write-time-validation-blind-spots-for-derived-fact-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-it-would-reject-on-reread-write-time-validation-blind-spots-for-derived-fact-memory.warrant.json
# Markdown SHA-256:   13d876eeed54491bdf8ba66fe2bee7c7994277f8941d689fe116886ffc8abfa6
# Code AST SHA-256:   cf43352c346c7e79b84538c1352b792e297b1f487cf2b643792edd5835ee6a0d
# Verified Classes:   ProvenanceInsufficientError, Artifact, CandidateFact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceInsufficientError(RuntimeError):
    """Raised when a memory write's persisted provenance cannot re-derive its value."""
    pass


@dataclass
class Artifact:
    artifact_id: str
    payload: str
    entails: bool  # does this artifact alone reproduce the candidate value?


@dataclass
class CandidateFact:
    key: str
    value: str
    artifacts: list[Artifact] = field(default_factory=list)


def rederive(artifact: Artifact) -> str | None:
    """Deterministic re-derivation from a single persisted artifact."""
    if not artifact.entails:
        return None
    return artifact.payload


def validate_write(fact: CandidateFact, allow_synthesis: bool = False) -> str:
    """
    Returns the status to persist: 'verified' or 'synthesis_pending'.
    Raises ProvenanceInsufficientError when no single artifact entails the
    value and synthesis is not an allowed disposition.
    """
    entailers = [a for a in fact.artifacts if rederive(a) == fact.value]

    if len(entailers) == 1:
        return "verified"

    if len(entailers) > 1:
        # Conjunctive provenance: value reproduced by multiple artifacts.
        # Safe only if every entailer independently reproduces it.
        digests = {hashlib.sha256(a.payload.encode()).hexdigest() for a in entailers}
        if len(digests) == 1:
            return "verified"
        if not allow_synthesis:
            raise ProvenanceInsufficientError(
                f"{fact.key}: multi-source synthesis without synthesis disposition; "
                f"entailers={[a.artifact_id for a in entailers]}"
            )
        return "synthesis_pending"

    # No artifact entails the value: the observed poisoning case.
    raise ProvenanceInsufficientError(
        f"{fact.key}={fact.value!r} not re-derivable from persisted provenance; "
        f"artifacts={[(a.artifact_id, a.entails) for a in fact.artifacts]}"
    )


# Reproduction of the observed failure:
poisoned = CandidateFact(
    key="service_b.max_replicas",
    value="40",
    artifacts=[
        Artifact("config_api_call_8812", "null", entails=False),
        Artifact("ticket_4471", "NOTE: replica ceiling raised to 40", entails=True),
    ],
)
# Single entailer (the ticket) -> 'verified' under naive rules, which is the bug.
# With synthesis disposition required for ticket-sourced config facts:
try:
    validate_write(poisoned, allow_synthesis=False)
except ProvenanceInsufficientError as e:
    # Correct outcome: ticket is not ground truth for a config value.
    print(f"rejected: {e}")
