# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-trace-stitching-from-silently-forking-at-delegated-sub-agent-boundaries-under-semantic-convention-compliant-observabil.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-trace-stitching-from-silently-forking-at-delegated-sub-agent-boundaries-under-semantic-convention-compliant-observabil.warrant.json
# Markdown SHA-256:   6d76101981d2e527eb0bb8bcaee3412db1ff9255465fba22832d70b7c69d9b6c
# Code AST SHA-256:   3459b48540ebc69adfed17158132313ff248ac2537d8835552791af6be326fb8
# Verified Classes:   TraceForkError, DelegationEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TraceForkError(RuntimeError):
    """Raised when a delegated sub-agent's root span cannot be causally
    parented to its issuing orchestrator span, or when a logical
    delegation yields more than one root (silent trace fork)."""
    pass


class DelegationEnvelope:
    def __init__(self, delegation_id: str, logical_delegation_id: str,
                 is_delegatee: bool, traceparent: str | None,
                 extracted_parent_span_id: str | None):
        self.delegation_id = delegation_id            # unique per attempt
        self.logical_delegation_id = logical_delegation_id  # stable across retries
        self.is_delegatee = is_delegatee
        self.traceparent = traceparent                # supplied in envelope
        self.extracted_parent_span_id = extracted_parent_span_id  # what propagator actually read


def emit_subagent_root_span(env: DelegationEnvelope) -> dict:
    """Decide whether the sub-agent may emit a root span, or must quarantine.

    The convention permits parentless roots; correctness does not, for a
    delegatee whose envelope carried a traceparent. This function enforces
    the invariant before export so the fork never reaches the stitcher.
    """
    if not env.is_delegatee:
        # Genuine top-level entry point: a root span is correct.
        return {"parent_span_id": None, "root": True, "quarantined": False}

    parent_supplied = env.traceparent is not None
    parent_resolved = env.extracted_parent_span_id is not None

    if parent_supplied and not parent_resolved:
        # Envelope carried a traceparent but the propagator never read it.
        # Emitting a clean root here is the silent fork.
        raise TraceForkError(
            f"delegatee {env.delegation_id}: traceparent present in envelope "
            f"but no parent span resolved; refusing to emit root span. "
            f"Quarantine with delegation.parent_unresolved=true."
        )

    if not parent_supplied:
        # No parent context at all: orchestrator-side protocol defect.
        # Emit as orphan candidate, not a clean root.
        return {
            "parent_span_id": None,
            "root": True,
            "quarantined": True,
            "attributes": {"delegation.orphan_candidate": True,
                           "delegation.logical_id": env.logical_delegation_id},
        }

    return {"parent_span_id": env.extracted_parent_span_id,
            "root": False, "quarantined": False}


def stitch_trace(roots: list[dict], logical_delegation_id: str) -> dict:
    """Stitcher-side gate: exactly one causally-parented root per logical
    delegation. Two roots under one logical delegation is a fork."""
    if len(roots) > 1:
        raise TraceForkError(
            f"logical delegation {logical_delegation_id} produced {len(roots)} "
            f"root spans; causal fork detected (retry reused delegation identity "
            f"or duplicate execution). Refusing to stitch a fabricated diamond."
        )
    root = roots[0]
    if root.get("quarantined"):
        raise TraceForkError(
            f"logical delegation {logical_delegation_id}: root span is an "
            f"orphan candidate with no resolved parent; causal edge missing."
        )
    return root
