# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-beneath-a-consistent-read-write-forget-audit-trail.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-beneath-a-consistent-read-write-forget-audit-trail.warrant.json
# Markdown SHA-256:   26a432bdf91879856f8e1d9a2b32743327334a1f06e0710aeba6e7f498667795
# Code AST SHA-256:   bacc80d234dffaa7dd85083f2a97bd08df89f2245ed3011fa015c8143dbee898
# Verified Classes:   DerivationAuditError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DerivationAuditError(RuntimeError):
    """Raised when a memory mutation would break derivation consistency."""
    pass


def audit_forget(record_id: str, live_dag: dict, consumers: set) -> None:
    """Reject a forget that orphans the last justification of a live record.

    live_dag: {record_id: {"parents": [...], "src": "user"|"derived"|"tool"}}
    consumers: set of record_ids currently readable/read-this-session
    """
    forgotten = live_dag.get(record_id, {"parents": []})
    # records that cite record_id as a parent
    orphans = [
        rid for rid, node in live_dag.items()
        if record_id in node.get("parents", [])
        and not (set(node["parents"]) - {record_id})
    ]
    live_orphans = [o for o in orphans if o in consumers]
    if live_orphans and forgotten.get("src") != "user":
        raise DerivationAuditError(
            f"forget({record_id}) src={forgotten.get('src')} would orphan "
            f"live consumers {live_orphans}; only user-sourced forget may "
            f"sever the last justification edge of an actively-read record"
        )


def audit_derived_write(record_id: str, parents: list, live_dag: dict,
                        entailment_holds: bool) -> None:
    """Reject a derived write whose cited parents do not entail its content."""
    missing = [p for p in parents if p not in live_dag]
    if missing:
        raise DerivationAuditError(
            f"write({record_id}) cites non-existent parents {missing}"
        )
    if not entailment_holds:
        raise DerivationAuditError(
            f"write({record_id}) is structurally valid but semantically "
            f"orphaned: declared parents {parents} do not entail content"
        )
