# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-a-federated-trace-s-causal-clock-when-its-parent-span-arrives-after-the-child-has-already-committed-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-a-federated-trace-s-causal-clock-when-its-parent-span-arrives-after-the-child-has-already-committed-side-effects.warrant.json
# Markdown SHA-256:   c9142e72ea850afc7df7147ffee09a03141df57bd50f0c5028e6bf10384d7efe
# Code AST SHA-256:   7ec7705e139f15c95b20247680ae28e2bd6decfdb37d234f6795aaadd446e217
# Verified Classes:   CausalityGapError, TraceContext, ChildRuntime
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class CausalityGapError(RuntimeError):
    """Raised when a side effect would commit before its parent context is pinned."""
    pass


@dataclass
class TraceContext:
    trace_id: str
    span_id: str
    hlc: int
    synthetic: bool = False


@dataclass
class ChildRuntime:
    runtime_id: str
    local_hlc: int = 0
    pinned_parent: Optional[TraceContext] = None
    drift_tolerance: int = 50  # HLC ticks; p99.9 of observed context-sync skew
    committed_effects: list = field(default_factory=list)

    def receive_context(self, parent: TraceContext) -> None:
        # HLC reconciliation: advance local clock past parent on receipt.
        self.local_hlc = max(self.local_hlc, parent.hlc + 1)
        if parent.synthetic:
            # Synthetic parents are never valid predecessors for side effects.
            raise CausalityGapError(
                f"runtime {self.runtime_id}: refusing synthetic parent "
                f"{parent.span_id}; mint a causal_gap marker, not a parent"
            )
        self.pinned_parent = parent

    def commit_side_effect(self, effect_key: str, tool: str) -> str:
        if self.pinned_parent is None:
            # The critical guard: no fallback root, no optimistic dispatch.
            raise CausalityGapError(
                f"runtime {self.runtime_id}: side effect '{tool}' attempted "
                f"before parent context pinned; block or fail, never synthesize"
            )
        if self.local_hlc - self.pinned_parent.hlc > self.drift_tolerance:
            raise CausalityGapError(
                f"runtime {self.runtime_id}: clock skew {self.local_hlc - self.pinned_parent.hlc} "
                f"exceeds tolerance {self.drift_tolerance}; reconcile HLC before commit"
            )
        # Effect is keyed to the *pinned* parent span, not a local root.
        keyed = f"{self.pinned_parent.span_id}/{effect_key}"
        self.committed_effects.append((tool, keyed, self.local_hlc))
        return keyed


def dispatch_with_barrier(rt: ChildRuntime, envelope: dict) -> str:
    """Envelope must carry trace context atomically with payload."""
    ctx = envelope.get("trace_context")
    if ctx is None:
        # Split-frame case: wait for context-sync, do not dispatch.
        raise CausalityGapError(
            f"runtime {rt.runtime_id}: envelope missing trace_context; "
            f"refuse dispatch until context_ready barrier observed"
        )
    rt.receive_context(ctx)
    return rt.commit_side_effect(envelope["effect_key"], envelope["tool"])
