"""Durable clock-anomaly gate for new phases in both execution queues.""" from datetime import datetime, timezone, timedelta import json import math import os from pathlib import Path import time import uuid SHANGHAI = timezone(timedelta(hours=8)) class AdmissionClock: def __init__(self, path): self.path = Path(path) self.watermark = 0.0 self.closed_through = "" self.reason = None self.valid = True if self.path.exists(): try: data = json.loads(self.path.read_text(encoding="utf-8")) self.watermark = float(data["max_seen"]) self.closed_through = data["closed_through"] if not math.isfinite(self.watermark) or not 0 <= self.watermark <= 253402300799: raise ValueError("Invalid timestamp") datetime.fromisoformat(self.closed_through) except (ValueError, KeyError, TypeError, OSError): self.valid = False def observe(self, now=None): if not self.valid: self.reason = "clock_state_invalid" return False try: now = time.time() if now is None else float(now) if not math.isfinite(now): raise ValueError() local = datetime.fromtimestamp(now, timezone.utc).astimezone(SHANGHAI) except (ValueError, TypeError, OverflowError, OSError): self.reason = "clock_invalid" return False closed = (local.date() if local.hour >= 8 else local.date() - timedelta(days=1)).isoformat() next_closed = max(self.closed_through, closed) next_watermark = max(self.watermark, now) if int(next_watermark) > int(self.watermark) or next_closed != self.closed_through: temporary = self.path.with_name(self.path.name + "." + uuid.uuid4().hex + ".tmp") try: self.path.parent.mkdir(parents=True, exist_ok=True) with temporary.open("x", encoding="utf-8") as stream: json.dump({"max_seen": next_watermark, "closed_through": next_closed}, stream) stream.flush() os.fsync(stream.fileno()) os.replace(temporary, self.path) self.watermark, self.closed_through = (next_watermark, next_closed) except OSError: self.reason = "clock_state_unwritable" return False finally: try: temporary.unlink(missing_ok=True) except OSError: pass if now < self.watermark - 5: self.reason = "clock_rollback" return False if local.hour >= 21 or local.hour < 8: window_end = local.date() + timedelta(days=1) if local.hour >= 21 else local.date() if window_end.isoformat() <= self.closed_through: self.reason = "window_already_closed" return False self.reason = None return True