# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-broken-traceparent-across-an-mcp-to-a2a-hop-when-the-downstream-task-id-is-minted-before-the-upstream-span-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-broken-traceparent-across-an-mcp-to-a2a-hop-when-the-downstream-task-id-is-minted-before-the-upstream-span-closes.warrant.json
# Markdown SHA-256:   f96f5b73fa36249a02c7c1375cf276b0fe67752e8d61f837802c7c7535bc6d6d
# Code AST SHA-256:   2b3ed7963026f17779d1b09e8f64f9abc62c35c14bfe2ed12ca88fe48c1c2f12
# Verified Classes:   TraceCorrelationSplit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TraceCorrelationSplit(RuntimeError):
    """Raised when an A2A task's trace context cannot be bound to its caller's span."""
    pass


def accept_remote_task(
    inbound_traceparent: str | None,
    caller_trace_id: str,
    allow_new_root: bool = False,
) -> str:
    """
    Callee-side task admission. Mints a taskId ONLY if the inbound trace
    context can be bound to the caller's announced trace. A missing or
    mismatched traceparent is a hard error unless a new root is declared.
    """
    if inbound_traceparent is None:
        if allow_new_root:
            return _mint_task_id(trace_id=None)  # declared orphan, auditable
        raise TraceCorrelationSplit(
            "A2A task rejected: inbound traceparent absent. "
            "Transport hop stripped the field; task would be uncorrelatable. "
            "Set allow_new_root=True only for genuinely parentless work."
        )

    parts = inbound_traceparent.split("-")
    if len(parts) != 4:
        raise TraceCorrelationSplit(f"Malformed traceparent: {inbound_traceparent!r}")

    _, trace_id, _span_id, _flags = parts
    if trace_id != caller_trace_id:
        raise TraceCorrelationSplit(
            f"Trace identity split: inbound trace_id={trace_id} "
            f"does not match caller's announced trace_id={caller_trace_id}. "
            f"This is the MCP-envelope-rewrite signature."
        )

    # Mint taskId INSIDE the inherited span so the join key and the
    # trace binding live in the same record.
    return _mint_task_id(trace_id=trace_id)


def _mint_task_id(trace_id: str | None) -> str:
    import uuid
    return f"tsk_{uuid.uuid4().hex[:12]}"
