# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/how-should-agents-detect-and-recover-from-silent-partial-results-during-streaming-inference.md # Remnant Warrant: https://corpusfetch.com/c/how-should-agents-detect-and-recover-from-silent-partial-results-during-streaming-inference.warrant.json # Markdown SHA-256: b3783eeeb8e07aecb6c17d548697e2fe5d098467a6f5e8a44e382f4ff27eaf1c # Code AST SHA-256: 35491cfc154d7fe3080ec33bdc012beec5ab0692db0bdc56cb8013b1950e2dca # Verified Classes: PartialStreamVerdict, StreamState, StreamPolicy, StreamManifest, PartialStreamGuard # Defensive Guards: 0 fail-closed invariants (zero external deps) from dataclasses import dataclass from enum import Enum, auto import hashlib import json class PartialStreamVerdict(Enum): COMPLETE_EXPLICIT = auto() COMPLETE_BY_LENGTH = auto() PARTIAL_MID_TOKEN = auto() PARTIAL_SAFE_BOUNDARY = auto() @dataclass(frozen=True) class StreamState: completion_signal_present: bool expected_length: int | None received_length: int terminal_byte_is_safe_boundary: bool @dataclass(frozen=True) class StreamPolicy: accept_partial_at_safe_boundary: bool @dataclass(frozen=True) class StreamManifest: verdict: PartialStreamVerdict directive: str manifest_digest: str class PartialStreamGuard: @staticmethod def _hash(data: str) -> str: return hashlib.sha256(data.encode("utf-8")).hexdigest() @classmethod def evaluate_stream( cls, state: StreamState, policy: StreamPolicy ) -> StreamManifest: # Gate 1: Explicit completion if state.completion_signal_present: digest = cls._hash(json.dumps({ "received": str(state.received_length), "completion": "EXPLICIT" }, sort_keys=True)) return StreamManifest( verdict=PartialStreamVerdict.COMPLETE_EXPLICIT, directive="PROCEED: Stream complete with explicit signal.", manifest_digest=digest ) # Gate 2: Length match if state.expected_length is not None and state.received_length == state.expected_length: digest = cls._hash(json.dumps({ "received": str(state.received_length), "expected": str(state.expected_length), "completion": "BY_LENGTH" }, sort_keys=True)) return StreamManifest( verdict=PartialStreamVerdict.COMPLETE_BY_LENGTH, directive=f"PROCEED: Stream length matches expected {state.expected_length}.", manifest_digest=digest ) # Gate 3: Safe boundary if state.terminal_byte_is_safe_boundary and policy.accept_partial_at_safe_boundary: digest = cls._hash(json.dumps({ "received": str(state.received_length), "boundary": "SAFE" }, sort_keys=True)) return StreamManifest( verdict=PartialStreamVerdict.PARTIAL_SAFE_BOUNDARY, directive="PROCEED_WITH_CAUTION: Partial stream at safe boundary. Verify downstream.", manifest_digest=digest ) # Gate 4: Mid-token partial return StreamManifest( verdict=PartialStreamVerdict.PARTIAL_MID_TOKEN, directive="HALT: Stream truncated mid-token. Re-fetch or repair.", manifest_digest=cls._hash(f"MID_TOKEN:{state.received_length}") )