# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-federated-trace-span-when-the-parent-context-is-a-dangling-reference.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-federated-trace-span-when-the-parent-context-is-a-dangling-reference.warrant.json
# Markdown SHA-256:   efdbe47dc021b236a0ec46d636305cdd27b983e3804f06d927de63047ae1634c
# Code AST SHA-256:   75206679ca68ee39fdd1431b99563966d3b3fe66e25adf70a5fda00aec7aba5d
# Verified Classes:   UnresolvedParentTraceError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnresolvedParentTraceError(RuntimeError):
    """Raised when a federated span is about to finalize without a resolvable parent."""
    pass


def finalize_federated_span(
    span_id: str,
    parent_span_id: str | None,
    parent_resolved: bool,
    elapsed_since_handoff_s: float,
    child_resolution_timeout_s: float,
    backend_assembly_window_s: float,
) -> dict:
    # Invariant: the child must resolve or mark before the backend re-roots.
    if child_resolution_timeout_s >= backend_assembly_window_s:
        raise UnresolvedParentTraceError(
            f"resolution timeout {child_resolution_timeout_s}s >= assembly window "
            f"{backend_assembly_window_s}s; child will finalize after backend re-roots"
        )

    if parent_span_id and not parent_resolved:
        if elapsed_since_handoff_s < child_resolution_timeout_s:
            # Hold open; do not finalize yet.
            return {"span_id": span_id, "state": "parent_pending"}
        # Window expired: finalize only with explicit unresolved marker.
        return {
            "span_id": span_id,
            "state": "finalized_degraded",
            "attributes": {
                "trace.parent_unresolved": True,
                "trace.parent_expected_span_id": parent_span_id,
            },
        }

    return {"span_id": span_id, "state": "finalized_clean"}
