# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-partial-genai-semantic-convention-span-as-a-continuity-hazard-rather-than-a-completed-retrieval-event.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-partial-genai-semantic-convention-span-as-a-continuity-hazard-rather-than-a-completed-retrieval-event.warrant.json
# Markdown SHA-256:   f8884be34819a10ce6f89863ca57d857564172c3d5335191ba9efcb0353131b2
# Code AST SHA-256:   5c8430c4143fdebb1e81a9e4debeb0f3a2d9369849b275f0c55ffc39076931b4
# Verified Classes:   PartialRetrievalContinuityError, RetrieveSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class PartialRetrievalContinuityError(RuntimeError):
    """Raised when a retrieve span looks successful but its document set is
    under-populated relative to usage.input_tokens, so the watermark must not advance."""
    pass

@dataclass
class RetrieveSpan:
    data_source_id: str
    finish_reasons: list[str]
    input_tokens: int
    document_token_sum: int
    document_count: int
    expected_count: Optional[int] = None

# Tolerance band: document token sum may under-count due to tokenizer/estimate
# differences, but a gap beyond this fraction signals dropped document events.
TOKEN_RECONCILIATION_TOLERANCE = 0.10

def advance_watermark(span: RetrieveSpan, current_watermark: int) -> int:
    if span.finish_reasons and span.finish_reasons[0] != "stop":
        # Ordinary failed retrieval: watermark unchanged, no hazard.
        return current_watermark

    if span.expected_count is not None and span.document_count < span.expected_count:
        raise PartialRetrievalContinuityError(
            f"retrieve on {span.data_source_id!r} closed 'stop' but returned "
            f"{span.document_count}/{span.expected_count} documents; "
            f"watermark must not advance"
        )

    if span.input_tokens > 0:
        shortfall = 1.0 - (span.document_token_sum / span.input_tokens)
        if shortfall > TOKEN_RECONCILIATION_TOLERANCE:
            raise PartialRetrievalContinuityError(
                f"retrieve on {span.data_source_id!r} claims {span.input_tokens} input tokens "
                f"but document events account for only {span.document_token_sum} "
                f"({shortfall:.0%} shortfall); treat as partial, re-issue retrieve"
            )

    # Reconciliation passed: safe to advance.
    return current_watermark + span.document_count
