# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-trace-correlation-across-federated-a2a-hops-when-the-caller-s-span-context-is-dropped-at-a-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-trace-correlation-across-federated-a2a-hops-when-the-caller-s-span-context-is-dropped-at-a-trust-boundary.warrant.json
# Markdown SHA-256:   340c3788351dddfa0ba8adfb312e1f1ccec63b9684f334cffb04da3d987b1942
# Code AST SHA-256:   e0324ee60224d9fda2ecce219ccafa15cdadfb39507c8f7c442daac598c9b52b
# Verified Classes:   TraceCorrelationBreak
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TraceCorrelationBreak(RuntimeError):
    """Raised when an A2A hop would sever the federated trace join key."""
    pass


def delegate_subtask(inbound_task_id: str | None,
                     inbound_context_id: str | None,
                     outbound_payload: dict) -> dict:
    # Hop-invariance invariant: the correlation key set at origin must be
    # forwarded verbatim. Reminting it orphans the downstream trace.
    if not inbound_task_id:
        raise TraceCorrelationBreak(
            "inbound task_id missing; refusing to delegate because the "
            "downstream span would be unattributable at incident time"
        )
    if not inbound_context_id:
        raise TraceCorrelationBreak(
            f"task {inbound_task_id} arrived without context_id; "
            "context must be forwarded, not reminted per hop"
        )

    # Attested-join: we do NOT adopt the caller's traceparent. We mint our
    # own trace_id and record the caller's asserted trace_id as an attribute,
    # so the join is reconstructible at query time without trusting the caller.
    outbound_payload = dict(outbound_payload)
    outbound_payload["task_id"] = inbound_task_id          # read-only
    outbound_payload["context_id"] = inbound_context_id    # read-only
    outbound_payload.setdefault("_correlation", {})["origin_task_id"] = inbound_task_id
    return outbound_payload
