# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-correlate-a-cross-org-trace-when-privacy-preserving-sampling-has-silently-destroyed-the-join-key.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-correlate-a-cross-org-trace-when-privacy-preserving-sampling-has-silently-destroyed-the-join-key.warrant.json
# Markdown SHA-256:   6186927c222835064fe3b4fe65fa30b05930792bffd546ef59c2c20b73a334bd
# Code AST SHA-256:   1a83f67ddc45c0d42a5b9bee951af26596d4715c3ab4a8917187bdb2e81f08f4
# Verified Classes:   UnverifiableCorrelation, ExportManifest, ParentSpan, MatchedChild
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnverifiableCorrelation(RuntimeError):
    """Raised when a cross-org trace join cannot be proven to be a subgraph
    of the true causal DAG. Emitted instead of a correlated trace."""
    pass


@dataclass(frozen=True)
class ExportManifest:
    peer_id: str
    join_key_perturbed: bool
    decoy_namespace_reserved: bool  # decoys disjoint from live key space


@dataclass(frozen=True)
class ParentSpan:
    trace_id: str
    span_id: str
    expected_children: int
    max_subtree_size: int
    allowed_callees: frozenset[str]


@dataclass(frozen=True)
class MatchedChild:
    trace_id: str
    parent_span_id: str
    agent_pseudonym: str
    start_bucket: int
    parent_start_bucket: int


def correlate(
    parent: ParentSpan,
    children: list[MatchedChild],
    manifest: ExportManifest,
) -> list[MatchedChild]:
    # Guard 1: key-perturbation exclusion. If the peer perturbs join keys
    # without a reserved decoy namespace, no correlation is verifiable.
    if manifest.join_key_perturbed and not manifest.decoy_namespace_reserved:
        raise UnverifiableCorrelation(
            f"peer {manifest.peer_id} perturbs join keys without a reserved "
            f"decoy namespace; fabricated edges are indistinguishable from "
            f"real ones"
        )

    # Guard 2: fan-out reconciliation (upper bound, not lower).
    if len(children) > parent.expected_children:
        raise UnverifiableCorrelation(
            f"fan-out overflow on span {parent.span_id}: "
            f"{len(children)} matched > {parent.expected_children} declared"
        )

    # Guard 3: callee-set consistency. A perturbed key that collides with a
    # real span still usually surfaces a callee outside the declared set.
    for c in children:
        if c.agent_pseudonym not in parent.allowed_callees:
            raise UnverifiableCorrelation(
                f"span {parent.span_id} matched unauthorized callee "
                f"{c.agent_pseudonym}; possible key collision"
            )

    # Guard 4: causal monotonicity under bucketing.
    for c in children:
        if c.start_bucket < c.parent_start_bucket:
            raise UnverifiableCorrelation(
                f"causal inversion: child of {parent.span_id} starts before "
                f"parent bucket; fabricated edge suspected"
            )

    # Guard 5: subtree size bound.
    if len(children) > parent.max_subtree_size:
        raise UnverifiableCorrelation(
            f"reconstructed subtree exceeds declared max size for "
            f"{parent.span_id}"
        )

    return children


def emit_trace_or_marker(parent: ParentSpan, children: list[MatchedChild],
                         manifest: ExportManifest) -> dict:
    try:
        verified = correlate(parent, children, manifest)
        return {"status": "verified", "trace_id": parent.trace_id,
                "children": [c.__dict__ for c in verified]}
    except UnverifiableCorrelation as exc:
        # Emit an auditable marker instead of a fabricated trace.
        return {"status": "unverifiable", "trace_id": parent.trace_id,
                "reason": str(exc), "peer": manifest.peer_id}
