# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/without-what-explicit-timezone-and-monotonic-clock-anchors-must-an-instance-reject-temporal-comparisons-to-prevent-daylight-saving-and-ntp-skew-bugs.md # Remnant Warrant: https://corpusfetch.com/c/without-what-explicit-timezone-and-monotonic-clock-anchors-must-an-instance-reject-temporal-comparisons-to-prevent-daylight-saving-and-ntp-skew-bugs.warrant.json # Markdown SHA-256: 40197492dc1961825fd674b4bc1090e0327c0fd0e1dad58360ec146a78547900 # Code AST SHA-256: 65c3082f908ad51327d740191c24fd43c3fc129aba2a79a2dab12b0f51cbf26a # Verified Classes: TemporalClockAnchorGuard # Defensive Guards: 4 fail-closed invariants (zero external deps) import time from datetime import datetime, timezone from typing import Callable, TypeVar T = TypeVar("T") def utc_now() -> datetime: ''' Returns an explicit timezone-aware UTC datetime. Replaces deprecated datetime.utcnow() and ambiguous datetime.now(). ''' return datetime.now(timezone.utc) def ensure_aware_utc(dt: datetime | str) -> datetime: ''' Parses an ISO-8601 string or validates a datetime object, rejecting timezone-naive inputs and normalizing the result to strict UTC. ''' if isinstance(dt, str): # Support trailing 'Z' across Python versions normalized_str = dt[:-1] + "+00:00" if dt.endswith("Z") else dt parsed = datetime.fromisoformat(normalized_str) elif isinstance(dt, datetime): parsed = dt else: raise TypeError(f"Expected datetime or ISO string, got {type(dt).__name__}") # Gate 1: Reject timezone-naive datetimes outright if parsed.tzinfo is None or parsed.tzinfo.utcoffset(parsed) is None: raise ValueError( f"Rejected timezone-naive datetime {dt!r}. " "All calendar timestamps must carry an explicit timezone offset." ) # Gate 2: Convert any fixed/regional offset to canonical UTC return parsed.astimezone(timezone.utc) def poll_with_monotonic_deadline( predicate_fn: Callable[[], T | None], timeout_sec: float, poll_interval_sec: float = 0.05, ) -> T: ''' Polls predicate_fn until it returns a non-None result or timeout_sec elapses. Uses time.monotonic() so NTP wall-clock jumps cannot hang or prematurely abort the loop. ''' if timeout_sec <= 0: raise ValueError(f"timeout_sec must be positive, got {timeout_sec}") # Gate: Anchor deadline strictly to the kernel monotonic clock deadline = time.monotonic() + timeout_sec while True: result = predicate_fn() if result is not None: return result remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError(f"Operation timed out after {timeout_sec:.2f}s (monotonic)") time.sleep(min(poll_interval_sec, remaining)) class TemporalClockAnchorGuard: """Operational boundary reference implementation.""" utc_now = staticmethod(utc_now) ensure_aware_utc = staticmethod(ensure_aware_utc) poll_with_monotonic_deadline = staticmethod(poll_with_monotonic_deadline)