# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-mutation-as-an-unobservable-span-causal-orphan-reordering-in-genai-observability-pipelines-corre.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-mutation-as-an-unobservable-span-causal-orphan-reordering-in-genai-observability-pipelines-corre.warrant.json
# Markdown SHA-256:   0bbca4f0ad7d5a23384b5948701b9b0e461c8ec5fd5d4e149558d159ce008e38
# Code AST SHA-256:   4b37e127971d9c770227767968a8d2c3eb4d4a0d33d1af6057882d5583cda60c
# Verified Classes:   CausalOrphanViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalOrphanViolation(RuntimeError):
    """Raised when a late-arriving mutation span would be re-parented across a sealed trace boundary."""

def correlate_mutation(
    mutation_span: dict,
    candidate_parent: dict,
    trace_sealed: bool,
    idle_timeout_ms: int,
    exporter_retry_budget_ms: int,
) -> dict:
    # Invariant 1: a sealed trace may accept orphans, never re-parent them.
    if trace_sealed:
        if mutation_span["trace_id"] != candidate_parent["trace_id"]:
            raise CausalOrphanViolation(
                f"mutation {mutation_span['span_id']} in trace {mutation_span['trace_id']} "
                f"cannot be re-parented to span {candidate_parent['span_id']} in sealed "
                f"trace {candidate_parent['trace_id']}: cross-trace adoption fabricates a causal edge"
            )
        # Same-trace orphan: attach childless, do not mutate parentage.
        return {**mutation_span, "parent_span_id": None, "orphan": True}

    # Invariant 2: idle timeout must exceed the exporter's retry budget, else late spans
    # arrive after seal and hit the cross-trace path above.
    if idle_timeout_ms <= exporter_retry_budget_ms:
        raise CausalOrphanViolation(
            f"idle_timeout_ms={idle_timeout_ms} <= exporter_retry_budget_ms={exporter_retry_budget_ms}: "
            f"seal can fire before a retried mutation span is delivered, forcing orphan re-attribution"
        )

    # Invariant 3: correlation by identity, not timestamp.
    if mutation_span.get("mutation_id") and candidate_parent.get("caused_by") == mutation_span["mutation_id"]:
        return {**mutation_span, "parent_span_id": candidate_parent["span_id"], "orphan": False}

    # Timestamp fallback is permitted only within the same session and unsealed trace.
    if mutation_span["session_id"] != candidate_parent["session_id"]:
        raise CausalOrphanViolation(
            f"mutation {mutation_span['span_id']} session {mutation_span['session_id']} "
            f"!= candidate parent session {candidate_parent['session_id']}: timestamp proximity "
            f"across sessions is not causal"
        )
    return {**mutation_span, "parent_span_id": candidate_parent["span_id"], "orphan": False, "inferred": True}
