# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-trace-corruption-when-a-single-prompt-fans-out-into-concurrent-retrievals-and-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-trace-corruption-when-a-single-prompt-fans-out-into-concurrent-retrievals-and-tool-calls.warrant.json
# Markdown SHA-256:   4662c65c85f7de7b5afefdcbbe6499312b8e82a2d91f67b8022fb40a371894dc
# Code AST SHA-256:   9034bdd9a093879013bfcf85c48fb8758b58ce82f2e79da41e07fb8fc33a1489
# Verified Classes:   TraceCorruptionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TraceCorruptionError(RuntimeError):
    """Raised when an assembler attempts to commit a causal edge not declared by the emitter."""
    pass


def commit_edge(span, declared_parent_id, resolved_parents, *, inferred=False):
    # Invariant: committed edges must be a subset of declared edges,
    # unless explicitly flagged as inferred and excluded from causal queries.
    if inferred:
        span.edge = None
        span.inferred = True
        return span

    if declared_parent_id is None:
        # Omission is distinct from UNKNOWN; omission is an emitter defect.
        raise TraceCorruptionError(
            f"span {span.id} emitted without parent_span_id; "
            "omission is not equivalent to UNKNOWN"
        )

    if declared_parent_id == "UNKNOWN":
        span.edge = None
        span.parent_unresolved = True
        return span

    if declared_parent_id not in resolved_parents:
        # Hold-and-flag: do not infer an edge from timestamp proximity.
        span.pending_parent = declared_parent_id
        return span

    span.edge = (declared_parent_id, span.id)
    span.inferred = False
    return span
