# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-span-misbinding-in-genai-trace-correlation-across-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-span-misbinding-in-genai-trace-correlation-across-agent-hops.warrant.json
# Markdown SHA-256:   d631a5c26c8bb9949cdb9d9cefcfaadd8dfd4da3c071ff24222671a6f25bcb1e
# Code AST SHA-256:   9bf786afedbecab132dc788e4d3a18bf9deb51e1e392af2aec65bf0e99d7a627
# Verified Classes:   CausalSpanMisbindingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalSpanMisbindingError(RuntimeError):
    """Raised when a span tree is well-formed but its parent edges do not
    match the caller's emitted dispatch intent (misbound propagation)."""
    pass


def reconcile_children(parent_span, dispatch_manifest, observed_children):
    """
    parent_span:        dict with 'span_id' and 'task_id'
    dispatch_manifest:  dict {child_call_id: expected_child_span_id}
    observed_children:  list of dicts with 'span_id', 'parent_span_id', 'task_id'
    """
    expected = set(dispatch_manifest.values())
    observed = {c["span_id"] for c in observed_children
                if c["parent_span_id"] == parent_span["span_id"]}

    # 1. Every dispatched call must appear as a child of the caller.
    missing = expected - observed
    if missing:
        raise CausalSpanMisbindingError(
            f"parent {parent_span['span_id']} dispatched {len(expected)} calls "
            f"but {len(missing)} children are absent from the tree: {sorted(missing)}"
        )

    # 2. No child may appear that the caller did not dispatch.
    #    A retry parented to the caller's parent shows up here.
    extra = observed - expected
    if extra:
        raise CausalSpanMisbindingError(
            f"parent {parent_span['span_id']} has undispatched children "
            f"(likely misbound retry/fallback): {sorted(extra)}"
        )

    # 3. No child may belong to a different task than its parent.
    for c in observed_children:
        if c["parent_span_id"] == parent_span["span_id"] and \
           c["task_id"] != parent_span["task_id"]:
            raise CausalSpanMisbindingError(
                f"child {c['span_id']} (task {c['task_id']}) parented to "
                f"{parent_span['span_id']} (task {parent_span['task_id']}): "
                f"cached context reused across task boundary"
            )

    return True
