|
| 1 | +"""Ingestion heartbeat / stale-data alerts (Issue #758). |
| 2 | +
|
| 3 | +Exposes a health check that reports when no new ledger has been ingested |
| 4 | +for longer than a configurable threshold. The check is transport-agnostic |
| 5 | +so it can be reused by the FastAPI health router, CLI, or periodic probes. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import time |
| 11 | +from datetime import datetime, timedelta, timezone |
| 12 | +from typing import Final |
| 13 | + |
| 14 | +from astroml.ingestion.state import StateStore |
| 15 | +from astroml.observability.health import CheckResult, HealthStatus |
| 16 | + |
| 17 | +#: Default threshold at which ingestion is considered stale (seconds). |
| 18 | +DEFAULT_STALE_THRESHOLD_SECONDS: Final[int] = 300 |
| 19 | + |
| 20 | +#: Threshold at which ingestion is considered critically stale (seconds). |
| 21 | +#: Used when the caller does not supply an explicit fail threshold. |
| 22 | +DEFAULT_FAIL_THRESHOLD_SECONDS: Final[int] = 600 |
| 23 | + |
| 24 | + |
| 25 | +def _parse_timestamp(value: str | None) -> datetime | None: |
| 26 | + """Parse an ISO-8601 timestamp produced by ``StateStore``. |
| 27 | +
|
| 28 | + Args: |
| 29 | + value: ISO-8601 string, e.g. ``2024-01-01T00:00:00Z``. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + A timezone-aware UTC datetime, or ``None`` if parsing fails. |
| 33 | + """ |
| 34 | + if not value: |
| 35 | + return None |
| 36 | + try: |
| 37 | + # StateStore writes ``datetime.utcnow().isoformat() + "Z"``. |
| 38 | + return datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 39 | + except ValueError: |
| 40 | + return None |
| 41 | + |
| 42 | + |
| 43 | +def check_ingestion_heartbeat( |
| 44 | + state_store: StateStore, |
| 45 | + *, |
| 46 | + stale_threshold_seconds: float = DEFAULT_STALE_THRESHOLD_SECONDS, |
| 47 | + fail_threshold_seconds: float | None = None, |
| 48 | + now: datetime | None = None, |
| 49 | +) -> CheckResult: |
| 50 | + """Check whether the ingestion pipeline has processed a ledger recently. |
| 51 | +
|
| 52 | + Args: |
| 53 | + state_store: Store that tracks ``last_processed_at``. |
| 54 | + stale_threshold_seconds: Seconds without a new ledger before the |
| 55 | + check becomes ``DEGRADED``. |
| 56 | + fail_threshold_seconds: Seconds without a new ledger before the |
| 57 | + check becomes ``FAIL``. Defaults to twice the stale threshold. |
| 58 | + now: Optional reference time for tests. Defaults to UTC now. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + A :class:`CheckResult` named ``"ingestion_heartbeat"``. |
| 62 | + """ |
| 63 | + started = time.perf_counter() |
| 64 | + fail_threshold = fail_threshold_seconds or stale_threshold_seconds * 2 |
| 65 | + now = now or datetime.now(timezone.utc) |
| 66 | + |
| 67 | + try: |
| 68 | + state = state_store.load() |
| 69 | + except OSError as exc: |
| 70 | + return CheckResult( |
| 71 | + name="ingestion_heartbeat", |
| 72 | + status=HealthStatus.FAIL, |
| 73 | + details={"state_path": state_store.path, "error": str(exc)}, |
| 74 | + remediation=( |
| 75 | + "Cannot read ingestion state. Verify the state file path " |
| 76 | + "and that the process user has read access." |
| 77 | + ), |
| 78 | + duration_ms=(time.perf_counter() - started) * 1000, |
| 79 | + ) |
| 80 | + |
| 81 | + last_processed_at = _parse_timestamp(state.last_processed_at) |
| 82 | + |
| 83 | + if last_processed_at is None: |
| 84 | + return CheckResult( |
| 85 | + name="ingestion_heartbeat", |
| 86 | + status=HealthStatus.DEGRADED, |
| 87 | + details={ |
| 88 | + "last_processed_ledger": state.last_processed_ledger, |
| 89 | + "last_processed_at": state.last_processed_at, |
| 90 | + "stale_threshold_seconds": stale_threshold_seconds, |
| 91 | + "fail_threshold_seconds": fail_threshold, |
| 92 | + }, |
| 93 | + remediation=( |
| 94 | + "No ingestion timestamp has been recorded yet. " |
| 95 | + "Run an ingestion batch or verify the state store is being updated." |
| 96 | + ), |
| 97 | + duration_ms=(time.perf_counter() - started) * 1000, |
| 98 | + ) |
| 99 | + |
| 100 | + # Ensure comparison is timezone-aware. |
| 101 | + if last_processed_at.tzinfo is None: |
| 102 | + last_processed_at = last_processed_at.replace(tzinfo=timezone.utc) |
| 103 | + |
| 104 | + elapsed_seconds = (now - last_processed_at).total_seconds() |
| 105 | + |
| 106 | + if elapsed_seconds >= fail_threshold: |
| 107 | + status = HealthStatus.FAIL |
| 108 | + remediation = ( |
| 109 | + f"No ledger ingested for {elapsed_seconds:.0f}s " |
| 110 | + f"(fail threshold {fail_threshold:.0f}s). " |
| 111 | + "Investigate the ingestion worker, Horizon stream, and network connectivity." |
| 112 | + ) |
| 113 | + elif elapsed_seconds >= stale_threshold_seconds: |
| 114 | + status = HealthStatus.DEGRADED |
| 115 | + remediation = ( |
| 116 | + f"No ledger ingested for {elapsed_seconds:.0f}s " |
| 117 | + f"(stale threshold {stale_threshold_seconds:.0f}s). " |
| 118 | + "Check the ingestion worker logs for stalls or rate-limiting." |
| 119 | + ) |
| 120 | + else: |
| 121 | + status = HealthStatus.OK |
| 122 | + remediation = "" |
| 123 | + |
| 124 | + return CheckResult( |
| 125 | + name="ingestion_heartbeat", |
| 126 | + status=status, |
| 127 | + details={ |
| 128 | + "last_processed_ledger": state.last_processed_ledger, |
| 129 | + "last_processed_at": state.last_processed_at, |
| 130 | + "elapsed_seconds": round(elapsed_seconds, 2), |
| 131 | + "stale_threshold_seconds": stale_threshold_seconds, |
| 132 | + "fail_threshold_seconds": fail_threshold, |
| 133 | + }, |
| 134 | + remediation=remediation, |
| 135 | + duration_ms=(time.perf_counter() - started) * 1000, |
| 136 | + ) |
0 commit comments