# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-trace-stitching-from-silently-breaking-when-federated-agents-redact-spans-for-privacy.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-trace-stitching-from-silently-breaking-when-federated-agents-redact-spans-for-privacy.warrant.json
# Markdown SHA-256:   82e4fc45fc8daf2145ec3f4a6b8b6274dc9cfdf9247670459d08aaaf2c90755b
# Code AST SHA-256:   7e1ade78607cad317936d2a9779f51b947593883adc56431797b3b092d151435
# Verified Classes:   CausalEdgeRedactionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CausalEdgeRedactionError(RuntimeError):
    """Raised when a redaction policy would delete the sole carrier of a
    cross-agent causal edge without leaving a tombstone or explicit break."""


def apply_redaction(span, policy, span_owner, child_owners):
    """
    span: dict with span_id, parent_id, trace_id, attributes, owner_agent
    policy: callable(span) -> bool, True means "redact this span"
    span_owner: agent that emitted span
    child_owners: mapping span_id -> owner_agent for known children
    """
    if not policy(span):
        return {"action": "keep", "span": span}

    # Find children whose owner differs from this span's owner.
    cross_agent_children = [
        cid for cid, owner in child_owners.items()
        if owner != span_owner
    ]

    if cross_agent_children:
        # The span is the sole parent of another agent's span. We may not
        # silently drop it: that would split the trace or, worse, invite
        # exporter-side reparenting that fabricates a causal edge.
        if span.get("identity_is_sensitive"):
            raise CausalEdgeRedactionError(
                f"span {span['span_id']} carries cross-agent edges "
                f"{cross_agent_children} and its identity is sensitive; "
                f"cannot tombstone and cannot drop without breaking causality. "
                f"Escalate to policy owner."
            )
        return {
            "action": "tombstone",
            "span": {
                "span_id": span["span_id"],
                "parent_id": span.get("parent_id"),
                "trace_id": span["trace_id"],
                "owner_agent": span_owner,
                "attributes": {},
                "redaction.applied": True,
            },
        }

    # No cross-agent children: safe to drop outright.
    return {"action": "drop", "span_id": span["span_id"]}


def stitch(child, redaction_manifest):
    """Attach a child to its parent, refusing silent misattachment."""
    parent_id = child.get("parent_id")
    if parent_id is None:
        return {"attached_to": None, "note": "root"}

    if parent_id in redaction_manifest:
        return {
            "attached_to": parent_id,
            "note": "parent redacted; edge preserved via tombstone",
        }

    # Parent_id is unknown and not in the manifest: this is either a
    # genuine orphan or an unrecorded redaction. Refuse to guess.
    raise CausalEdgeRedactionError(
        f"child {child['span_id']} references unknown parent {parent_id} "
        f"with no redaction manifest entry; refusing to attach to trace root"
    )
