# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-its-own-provenance-ledger-when-a-poisoned-memory-entry-is-re-ingested-through-a-legitimate-write-path.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-its-own-provenance-ledger-when-a-poisoned-memory-entry-is-re-ingested-through-a-legitimate-write-path.warrant.json
# Markdown SHA-256:   a3500ccd389bd56a65bfab4fc913082f8f73cd15003325cf1491b29dfa757147
# Code AST SHA-256:   9d15073a8aa694be5a7e09c551d720e6cffe0852ad774a346c2af86403ea9a34
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a re-ingested entry's taint cannot be trusted from the ledger."""
    pass


TRANSPORT_PRINCIPALS = {"replication_svc", "restore_daemon", "export_importer"}


def verify_entry_taint(entry: dict, ledger: dict) -> str:
    """
    Return the effective taint for an entry, or raise if provenance is laundered.
    entry: {"id", "writer_id", "causal_parent", "taint", "taint_signed_by"}
    ledger: {entry_id: entry} for backward walk.
    """
    chain = []
    cursor = entry
    seen = set()
    while cursor is not None:
        if cursor["id"] in seen:
            raise ProvenanceLaunderingError(f"cycle in provenance chain at {cursor['id']}")
        seen.add(cursor["id"])
        chain.append(cursor)
        parent_id = cursor.get("causal_parent")
        cursor = ledger.get(parent_id)

    crosses_transport = any(e["writer_id"] in TRANSPORT_PRINCIPALS for e in chain)
    taint = entry.get("taint")
    signed_by = entry.get("taint_signed_by")

    if taint is None or taint == "clean":
        if crosses_transport:
            raise ProvenanceLaunderingError(
                f"entry {entry['id']} claims clean taint but chain crosses "
                f"transport principal; content re-scan required"
            )
        if signed_by != entry["writer_id"]:
            raise ProvenanceLaunderingError(
                f"entry {entry['id']} taint not signed by originating writer"
            )
    return taint
