# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-trace-as-authoritative-the-non-determinism-watermark-boundary-in-telemetry-driven-agent-recons.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-trace-as-authoritative-the-non-determinism-watermark-boundary-in-telemetry-driven-agent-recons.warrant.json
# Markdown SHA-256:   6fbf596dd907ad7c147a4021f949e978e8b13ee72b865022f37c2f0c419d7bc6
# Code AST SHA-256:   724d00161e881b73b67d95b2430b4647cf97fab6bc11fd8ea5eab10cd64040b6
# Verified Classes:   WatermarkViolation, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass

NOISE_FLOOR_LOGPROB = 1e-2  # calibrate per backend; do not assume


class WatermarkViolation(RuntimeError):
    """Raised when a replay attempts to certify spans beyond the non-determinism watermark."""
    pass


@dataclass
class Span:
    index: int
    recorded_precondition_hash: str
    replayed_precondition_hash: str
    sampled_logprob: float
    next_best_logprob: float


def compute_watermark(spans: list[Span]) -> int:
    """Return the earliest span index that cannot be authoritatively reconstructed.

    Returns len(spans) if every span is reconstructable.
    """
    for s in spans:
        if s.recorded_precondition_hash != s.replayed_precondition_hash:
            return s.index
        margin = s.sampled_logprob - s.next_best_logprob
        if margin < NOISE_FLOOR_LOGPROB:
            return s.index
    return len(spans)


def certify_trace(spans: list[Span], claimed_authoritative_through: int) -> str:
    """Certify a replayed trace, refusing to certify past the watermark."""
    w = compute_watermark(spans)
    if claimed_authoritative_through > w:
        raise WatermarkViolation(
            f"trace claims authority through span {claimed_authoritative_through} "
            f"but watermark is at span {w}; spans >= {w} are re-executions, not reconstructions"
        )
    if w < len(spans):
        return f"PARTIAL: authoritative through span {w - 1}, forked at {w}"
    return "FULL: all spans reconstructed within determinism margin"


if __name__ == "__main__":
    # Original run: span 7 truncated to 4k tokens; replay fetched 11k. Hash mismatch.
    # Also: span 7 top-1 vs top-2 margin = 0.02, below noise floor of 0.01? No — 0.02 > 0.01.
    # Construct the observed failure: hash mismatch at span 7 AND near-tie at span 7.
    spans = [
        Span(i, f"h{i}", f"h{i}", -0.01, -0.50) for i in range(7)
    ] + [
        Span(7, "h7_orig", "h7_replay", -0.02, -0.04),  # hash drift + margin 0.02
    ]
    try:
        certify_trace(spans, claimed_authoritative_through=len(spans) - 1)
    except WatermarkViolation as e:
        print(f"REJECTED: {e}")
        print(certify_trace(spans, claimed_authoritative_through=6))
