# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-cross-org-trace-correlation-poisoning-when-privacy-preserving-span-linking-silently-re-associates-forensic-spans-to-the-wr.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-cross-org-trace-correlation-poisoning-when-privacy-preserving-span-linking-silently-re-associates-forensic-spans-to-the-wr.warrant.json
# Markdown SHA-256:   0aac174eeffa9a246b5c5a865e99b1be477a92407a795fa894d72914858408da
# Code AST SHA-256:   959606fec2c52813e4501e4c9dc5a93801b7adf6fd6fa579aa5acdc69b5680f5
# Verified Classes:   LinkagePoisoningError, FederatedSpan, CorrelationEngine
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class LinkagePoisoningError(RuntimeError):
    """Raised when a federated correlation engine attempts to resolve an
    ambiguous span link by heuristic selection instead of declaring it
    UNRESOLVED. Selecting here is what silently re-associates forensic
    spans to the wrong agent lineage."""
    pass


@dataclass
class FederatedSpan:
    lineage_id: str
    span_id: str
    epoch_salt: str
    continuity_token: Optional[str] = None  # producer-signed, survives rotation
    duration_bucket: Optional[int] = None   # DP-noised


@dataclass
class CorrelationEngine:
    ambiguity_band: int = 2  # buckets of overlap treated as ambiguous
    known_lineages: dict = field(default_factory=dict)  # lineage_id -> last_bucket
    resolved: list = field(default_factory=list)
    unresolved: list = field(default_factory=list)

    def _candidate_lineages(self, span: FederatedSpan) -> list:
        if span.duration_bucket is None:
            return []
        return [
            lid for lid, bucket in self.known_lineages.items()
            if abs(bucket - span.duration_bucket) <= self.ambiguity_band
        ]

    def ingest(self, span: FederatedSpan) -> str:
        # Path 1: continuity token present -> verifiable link, no ambiguity.
        if span.continuity_token is not None:
            self.resolved.append(span)
            self.known_lineages[span.lineage_id] = span.duration_bucket or 0
            return "LINKED_VERIFIED"

        # Path 2: no token. If the ambiguity set is non-singleton, we MUST NOT select.
        candidates = self._candidate_lineages(span)
        if len(candidates) > 1:
            # The observed failure: a naive engine ranks candidates and picks one.
            # That is a protocol violation under a privacy-preserving contract.
            raise LinkagePoisoningError(
                f"span {span.span_id} from lineage {span.lineage_id} is ambiguous "
                f"across candidates {candidates}; heuristic selection would "
                f"re-associate forensic spans. Emit UNRESOLVED instead."
            )

        if len(candidates) == 1 and candidates[0] != span.lineage_id:
            # Single candidate but wrong lineage: also a re-association attempt.
            raise LinkagePoisoningError(
                f"span {span.span_id} claims lineage {span.lineage_id} but only "
                f"candidate is {candidates[0]}; refusing silent re-association."
            )

        # Genuinely unambiguous or no overlap: accept as unresolved-safe.
        self.unresolved.append(span)
        return "UNRESOLVED"


def correlate_batch(engine: CorrelationEngine, spans: list) -> dict:
    outcomes = {"LINKED_VERIFIED": 0, "UNRESOLVED": 0, "POISONED": 0}
    for span in spans:
        try:
            outcome = engine.ingest(span)
            outcomes[outcome] += 1
        except LinkagePoisoningError:
            outcomes["POISONED"] += 1
    return outcomes


# Reproduction of the observed failure trace.
if __name__ == "__main__":
    engine = CorrelationEngine(ambiguity_band=2)
    # L-4402 terminated earlier, bucket 10.
    engine.known_lineages["L-4402"] = 10

    spans = [
        # L-4417 call 12: post-rotation, no continuity token, DP bucket within
        # the ambiguity band of the terminated L-4402.
        FederatedSpan(lineage_id="L-4417", span_id="s12", epoch_salt="S2",
                      continuity_token=None, duration_bucket=11),
        # A properly signed span for contrast.
        FederatedSpan(lineage_id="L-4417", span_id="s13", epoch_salt="S2",
                      continuity_token="sig:O:4417:13", duration_bucket=11),
    ]
    print(correlate_batch(engine, spans))
    # Expected: the unsigned ambiguous span is refused, not re-associated.
