# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-cache-poisoning-when-a-peer-agent-s-working-memory-write-is-coherent-locally-but-incoherent-globally.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-cache-poisoning-when-a-peer-agent-s-working-memory-write-is-coherent-locally-but-incoherent-globally.warrant.json
# Markdown SHA-256:   43bf8c177ac2c5a43dbdc72525572050a08af619a9015616fef243fdf56689d2
# Code AST SHA-256:   e3a39d7ba9389ab29d928c1f1f0ef46ef4972c31a08b05fb271d47ce866e7539
# Verified Classes:   AliasClobberDetected, CacheEntry, WriteLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, Optional


class AliasClobberDetected(RuntimeError):
    """Raised when a shared-cache read resolves to a value the reader cannot
    prove was written by an authorized peer, and which contradicts the
    reader's own last-write ledger entry for the same logical key."""


@dataclass(frozen=True)
class CacheEntry:
    logical_key_hash: str
    value: str
    writer_id: str
    writer_epoch: int
    scope_tag: str
    similarity: float  # similarity of the resolving key vs. the stored key


class WriteLedger:
    """Monotonic local record of what this instance last wrote/witnessed per
    logical key. Must survive checkpoint/resume; if lost, the invariant
    degrades to unconditional cache trust."""

    def __init__(self) -> None:
        self._seen: Dict[str, int] = {}

    def record(self, logical_key_hash: str, epoch: int) -> None:
        if epoch > self._seen.get(logical_key_hash, -1):
            self._seen[logical_key_hash] = epoch

    def last_epoch(self, logical_key_hash: str) -> int:
        return self._seen.get(logical_key_hash, -1)


def read_shared_cache(
    entry: CacheEntry,
    ledger: WriteLedger,
    authorized_writers: set,
    admission_threshold: float,
    task_scope: str,
) -> str:
    """Consume a shared-cache read under the write-provenance-pinning invariant.

    Returns the value only when the read is provably authorized and
    scope-compatible. Raises AliasClobberDetected when the read is a
    suspected semantic-alias clobber that would otherwise silently
    de-escalate the caller's guardrail.
    """
    key = entry.logical_key_hash

    # Near-miss resolution: the key aliased into a bucket it did not own.
    if entry.similarity < 1.0 and entry.similarity >= admission_threshold:
        # Allowed as *data* only if scope matches and writer is authorized;
        # never allowed to relax a constraint.
        if entry.writer_id not in authorized_writers or entry.scope_tag != task_scope:
            raise AliasClobberDetected(
                f"near-miss read key={key[:12]} sim={entry.similarity:.3f} "
                f"writer={entry.writer_id} scope={entry.scope_tag} "
                f"caller_scope={task_scope}: refusing to consume aliased value"
            )

    # Exact read, but the writer epoch is not newer than what we've seen.
    # This is the clobber signal: someone wrote under our logical key with
    # an epoch we never witnessed, or an older epoch overwrote a newer one.
    last = ledger.last_epoch(key)
    if entry.writer_epoch <= last and entry.writer_id not in authorized_writers:
        raise AliasClobberDetected(
            f"epoch regression key={key[:12]} "
            f"entry_epoch={entry.writer_epoch} ledger_epoch={last} "
            f"writer={entry.writer_id}: unauthorized overwrite of pinned entry"
        )

    # A value that contradicts our own last-write and was not witnessed
    # as an authorized intervening write must not lower a guardrail.
    if entry.writer_epoch <= last and entry.value != _value_at(ledger, key):
        raise AliasClobberDetected(
            f"unwitnessed value change key={key[:12]} "
            f"epoch={entry.writer_epoch} ledger_epoch={last}: "
            f"cannot prove peer authority for constraint change"
        )

    ledger.record(key, entry.writer_epoch)
    return entry.value


def _value_at(ledger: WriteLedger, key: str) -> Optional[str]:
    # Placeholder: a real implementation stores the value hash alongside the
    # epoch so the contradiction check above is meaningful. Omitting it here
    # keeps the example focused on the epoch/authority predicate.
    return None
