# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-context-poisoning-in-provenance-weighted-retrieval-attribution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-context-poisoning-in-provenance-weighted-retrieval-attribution.warrant.json
# Markdown SHA-256:   f9ad08602a5c8dc1d4b292c5cb8d824e78788f3b31ae58126cd923a7fb14bf6f
# Code AST SHA-256:   ea4a9203b0d098c3c66449d725a155a2b0a1f93960a8026023915cffc0196dbb
# Verified Classes:   ProvenancePoisoningError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenancePoisoningError(RuntimeError):
    """Raised when a chunk's declared attribution weight is not underwritten
    by a structurally consistent provenance record."""
    pass


def validate_chunk_provenance(chunk, provenance_store, tier_threshold=0.9):
    trust = chunk.get("source_trust", 0.0)
    parent = chunk.get("derivation_parent")
    depth = chunk.get("derivation_depth")
    corroboration = chunk.get("corroboration_count", 0)
    independent_origins = chunk.get("independent_origin_count", 0)

    # Signal 1: high-trust weight with unresolvable derivation parent.
    if trust >= tier_threshold:
        if parent is None or parent not in provenance_store:
            raise ProvenancePoisoningError(
                f"chunk {chunk.get('id')} declares trust={trust} "
                f"but derivation parent {parent!r} is unresolvable"
            )

    # Signal 2: corroboration inflated over a single origin.
    if corroboration > 1 and independent_origins == 0:
        raise ProvenancePoisoningError(
            f"chunk {chunk.get('id')} reports corroboration={corroboration} "
            f"with independent_origin_count=0 (forged corroboration)"
        )

    # Signal 3: primary-source claim that is a copy of a deep derivative.
    if depth == 0 and parent is not None:
        parent_depth = provenance_store[parent].get("derivation_depth")
        if parent_depth is not None and parent_depth >= 1:
            raise ProvenancePoisoningError(
                f"chunk {chunk.get('id')} claims depth=0 (primary) but "
                f"derives from depth={parent_depth} node {parent!r}"
            )

    return True
