Compare commits

...
Author SHA1 Message Date
David Santos 3abd4ab804 hotfix(hub): preserve production drift — slimContext/context_data + resolve endpoints
Production CT225 has uncommitted changes not in master:
- recentErrors.ts: add slimContext() to trim large context_data blobs
  and expose context_data in the recent-errors response
- admin-ui resolve-by-pattern/route.ts: new endpoint
- admin-ui resolve-fixed-patterns/route.ts: new endpoint

This commit preserves the drift so it can be PR-reviewed and merged
over 7bc04e8 (PR20).

Paperclip-Issue: BIT-33338
2026-11-25 12:18:20 +00:00
spark 954b0ced2e Merge pull request 'chore(hub): BIT-30701 add per-slug freshness override + exclude synthetic smoke-test events from fleet audit' (#15) from chore/BIT-30701-fleet-audit-per-slug-threshold-and-synthetic-filter into master
CI / Test ingest-api (push) Successful in 1m2s
CI / Test api (push) Successful in 1m11s
CI / Lint and typecheck admin-ui (push) Successful in 2m6s
CI / Validate Docker build (push) Successful in 5m11s
2026-09-28 08:22:42 +01:00
David Santos 9dd88db4ae chore(hub): BIT-30701 add per-slug freshness override + exclude synthetic smoke-test events from fleet audit
CI / Test ingest-api (pull_request) Successful in 55s
CI / Test api (pull_request) Successful in 1m1s
CI / Lint and typecheck admin-ui (pull_request) Successful in 2m9s
CI / Validate Docker build (pull_request) Successful in 5m55s
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] <actor> ... smoke test" marker convention from freshness scoring
so future liveness checks no longer pollute the metric.
2026-09-28 08:22:16 +01:00
spark 52e75a8760 Merge pull request 'chore(hub): BIT-30044 restore multi-status filter in fleet audit script' (#14) from chore/BIT-30044-restore-multistatus-audit-filter into master
CI / Test ingest-api (push) Successful in 1m28s
CI / Test api (push) Successful in 1m30s
CI / Lint and typecheck admin-ui (push) Successful in 2m42s
CI / Validate Docker build (push) Successful in 6m25s
2026-09-07 09:40:05 +01:00
David Santos b190d6fa1b chore(hub): BIT-30044 restore multi-status filter in fleet audit script
CI / Test ingest-api (pull_request) Successful in 54s
CI / Test api (pull_request) Successful in 1m6s
CI / Lint and typecheck admin-ui (pull_request) Successful in 2m37s
CI / Validate Docker build (pull_request) Successful in 6m56s
Revert the BIT-25722 workaround now that BIT-30040 fixed the recent-errors
mega-incident query hang (verified <1s in prod with status=open,investigating,resolved,ignored&limit=2000).
2026-09-07 09:39:28 +01:00
spark 3da9e47873 Merge pull request 'fix(hub): BIT-30040 stop ROW_NUMBER from materializing mega-incident partitions' (#13) from fix/BIT-30040-recent-errors-mega-incident-fastpath into master
CI / Test ingest-api (push) Successful in 1m26s
CI / Test api (push) Successful in 1m41s
CI / Lint and typecheck admin-ui (push) Successful in 3m28s
CI / Validate Docker build (push) Successful in 7m8s
2026-09-07 09:12:28 +01:00
David Santos a1fd3d2db0 fix(hub): BIT-30040 stop ROW_NUMBER from materializing mega-incident partitions
CI / Test ingest-api (pull_request) Successful in 1m9s
CI / Test api (pull_request) Successful in 1m22s
CI / Lint and typecheck admin-ui (pull_request) Successful in 2m30s
CI / Validate Docker build (pull_request) Successful in 8m52s
BIT-29730's incident-first fast path still ran ROW_NUMBER() OVER
(PARTITION BY incident_id ...) across ALL occurrences of every
selected incident before filtering rn = 1. MariaDB can't turn a
PARTITION BY window function into a loose index scan, so it
materializes and sorts each partition in full. At fleet-audit scale
(status=open,investigating,resolved,ignored&limit=2000) several
"mega-incidents" with 48k-148k occurrences each landed in the
selected page, and sorting those partitions hung the query for 70s+.

Replace the ROW_NUMBER CTE with a `LIMIT 1` correlated subquery per
selected incident. EXPLAIN confirms this walks
er_incident_occurrences_incident_time_idx (incident_id, occurred_at
DESC) and stops at the first row per incident instead of scanning the
rest of its history.

Verified against MariaDB (docker compose) seeded with the production
shape from the bug report (3235 resolved / 20 open incidents, 5
mega-incidents at 48k-148k occurrences each, ~425k occurrence rows
total): status=open,investigating,resolved,ignored&limit=2000 dropped
from 2.1s to 0.44s with identical result rows, and
status=resolved&limit=10 stayed at ~0.3s untouched by the
mega-incidents.
2026-09-07 09:05:52 +01:00
spark 7f76c5287d Merge pull request 'fix(hub): BIT-29730 stop timeout on GET recent-errors?status=resolved' (#12) from fix/BIT-29730-recent-errors-resolved-timeout into master
CI / Test ingest-api (push) Successful in 49s
CI / Test api (push) Successful in 50s
CI / Lint and typecheck admin-ui (push) Successful in 1m29s
CI / Validate Docker build (push) Successful in 4m27s
2026-08-24 09:02:38 +01:00
4 changed files with 185 additions and 26 deletions

No files matched your search

@@ -0,0 +1,47 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export async function POST(request: NextRequest) {
const rawBase = process.env.ERROR_REPORTING_ADMIN_API_BASE?.trim();
if (!rawBase) {
return NextResponse.json(
{
success: false,
message: "ERROR_REPORTING_ADMIN_API_BASE is not configured.",
},
{ status: 503 },
);
}
const base = rawBase.replace(/\/$/, "");
const target = `${base}/api/error-monitoring/resolve-by-pattern`;
const body = await request.text();
const headers: Record<string, string> = {
Accept: "application/json",
"Content-Type": request.headers.get("Content-Type") ?? "application/json",
};
const cookie = request.headers.get("cookie");
if (cookie) {
headers.Cookie = cookie;
}
const resolveHdr = request.headers.get("x-error-resolve-key");
if (resolveHdr) {
headers["X-Error-Resolve-Key"] = resolveHdr;
}
const upstream = await fetch(target, {
method: "POST",
headers,
body: body || undefined,
cache: "no-store",
});
const text = await upstream.text();
const ct = upstream.headers.get("Content-Type") ?? "application/json; charset=utf-8";
return new NextResponse(text, {
status: upstream.status,
headers: { "Content-Type": ct },
});
}
@@ -0,0 +1,47 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export async function POST(request: NextRequest) {
const rawBase = process.env.ERROR_REPORTING_ADMIN_API_BASE?.trim();
if (!rawBase) {
return NextResponse.json(
{
success: false,
message: "ERROR_REPORTING_ADMIN_API_BASE is not configured.",
},
{ status: 503 },
);
}
const base = rawBase.replace(/\/$/, "");
const target = `${base}/api/error-monitoring/resolve-fixed-patterns`;
const body = await request.text();
const headers: Record<string, string> = {
Accept: "application/json",
"Content-Type": request.headers.get("Content-Type") ?? "application/json",
};
const cookie = request.headers.get("cookie");
if (cookie) {
headers.Cookie = cookie;
}
const resolveHdr = request.headers.get("x-error-resolve-key");
if (resolveHdr) {
headers["X-Error-Resolve-Key"] = resolveHdr;
}
const upstream = await fetch(target, {
method: "POST",
headers,
body: body || undefined,
cache: "no-store",
});
const text = await upstream.text();
const ct = upstream.headers.get("Content-Type") ?? "application/json; charset=utf-8";
return new NextResponse(text, {
status: upstream.status,
headers: { "Content-Type": ct },
});
}
+46 -21
View File
@@ -100,6 +100,29 @@ function parseStatusList(raw: string | undefined): string[] | null {
return parts.length > 0 ? parts : ['open', 'investigating'];
}
function slimContext(ctx: Record<string, unknown> | null): Record<string, unknown> | null {
if (!ctx) return null;
const out: Record<string, unknown> = {};
for (const key of Object.keys(ctx).slice(0, 40)) out[key] = slimContextValue(ctx[key], 0);
return out;
}
function slimContextValue(value: unknown, depth: number): unknown {
if (depth > 3) return '[nested]';
if (typeof value === 'string') return value.length > 1500 ? `${value.slice(0, 1500)}…` : value;
if (value == null || typeof value === 'number' || typeof value === 'boolean') return value;
if (Array.isArray(value)) return value.slice(0, 20).map((item) => slimContextValue(item, depth + 1));
if (typeof value === 'object') {
const nested: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value as Record<string, unknown>).slice(0, 30)) {
nested[key] = slimContextValue(item, depth + 1);
}
return nested;
}
return String(value).slice(0, 500);
}
async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const db = request.server.db;
@@ -178,12 +201,18 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
let params: Array<string | number>;
if (!hasSearch) {
// Fast path (BIT-29730): page through er_incidents first (small, indexed by
// current_state) and only rank/scan occurrences for the selected page of
// incidents. Starting from er_incident_occurrences instead — as the search
// path below still does — makes the window function churn through the full
// occurrence history of every matching incident before LIMIT is applied,
// which times out for status=resolved (the majority, longest-lived state).
// Fast path (BIT-29730, tightened in BIT-30040): page through er_incidents
// first (small, indexed by current_state) and fetch only the single latest
// occurrence per selected incident via a correlated subquery. Earlier this
// still used ROW_NUMBER() over ALL occurrences of the selected incidents —
// MariaDB can't turn PARTITION BY into a loose index scan, so it
// materialized and sorted the entire occurrence history of every matching
// incident before filtering rn = 1. Fleet-audit-scale "mega-incidents"
// (100k+ occurrences each) blew that up to minutes even after the
// incident-first paging fix. A `LIMIT 1` correlated subquery per incident
// instead walks er_incident_occurrences_incident_time_idx
// (incident_id, occurred_at DESC) and stops at the first row — no
// materialization of the rest of that incident's history.
const incidentOrderDir = orderRaw === 'occurred_at_asc' ? 'ASC' : 'DESC';
sql = `
WITH selected_incidents AS (
@@ -193,18 +222,6 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
WHERE ${incidentWhereClause}
ORDER BY i.last_seen_at ${incidentOrderDir}, i.id ${incidentOrderDir}
LIMIT ? OFFSET ?
),
ranked AS (
SELECT o.id,
o.incident_id,
o.message,
o.stack_trace AS stack_trace,
o.context_json AS context_json,
o.environment,
o.occurred_at AS occurred_at,
ROW_NUMBER() OVER (PARTITION BY o.incident_id ORDER BY o.occurred_at DESC, o.id DESC) AS rn
FROM er_incident_occurrences o
INNER JOIN selected_incidents si ON si.incident_id = o.incident_id
)
SELECT CAST(i.id AS CHAR) AS incident_id,
CAST(r.id AS CHAR) AS occurrence_id,
@@ -216,10 +233,16 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
r.context_json,
r.environment,
r.occurred_at
FROM ranked r
INNER JOIN er_incidents i ON i.id = r.incident_id
FROM selected_incidents si
INNER JOIN er_incidents i ON i.id = si.incident_id
INNER JOIN er_projects p ON p.id = i.project_id
WHERE r.rn = 1
INNER JOIN er_incident_occurrences r ON r.id = (
SELECT o.id
FROM er_incident_occurrences o
WHERE o.incident_id = si.incident_id
ORDER BY o.occurred_at DESC, o.id DESC
LIMIT 1
)
ORDER BY ${orderSql}
`;
params = [...incidentParams, limit, offset];
@@ -303,6 +326,8 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
if (paperclip_project_id !== '') {
rowOut.paperclip_project_id = paperclip_project_id;
}
const contextData = slimContext(ctx);
if (contextData) rowOut.context_data = contextData;
return rowOut;
});
@@ -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
# ---------------------------------------------------------------------------
@@ -126,7 +135,7 @@ def _patch_json(url: str, payload: dict[str, Any], headers: dict[str, str] | Non
def fetch_hub_rows(hub_base: str, api_key: str, limit: int) -> list[dict[str, Any]]:
url = (
f"{hub_base}/api/error-monitoring/recent-errors"
f"?limit={limit}&order=occurred_at_desc&api_key={api_key}"
f"?limit={limit}&order=occurred_at_desc&status=open,investigating,resolved,ignored&api_key={api_key}"
)
# Use curl to avoid Cloudflare bot challenges on urllib
result = subprocess.run(
@@ -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"