From 9dd88db4ae07659ceb5e13651fd0588ca6899bf9 Mon Sep 17 00:00:00 2001 From: David Santos Date: Mon, 28 Sep 2026 08:22:16 +0100 Subject: [PATCH] chore(hub): BIT-30701 add per-slug freshness override + exclude synthetic smoke-test events from fleet audit netvision's real error rate dropped sharply after the 2026-08-25..08-29 bug-fix wave; at the global 168h threshold the weekly audit fired 3 weeks running for a now-quiet app, not a broken pipe (BIT-30273/BIT-30527). Each investigation sent a synthetic verification event to confirm the reporter still works, but those events were then counted as "fresh" traffic by the next week's run, masking the real last-event date until the synthetic row itself aged past the threshold. Add PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES (CSV slug=hours) so a slug's threshold can differ from the global default, and exclude events matching the "[BIT-xxxxx] ... smoke test" marker convention from freshness scoring so future liveness checks no longer pollute the metric. --- ...erclip_fleet_error_reporting_audit_once.py | 48 +++++++++++++++++-- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/tools/paperclip/paperclip_fleet_error_reporting_audit_once.py b/tools/paperclip/paperclip_fleet_error_reporting_audit_once.py index 581fb72..8e5c0a3 100755 --- a/tools/paperclip/paperclip_fleet_error_reporting_audit_once.py +++ b/tools/paperclip/paperclip_fleet_error_reporting_audit_once.py @@ -11,6 +11,8 @@ Env vars lidos (ver /etc/paperclip/paperclip-fleet-error-audit.env): PAPERCLIP_FLEET_AUDIT_HUB_BASE — base URL do hub (default: https://errors.bitreport.pt) PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS — CSV de slugs esperados PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS — limiar de frescura (default: 168) + PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES — CSV "slug=horas" por slug (opcional, + sobrepõe o limiar global para esse slug) PAPERCLIP_FLEET_AUDIT_FETCH_LIMIT — rows a buscar (default: 2000) PAPERCLIP_FLEET_AUDIT_MIN_ROWS — mínimo de rows antes de enforcement (default: 20) PAPERCLIP_FLEET_AUDIT_PROJECT_ID — Paperclip project ID para issues de correção @@ -27,6 +29,7 @@ from __future__ import annotations import json import os +import re import subprocess import sys from collections import defaultdict @@ -36,6 +39,12 @@ from typing import Any from urllib import request as urllib_request from urllib.error import HTTPError, URLError +# Marker convention used for one-off pipe-liveness verification events (e.g. sent by +# hand while investigating a "stale" finding, per BIT-30273/BIT-30527). These are real +# hub rows but not production traffic — counting them as "fresh" masks genuine staleness +# for as long as they remain the newest row for a slug. Excluded from freshness scoring. +_SYNTHETIC_EVENT_RE = re.compile(r"^\[BIT-\d+\]\s+\S+.*smoke test", re.IGNORECASE) + # --------------------------------------------------------------------------- # Env helpers # --------------------------------------------------------------------------- @@ -144,21 +153,45 @@ def fetch_hub_rows(hub_base: str, api_key: str, limit: int) -> list[dict[str, An return data.get("data", []) +def _parse_max_age_overrides(raw: str) -> dict[str, int]: + overrides: dict[str, int] = {} + for part in raw.split(","): + part = part.strip() + if not part or "=" not in part: + continue + slug, _, hours_raw = part.partition("=") + slug = slug.strip().lower() + try: + hours = int(hours_raw.strip()) + except ValueError: + continue + if slug: + overrides[slug] = hours + return overrides + + def analyse_rows( rows: list[dict[str, Any]], expected_slugs: list[str], max_age_hours: int, min_rows: int, + max_age_overrides: dict[str, int] | None = None, ) -> dict[str, Any]: + max_age_overrides = max_age_overrides or {} now = datetime.now(timezone.utc) # Aggregate per slug by_slug: dict[str, list[datetime]] = defaultdict(list) + synthetic_skipped: dict[str, int] = defaultdict(int) for row in rows: slug = str(row.get("project_slug", "")).lower() occurred_at_raw = row.get("occurred_at", "") if not slug or not occurred_at_raw: continue + message = str(row.get("message") or row.get("error_message") or "") + if _SYNTHETIC_EVENT_RE.match(message.strip()): + synthetic_skipped[slug] += 1 + continue try: dt = datetime.fromisoformat(str(occurred_at_raw).replace("Z", "+00:00")) by_slug[slug].append(dt) @@ -171,6 +204,7 @@ def analyse_rows( results: list[dict[str, Any]] = [] for slug in expected_slugs: times = by_slug.get(slug, []) + slug_max_age = max_age_overrides.get(slug, max_age_hours) if not times: status = "silent" hours_since = None @@ -178,7 +212,7 @@ def analyse_rows( else: latest = max(times) hours_since = (now - latest).total_seconds() / 3600 - status = "stale" if hours_since > max_age_hours else "ok" + status = "stale" if hours_since > slug_max_age else "ok" results.append( { @@ -187,6 +221,8 @@ def analyse_rows( "event_count": len(times), "latest_occurred_at": latest.isoformat() if latest else None, "hours_since_last_event": round(hours_since, 1) if hours_since is not None else None, + "max_age_hours": slug_max_age, + "synthetic_events_excluded": synthetic_skipped.get(slug, 0), } ) @@ -283,6 +319,7 @@ def main() -> int: hub_api_key = _env("PAPERCLIP_ERROR_API_KEY") expected_slugs_raw = _env("PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS", "") max_age_hours = _env_int("PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS", 168) + max_age_overrides = _parse_max_age_overrides(_env("PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES", "")) fetch_limit = _env_int("PAPERCLIP_FLEET_AUDIT_FETCH_LIMIT", 2000) min_rows = _env_int("PAPERCLIP_FLEET_AUDIT_MIN_ROWS", 20) project_id = _env("PAPERCLIP_FLEET_AUDIT_PROJECT_ID") @@ -308,6 +345,8 @@ def main() -> int: print(f"Fleet audit starting — hub: {hub_base}") print(f"Expected slugs: {expected_slugs}") print(f"Max age: {max_age_hours}h, min rows: {min_rows}, fetch limit: {fetch_limit}") + if max_age_overrides: + print(f"Max age overrides: {max_age_overrides}") # Fetch hub data try: @@ -319,7 +358,7 @@ def main() -> int: print(f"Fetched {len(rows)} rows from hub") # Analyse - report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows) + report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows, max_age_overrides) print(json.dumps(report, indent=2, default=str)) # Determine problems @@ -352,10 +391,11 @@ def main() -> int: else: hours = p["hours_since_last_event"] latest = p["latest_occurred_at"] + slug_max_age = p["max_age_hours"] title = f"[fleet-audit] {slug} — stale ({hours:.0f}h sem eventos)" desc = ( f"O slug `{slug}` está stale: último evento há **{hours:.1f}h** " - f"(limiar: {max_age_hours}h).\n\n" + f"(limiar: {slug_max_age}h).\n\n" f"Último evento: `{latest}`\n" f"Hub: `{hub_base}`\n" f"Auditoria: {report['audited_at']}" @@ -396,7 +436,7 @@ def main() -> int: elif st == "stale": hours = r["hours_since_last_event"] icon = "⚠️" - detail = f"stale — último evento há {hours:.1f}h (limiar: {max_age_hours}h)" + detail = f"stale — último evento há {hours:.1f}h (limiar: {r['max_age_hours']}h)" else: icon = "🔴" detail = "silencioso — sem eventos"