# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-fracture-when-token-level-traces-desynchronize-from-its-own-decision-log-under-concurrent-tool-streaming.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-fracture-when-token-level-traces-desynchronize-from-its-own-decision-log-under-concurrent-tool-streaming.warrant.json
# Markdown SHA-256:   a8e1cac2b671d8feed9e9125f5cbe2380a1641c834497562dc27b2600a2a6e68
# Code AST SHA-256:   6d7580344421119557f26ec2b8b5842824181b073fcfd22bbfa32425cfc95d3e
# Verified Classes:   ProvenanceFracture, TokenSpan, DecisionCommit, TurnTrace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ProvenanceFracture(RuntimeError):
    """Raised when token-level trace cannot be soundly correlated to a committed decision."""
    pass


@dataclass
class TokenSpan:
    attempt_id: str
    token_index: int
    token: str
    speculative: bool = False


@dataclass
class DecisionCommit:
    plan_node: str
    rationale_hash: str
    attempt_id: str
    predecessor: Optional[str] = None


@dataclass
class TurnTrace:
    trace_id: str
    spans: list[TokenSpan] = field(default_factory=list)
    injections: list[tuple[int, str]] = field(default_factory=list)  # (token_index, payload_hash)


def reconstruct_rationale(spans: list[TokenSpan], attempt_id: str) -> str:
    """Committed tokens for one attempt, excluding speculative drafts, in index order."""
    committed = [s for s in spans if s.attempt_id == attempt_id and not s.speculative]
    committed.sort(key=lambda s: s.token_index)
    return "".join(s.token for s in committed)


def correlate(trace: TurnTrace, commit: DecisionCommit) -> None:
    # Fence 1: only one attempt may contribute tokens to a single commit.
    attempts = {s.attempt_id for s in trace.spans}
    if len(attempts) > 1:
        raise ProvenanceFracture(
            f"trace {trace.trace_id} carries tokens from attempts {sorted(attempts)} "
            f"but commit {commit.plan_node} names only {commit.attempt_id}; "
            f"retry splice would fabricate provenance"
        )

    # Fence 2: committed rationale must be recoverable from verified tokens.
    reconstructed = reconstruct_rationale(trace.spans, commit.attempt_id)
    actual_hash = hashlib.sha256(reconstructed.encode()).hexdigest()
    if actual_hash != commit.rationale_hash:
        raise ProvenanceFracture(
            f"rationale hash mismatch at {commit.plan_node}: "
            f"committed={commit.rationale_hash[:12]} reconstructed={actual_hash[:12]}; "
            f"token trace does not evidence the committed decision"
        )

    # Fence 3: every mid-stream injection must be anchored, not silently absorbed.
    for idx, payload_hash in trace.injections:
        if not any(s.token_index == idx - 1 for s in trace.spans):
            raise ProvenanceFracture(
                f"context injection at token {idx} ({payload_hash[:12]}) has no "
                f"anchoring token span; model conditioned on unrecorded content"
            )
