# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-starves-a-peer-through-context-budget-arbitration-in-a-shared-memory-namespace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-starves-a-peer-through-context-budget-arbitration-in-a-shared-memory-namespace.warrant.json
# Markdown SHA-256:   662e0ee58cee82ca27d1c7940025077a6d28854a63029c4f624cff1ecb7fc281
# Code AST SHA-256:   776c1f01ea81e996140f3c8b4012ff64dae239f9d35719baf88157e6e7f75054
# Verified Classes:   StarvationInducedDistillationLoss, RetrievalResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StarvationInducedDistillationLoss(RuntimeError):
    """Raised when a write is attempted from a partial (starvation-truncated) read."""
    pass


class RetrievalResult:
    def __init__(self, chunks, total_expected, attestation):
        self.chunks = chunks
        self.total_expected = total_expected
        self.attestation = attestation  # None if arbiter gave no completeness signal

    def is_complete(self) -> bool:
        # No attestation => cannot prove completeness => treat as incomplete.
        if self.attestation is None:
            return False
        return self.attestation.get("returned") == self.total_expected == len(self.chunks)


def guarded_write(namespace, key, new_value, provenance: RetrievalResult):
    """Reject writes whose provenance is a degraded read of the same namespace."""
    if not provenance.is_complete():
        raise StarvationInducedDistillationLoss(
            f"Refusing write to {namespace}/{key}: provenance read returned "
            f"{len(provenance.chunks)}/{provenance.total_expected} chunks "
            f"(attestation={provenance.attestation}). "
            f"Re-query under a budget floor before mutating shared state."
        )
    namespace.put(key, new_value)
    return True


# --- trigger trace ---
planner_read = RetrievalResult(
    chunks=["c1", "c2", "c3"],
    total_expected=9,
    attestation=None,  # arbiter stripped the flag under starvation
)
try:
    guarded_write(session_memory, "task_constraints", {"plan": "v2"}, planner_read)
except StarvationInducedDistillationLoss as e:
    # Correct behavior: planner re-queries instead of laundering a partial view.
    planner_read = arbiter.fetch_with_floor("task_constraints", min_slice=8192)
    guarded_write(session_memory, "task_constraints", {"plan": "v2"}, planner_read)
