# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-level-trace-replay-diverge-from-the-causal-chain-it-claims-to-reconstruct-when-semantic-conventions-bind-span-attributes-at-emiss.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-level-trace-replay-diverge-from-the-causal-chain-it-claims-to-reconstruct-when-semantic-conventions-bind-span-attributes-at-emiss.warrant.json
# Markdown SHA-256:   18aeda6b552cf388783d26a0c40af533fd80b181c978686a525837ff32175bbb
# Code AST SHA-256:   338e53fea3f29b15c10ad355fb59bbedf4642905de6a27eb54d89a3e7070e084
# Verified Classes:   ConditioningUnverifiedError, ReplaySpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class ConditioningUnverifiedError(RuntimeError):
    """Raised when a replay span's conditioning context cannot be verified
    against recorded usage or hash, making content-dependent causal edges inadmissible."""

@dataclass
class ReplaySpan:
    span_id: str
    reconstructed_prompt: str
    recorded_input_tokens: int
    recorded_prompt_hash: str | None  # gen_ai.prompt.hash extension, if present
    tokenizer_drift_bound: int = 8

def verify_conditioning(span: ReplaySpan, tokenize) -> str:
    reconstructed_tokens = len(tokenize(span.reconstructed_prompt))
    drift = abs(reconstructed_tokens - span.recorded_input_tokens)

    if drift <= span.tokenizer_drift_bound:
        return "conditioning_verified"

    if span.recorded_prompt_hash is None:
        raise ConditioningUnverifiedError(
            f"span {span.span_id}: token drift {drift} exceeds bound "
            f"{span.tokenizer_drift_bound} and no gen_ai.prompt.hash present; "
            f"content-dependent causal edges inadmissible"
        )

    recomputed = hashlib.sha256(span.reconstructed_prompt.encode()).hexdigest()
    if recomputed != span.recorded_prompt_hash:
        raise ConditioningUnverifiedError(
            f"span {span.span_id}: prompt hash mismatch "
            f"(recorded {span.recorded_prompt_hash[:12]}..., "
            f"recomputed {recomputed[:12]}...); replay branch must halt"
        )
    return "conditioning_verified_with_drift"

def build_causal_edge(span: ReplaySpan, tokenize, claim: str) -> dict:
    status = verify_conditioning(span, tokenize)
    if status == "conditioning_verified_with_drift":
        # admissible, but annotate the edge so downstream consumers know drift occurred
        return {"span": span.span_id, "claim": claim, "status": status, "drift_annotated": True}
    return {"span": span.span_id, "claim": claim, "status": status, "drift_annotated": False}
