Compare commits

..
Author SHA1 Message Date
David Santos 7987aa94ae fix(hub): BIT-29730 stop timeout on GET recent-errors?status=resolved
CI / Test ingest-api (pull_request) Successful in 1m13s
CI / Test api (pull_request) Successful in 1m12s
CI / Lint and typecheck admin-ui (pull_request) Successful in 1m45s
CI / Validate Docker build (pull_request) Successful in 5m11s
recent-errors built its result by ranking ALL occurrences of every
matching incident with ROW_NUMBER() before applying LIMIT, so
status=resolved (the majority, longest-lived incident state) forced a
scan of the full historical occurrence log just to return one page.
admin/incidents.ts already filters/orders er_incidents directly for
this reason; apply the same pattern here: page through er_incidents
first (small, indexed by current_state), then rank occurrences only
for that page. The q= search path is kept on the old occurrence-first
query since it needs to match occurrence content across an incident's
full history.

Adds er_incidents_state_seen_idx (current_state, last_seen_at) so the
new incident-first path stays indexed even without a project_slug
filter, and backfills the docker/local migration runners that had
drifted behind deploy/lxc/run-migrate.sh (missing three prior
migrations), since the new migration needs to run through them too.

Verified locally against MariaDB (docker compose) with 3k resolved /
20 open incidents and ~90k synthetic occurrences: the reported repro
curls now return HTTP 200 in <100ms (previously reproduced as a hang
via manual EXPLAIN/timing of the old query, ~2s at this seed size and
scaling with total occurrence history).
2026-08-24 08:32:26 +01:00
David Santos 308ff624cf fix(noise): remove stale_bundle_* rules — functions no longer exist (BIT-26793)
CI / Test ingest-api (push) Successful in 54s
CI / Test api (push) Successful in 58s
CI / Lint and typecheck admin-ui (push) Successful in 1m29s
CI / Validate Docker build (push) Successful in 5m0s
switchSelectionEditorTab and descriptionEditorReady are absent from the
current codebase; continuing to suppress ReferenceErrors for these names
would silently hide real errors if the names were ever reused. Ruleset
bumped to 1.0.7.
2026-07-17 23:02:36 +00:00
David Santos 23704d2e59 feat(ingest): label er_ingest_events_total skipped_noise by rule_id
CI / Test api (push) Successful in 54s
CI / Test ingest-api (push) Successful in 57s
CI / Lint and typecheck admin-ui (push) Successful in 1m48s
CI / Validate Docker build (push) Successful in 5m19s
Break down noise filter counters per noise policy rule for Prometheus observability.

Paperclip-Agent: David Santos (urlKey david-santos; id 0b1fcf92-5fe3-4ac0-9f29-df4ab72f5376)
Paperclip-Issue: BIT-26791
Paperclip-Run: cea24469-2886-457d-9f6f-09d83aaf9e4a
2026-07-17 23:01:35 +00:00
David Santos caeb37ff0a feat(hub): time-limited fixed patterns — expire after N days (BIT-26790)
CI / Test ingest-api (push) Successful in 48s
CI / Test api (push) Successful in 47s
CI / Lint and typecheck admin-ui (push) Successful in 1m20s
CI / Validate Docker build (push) Successful in 4m29s
Add optional addedAt + expiresAfterDays to FixedPattern so each pattern
has a TTL. The resolve-fixed-patterns handler now skips expired patterns,
letting persistent errors resurface and forcing a real code fix instead
of indefinite suppression.

- Transient infra patterns (WSREP, Google API, session write) carry addedAt
  for audit but no expiry — they are permanent noise with no code fix.
- fix-duplicate-logo.js expires 14 days after 2026-07-17; if still firing
  after that the deploy or client filter is broken and needs attention.
- Response includes expired_pattern_count and per-pattern expired/expires_at.
2026-07-17 22:42:56 +00:00
David Santos 37ab9f1ccb fix(hub): BIT-25223 add fix-duplicate-logo.js resolve pattern + auto-apply on deploy
CI / Test api (push) Successful in 1m8s
CI / Test ingest-api (push) Successful in 1m9s
CI / Lint and typecheck admin-ui (push) Successful in 1m30s
CI / Validate Docker build (push) Successful in 5m22s
- resolveFixedPatterns.ts: add '%fix-duplicate-logo.js%' entry so any
  Chrome-style CRM JS error that reaches the hub is auto-resolved on deploy
- webhook-deploy.sh: call resolve-fixed-patterns after every service restart
  so code fixes clear stale hub incidents automatically (uses ERROR_RESOLVE_API_KEY
  from /etc/error-reporting/env which is already sourced by the script)

The 5 open incidents for ERRCLUSTER:33b4e527d8fd were bulk-resolved directly
(IDs 747145, 747381, 753209, 753550, 753551). Client-side noise filter (CRM PR #684)
prevents new occurrences.
2026-07-17 22:20:18 +00:00
David Santos 615d771ade fix(tools): drop multi-status filter in fleet audit — hub times out on comma-separated status values
CI / Test ingest-api (push) Failing after 40s
CI / Lint and typecheck admin-ui (push) Failing after 43s
CI / Validate Docker build (push) Failing after 42s
CI / Test api (push) Failing after 10m49s
Paperclip-Task-Id: BIT-25722
2026-06-22 07:22:16 +00:00
David SantosandPaperclip 3c307ea32d feat(hub): accept and expose paperclip_project_id on error records (BIT-25537)
- php-error bridge: accept paperclip_project_id / paperclipProjectId in
  CrmPhpPayload and promote into event context alongside project_slug/gitea_repo
- recent-errors: extract paperclip_project_id from context_json and emit as
  top-level field so error loop can route issues to the correct project board
  column without falling back to PAPERCLIP_ERROR_LOOP_PROJECT_ID_BY_SLUG
- Add tests for include/omit behaviour (mirrors gitea_repo coverage)
- Update ERROR_MONITORING_PUBLIC_API.md to document both optional fields

No DB migration required: field is stored in existing context_json column.

Co-Authored-By: Paperclip <[email protected]>
2026-06-18 02:15:49 +00:00
David SantosandPaperclip be735a16b6 feat(tools): add fleet error reporting audit script (BIT-25194)
CI / Test ingest-api (push) Successful in 2m18s
CI / Test api (push) Successful in 2m24s
CI / Lint and typecheck admin-ui (push) Successful in 3m14s
CI / Validate Docker build (push) Successful in 12m14s
Weekly routine that queries errors.bitreport.pt for each expected slug,
checks freshness against a configurable threshold, and creates Paperclip
correction issues for silent or stale reporters. Reads config from
/etc/paperclip/paperclip-fleet-error-audit.env.

Paperclip-Task-Id: BIT-25194
Co-Authored-By: Paperclip <[email protected]>
2026-06-15 07:21:16 +00:00
tiago-nevesandPaperclip 050a380230 fix(admin-ui): proxy /api/error-monitoring/* to Fastify API (BIT-25083)
CI / Test ingest-api (push) Successful in 1m51s
CI / Test api (push) Successful in 1m50s
CI / Lint and typecheck admin-ui (push) Successful in 2m15s
CI / Validate Docker build (push) Successful in 7m29s
Next.js catches /api/* before Fastify, causing 404 on resolve-fixed-patterns.
Add rewrite so external callers (error-loop via CRM_RESOLVE_API_URL) reach
the hub Fastify API on port 3200 via the canonical errors.bitreport.pt URL.

Paperclip-Issue: BIT-25083
Co-Authored-By: Paperclip <[email protected]>
2026-06-14 02:23:41 +00:00
spark bebbfb3e57 Merge pull request 'feat(hub): add resolve-fixed-patterns endpoint for CRM routing parity (BIT-25072)' (#11) from task/BIT-25072-resolve-fixed-patterns into master
CI / Test ingest-api (push) Successful in 2m52s
CI / Test api (push) Successful in 2m53s
CI / Lint and typecheck admin-ui (push) Successful in 3m14s
CI / Validate Docker build (push) Successful in 12m41s
feat(hub): add resolve-fixed-patterns endpoint for CRM routing parity (BIT-25072)
2026-06-14 02:04:22 +01:00
David Santos 7fe045d314 feat(hub): add resolve-fixed-patterns endpoint for CRM routing parity (BIT-25072)
CI / Test ingest-api (pull_request) Successful in 2m12s
CI / Test api (pull_request) Successful in 2m12s
CI / Lint and typecheck admin-ui (pull_request) Successful in 2m51s
CI / Validate Docker build (pull_request) Successful in 15m33s
POST /api/error-monitoring/resolve-fixed-patterns — resolves hub incidents
matching known-fixed/transient patterns from config/resolveFixedPatterns.ts.
Fixes 404 from run-error-loop-with-resolve.sh when CRM_RESOLVE_API_URL points
to the hub (CRM module removed in BIT-24199; hub now owns all error monitoring).

Patterns file is extensible; initial set covers Galera/WSREP transients,
Google API backendError, session_write_close cascades, and storage COMMIT noise.

Paperclip-Issue: BIT-25072
Paperclip-Agent: tiago-neves
2026-06-13 22:36:56 +00:00
spark 1181093739 Merge pull request 'docs(deploy): add .env runtime preservation rule (BIT-25008)' (#10) from task/BIT-25008-env-preservation into master
CI / Test ingest-api (push) Successful in 1m4s
CI / Test api (push) Successful in 2m3s
CI / Lint and typecheck admin-ui (push) Successful in 2m28s
CI / Validate Docker build (push) Successful in 13m22s
2026-06-11 17:31:48 +01:00
David SantosandPaperclip 2b8976551f docs(deploy): add .env runtime preservation rule (BIT-25008)
CI / Test ingest-api (pull_request) Successful in 2m7s
CI / Test api (pull_request) Successful in 2m11s
CI / Lint and typecheck admin-ui (pull_request) Successful in 3m21s
CI / Validate Docker build (pull_request) Successful in 15m49s
Adds .cursor/rules/bitreport-env-preservation.mdc enforcing DEPLOY_STANDARD.md §3.1.

Co-Authored-By: Paperclip <[email protected]>
2026-06-11 16:25:57 +00:00
spark 8bb129ac77 Merge pull request 'docs(deploy): add .env runtime preservation rules (BIT-25005)' (#9) from task/BIT-25008-env-preservation into master
CI / Test ingest-api (push) Successful in 1m29s
CI / Test api (push) Successful in 56s
CI / Lint and typecheck admin-ui (push) Successful in 2m37s
CI / Validate Docker build (push) Successful in 21m52s
docs(deploy): add .env runtime preservation rules (BIT-25005)
2026-06-11 17:13:56 +01:00
David Santos f19ff03dd6 docs(deploy): add .env runtime preservation rules (BIT-25005)
CI / Test ingest-api (pull_request) Successful in 1m35s
CI / Test api (pull_request) Successful in 2m14s
CI / Lint and typecheck admin-ui (pull_request) Successful in 3m1s
CI / Validate Docker build (pull_request) Successful in 24m7s
Propagate DEPLOY_STANDARD.md §3.1: add warning that cp .env.example .env is
only for initial bootstrap, prohibit overwriting existing prod .env, mandate
PRODUCTION_ACCESS_SYNC_LOG entries for ER_MYSQL_* changes.

Paperclip-Task: BIT-25008
2026-06-11 15:37:24 +00:00
spark 47f77e85de Merge pull request 'feat(hub): retire WDMI projects from error reporting (BIT-24704)' (#8) from task/BIT-24704-retire-wdmi into master
CI / Test ingest-api (push) Successful in 14m57s
CI / Test api (push) Successful in 19m18s
CI / Lint and typecheck admin-ui (push) Successful in 20m37s
CI / Validate Docker build (push) Failing after 11m9s
Merge BIT-24704: retire WDMI projects from error reporting

Revokes all WDMI-family ingest keys, deactivates collector sources,
and deletes project rows. ingest-api now returns 401 for retired slugs.

Deploy issue: BIT-24705
2026-06-08 15:44:48 +01:00
25 changed files with 964 additions and 39 deletions

No files matched your search

@@ -0,0 +1,29 @@
---
alwaysApply: true
---
# Deploy: nunca sobrescrever `.env` de produção (BIT-25005)
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
## Proibido em scripts de deploy e agentes
| Proibido | Alternativa |
|----------|------------|
| `cp .env.example .env` sobre `.env` **já existente** em produção | `git pull` / rsync **excluindo** `.env` |
| Escrever `root`, `changeme`, `password` ou superuser como credencial de BD em produção | Valores da vault; documentar chaves novas em `.env.example` **vazias** |
| Alterar `DB_*` / `DATABASE_*` / `MYSQL_*` no host sem issue, rollback e log | Entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo) antes de aplicar |
## Regras obrigatórias
1. Scripts de deploy devem **falhar** (`exit 1`) se um passo tentaria sobrescrever um `.env` existente com conteúdo de exemplo.
2. Usar **`rsync --exclude='.env'`** (e paths documentados por serviço) ou `git pull` sem toque no `.env`.
3. Pós-deploy: validar que variáveis críticas **não** regressaram a placeholders (`changeme`, `root`, `password`, `secret`, etc.).
4. Qualquer alteração a `.env` de produção requer: issue explícita, plano de rollback, e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md`.
## Quando a regra se aplica
- Todos os scripts de deploy (webhook, CI, manual).
- Agentes que editam, geram ou sugerem alterações a ficheiros `.env`, `.env.example`, `docker-compose.yml` com variáveis de ambiente, ou scripts que copiam/escrevem ficheiros de configuração em produção.
**Referência:** `docs/DEPLOY_STANDARD.md` §3.1 no meta-repo `paperclip` (regra canónica).
@@ -35,6 +35,9 @@ interface CrmPhpPayload {
project_slug?: unknown;
project_name?: unknown;
gitea_repo?: unknown;
// Paperclip project UUID — used by error loop to route issues to the correct project board column
paperclip_project_id?: unknown;
paperclipProjectId?: unknown;
}
function safeStr(v: unknown): string {
@@ -94,9 +97,11 @@ export async function POST(request: NextRequest) {
const gitea_repo = safeStr(body.gitea_repo);
const project_slug = safeStr(body.project_slug);
const project_name = safeStr(body.project_name);
const paperclip_project_id = safeStr(body.paperclip_project_id || body.paperclipProjectId);
if (gitea_repo) contextData.gitea_repo = gitea_repo;
if (project_slug) contextData.project_slug = project_slug;
if (project_name) contextData.project_name = project_name;
if (paperclip_project_id) contextData.paperclip_project_id = paperclip_project_id;
// Preserve other top-level diagnostic fields.
const file_path = safeStr(body.file_path);
+13
View File
@@ -7,6 +7,15 @@ import type { NextConfig } from "next";
const INGEST_API_URL =
process.env.INGEST_API_URL || "http://127.0.0.1:3041";
/**
* Admin/mutation API backend (same LXC, port 3200).
* Proxies hub-only mutation endpoints (resolve-fixed-patterns, etc.) so they are
* reachable via the public errors.bitreport.pt hostname without a separate FQDN.
* BIT-25072: resolve-fixed-patterns is hub-only; CRM error-loop calls this via HTTPS.
*/
const ADMIN_API_URL =
process.env.ERROR_REPORTING_ADMIN_API_BASE || "http://127.0.0.1:3200";
const nextConfig: NextConfig = {
output: "standalone",
reactStrictMode: true,
@@ -15,6 +24,10 @@ const nextConfig: NextConfig = {
return [
{ source: "/health", destination: `${INGEST_API_URL}/health` },
{ source: "/v1/:path*", destination: `${INGEST_API_URL}/v1/:path*` },
{
source: "/api/error-monitoring/:path*",
destination: `${ADMIN_API_URL}/api/error-monitoring/:path*`,
},
];
},
};
+4
View File
@@ -55,6 +55,10 @@ Each row includes CRM-compatible fields. For non-resolved incidents, `status` is
**`stack_trace`:** Non-empty for every row: missing client stacks are synthesized on ingest; legacy DB rows with null/blank `stack_trace` get the same synthesis when serializing this endpoint (BIT-1008).
**`gitea_repo`** *(optional)*: Gitea `Owner/Repo` path (e.g. `BitReport.pt/WDMI`) if the reporter sent `gitea_repo` in the error payload. Omitted when not present.
**`paperclip_project_id`** *(optional)*: Paperclip project UUID sent by the reporter (via `paperclip_project_id` or `paperclipProjectId` payload field). When present, the Paperclip error loop uses this UUID directly to route issues to the correct project board column instead of falling back to the `PAPERCLIP_ERROR_LOOP_PROJECT_ID_BY_SLUG` env map. Omitted when not present.
**Example**
```bash
+69
View File
@@ -0,0 +1,69 @@
/**
* Known-resolved error patterns for the hub resolve-fixed-patterns endpoint (BIT-25072).
* Each entry matches against er_incident_occurrences.message (via LIKE or exact).
*
* Schema: { messagePatterns, note, addedAt?, expiresAfterDays? }
* messagePatterns: SQL LIKE patterns (use % wildcards). All patterns in an entry are AND-ed.
* note: human-readable reason / fix reference (written to er_incident_state_history.change_note).
* addedAt: ISO date when this pattern was added (YYYY-MM-DD).
* expiresAfterDays: if set, the pattern stops auto-resolving this many days after addedAt.
* This forces errors that persist beyond the grace period back to open state, ensuring the
* fix landed in code and wasn't just hidden. Omit for permanent patterns (transient infra noise
* with no code fix expected). See BIT-26790.
*
* Transient infrastructure errors: noise from known-bad infra states that self-resolve.
* Fixed code errors: added after the fix is deployed to production — set expiresAfterDays.
*/
export interface FixedPattern {
/** Each element becomes: o.message LIKE ? (all AND-ed together for this entry). */
messagePatterns: string[];
note: string;
/** ISO date (YYYY-MM-DD) when this pattern was added. */
addedAt?: string;
/**
* Days after addedAt when this pattern expires and stops auto-resolving.
* Expired patterns are skipped so the error resurfaces if it still occurs,
* signalling that the code fix hasn't landed yet. Omit for permanent patterns.
*/
expiresAfterDays?: number;
}
const patterns: FixedPattern[] = [
// Galera/WSREP cluster transient — node not ready
{
messagePatterns: ['%WSREP has not yet prepared node%'],
note: 'Transient: Galera cluster node not ready; infrastructure',
addedAt: '2026-06-13',
},
// Google API backendError — transient external
{
messagePatterns: ['%Internal error encountered%', '%backendError%'],
note: 'Transient: Google API 500 backendError; external; no code fix',
addedAt: '2026-06-13',
},
// Session write fails when DB is unavailable (cascading)
{
messagePatterns: ['%session_write_close(): Failed to write session data%'],
note: 'Transient: cascades from DB unavailability; no code fix',
addedAt: '2026-06-13',
},
// Storage / COMMIT transient
{
messagePatterns: ['%No such device or address%'],
note: 'Transient: storage/infrastructure during COMMIT; retry on next request',
addedAt: '2026-06-13',
},
// CRM: fix-duplicate-logo.js load failure (BIT-25223 ERRCLUSTER:33b4e527d8fd)
// File is present and protected by CopyWebpackPlugin + deploy gate; client-side noise
// filter (PR #684) suppresses at source. Chrome-style messages include the URL; this
// pattern resolves any that still reach the hub. Firefox-style resolved by bulk-resolve.
// Expires after 14 days — if still occurring after that, the deploy or filter is broken.
{
messagePatterns: ['%fix-duplicate-logo.js%'],
note: 'Fixed: fix-duplicate-logo.js present + protected (BIT-25223); client noise filter PR #684',
addedAt: '2026-07-17',
expiresAfterDays: 14,
},
];
export default patterns;
@@ -3,11 +3,13 @@
* POST /api/error-monitoring/resolve
* POST /api/error-monitoring/bulk-resolve
* POST /api/error-monitoring/resolve-by-pattern
* POST /api/error-monitoring/resolve-fixed-patterns
* POST /api/error-monitoring/purge-resolved
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { ResultSetHeader, RowDataPacket } from 'mysql2';
import fixedPatterns from '../../config/resolveFixedPatterns.js';
import {
authorizeMutation,
changedByRef,
@@ -611,10 +613,136 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply)
});
}
async function handleResolveFixedPatterns(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const db = request.server.db;
const body = parseJsonBody(request.body);
const auth = await authorizeMutation(request, reply, body, 'errors:triage');
if (!auth) {
return;
}
const dryRun = Boolean(body.dry_run);
const { type, ref } = changedByRef(auth);
const details: Array<{
note: string;
resolved?: number;
would_resolve?: number;
expired?: boolean;
expires_at?: string;
}> = [];
let total = 0;
let expiredCount = 0;
const nowMs = Date.now();
for (const pattern of fixedPatterns) {
if (pattern.messagePatterns.length === 0) {
continue;
}
// Skip patterns that have passed their expiry window (BIT-26790).
// Expired patterns stop suppressing so the error resurfaces if still present.
if (pattern.addedAt && pattern.expiresAfterDays !== undefined) {
const addedMs = new Date(pattern.addedAt).getTime();
const expiresAt = new Date(addedMs + pattern.expiresAfterDays * 86_400_000);
if (nowMs > expiresAt.getTime()) {
expiredCount += 1;
details.push({ note: pattern.note, expired: true, expires_at: expiresAt.toISOString().slice(0, 10) });
continue;
}
}
const likeClauses = pattern.messagePatterns.map(() => 'o.message LIKE ?').join(' AND ');
const params: string[] = pattern.messagePatterns;
const [countRows] = await db.execute<RowDataPacket[]>(
`SELECT COUNT(DISTINCT i.id) AS c
FROM er_incidents i
INNER JOIN er_incident_occurrences o ON o.incident_id = i.id
WHERE i.current_state IN ('open','investigating')
AND (${likeClauses})`,
params,
);
const n = Number((countRows[0] as { c?: number }).c ?? 0);
if (n === 0) {
continue;
}
if (dryRun) {
total += n;
details.push({ note: pattern.note, would_resolve: n });
continue;
}
const [matchRows] = await db.execute<RowDataPacket[]>(
`SELECT DISTINCT CAST(i.id AS CHAR) AS incident_id,
CAST(i.project_id AS CHAR) AS project_id,
i.current_state AS current_state
FROM er_incidents i
INNER JOIN er_incident_occurrences o ON o.incident_id = i.id
WHERE i.current_state IN ('open','investigating')
AND (${likeClauses})`,
params,
);
const targets = (matchRows as Record<string, unknown>[]).map((r) => ({
incidentId: String(r.incident_id),
projectId: String(r.project_id),
currentState: String(r.current_state),
}));
let resolved = 0;
const conn = await db.getConnection();
try {
await conn.beginTransaction();
for (const row of targets) {
const [upd] = await conn.execute<ResultSetHeader>(
`UPDATE er_incidents
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
WHERE id = ? AND current_state IN ('open','investigating')`,
[row.incidentId],
);
if (upd.affectedRows === 0) {
continue;
}
await conn.execute(
`INSERT INTO er_incident_state_history
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
[row.incidentId, row.projectId, row.currentState, type, ref, pattern.note],
);
resolved += upd.affectedRows;
}
await conn.commit();
} catch (e) {
await conn.rollback();
throw e;
} finally {
conn.release();
}
total += resolved;
details.push({ note: pattern.note, resolved });
}
if (!dryRun) {
await auditMutation(request.server, request, auth, 'error_monitoring.resolve_fixed_patterns', 'batch', {
resolved: total,
pattern_count: fixedPatterns.length,
expired_pattern_count: expiredCount,
});
}
return void reply.send({
success: true,
message: dryRun ? `Would resolve ${total} incidents` : `Resolved ${total} incidents`,
data: { total, dry_run: dryRun, expired_pattern_count: expiredCount, details },
});
}
export default async function errorMonitoringMutationsRoutes(app: FastifyInstance): Promise<void> {
const rl = { config: { rateLimit: app.rateLimits.mutation } };
app.post('/api/error-monitoring/resolve', rl, handleResolve);
app.post('/api/error-monitoring/bulk-resolve', rl, handleBulkResolve);
app.post('/api/error-monitoring/resolve-by-pattern', rl, handleResolveByPattern);
app.post('/api/error-monitoring/resolve-fixed-patterns', rl, handleResolveFixedPatterns);
app.post('/api/error-monitoring/purge-resolved', rl, handlePurgeResolved);
}
@@ -84,4 +84,91 @@ describe('GET /api/error-monitoring/recent-errors', () => {
const body = res.json() as { data: Array<{ gitea_repo?: string }> };
expect(body.data[0].gitea_repo).toBeUndefined();
});
it('includes top-level paperclip_project_id when stored in context_json', async () => {
const execute = vi.fn().mockResolvedValue([
[
{
incident_id: '2',
occurrence_id: '100',
project_slug: 'crm',
incident_severity: 'high',
incident_state: 'open',
message: 'probe',
stack_trace: '',
context_json: JSON.stringify({
paperclip_project_id: 'dba3fc26-c728-4e51-a23c-083881a2f534',
}),
environment: 'production',
occurred_at: '2026-01-01T00:00:00.000Z',
} as RowDataPacket,
],
]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors?api_key=test-recent-errors-key',
});
expect(res.statusCode).toBe(200);
const body = res.json() as { data: Array<{ paperclip_project_id?: string }> };
expect(body.data[0].paperclip_project_id).toBe('dba3fc26-c728-4e51-a23c-083881a2f534');
});
it('omits paperclip_project_id when not present in context', async () => {
const execute = vi.fn().mockResolvedValue([
[
{
incident_id: '3',
occurrence_id: '101',
project_slug: 'wdmi-store',
incident_severity: 'low',
incident_state: 'open',
message: 'y',
stack_trace: '',
context_json: JSON.stringify({ project_slug: 'wdmi-store' }),
environment: 'production',
occurred_at: '2026-01-01T00:00:00.000Z',
} as RowDataPacket,
],
]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors?api_key=test-recent-errors-key',
});
expect(res.statusCode).toBe(200);
const body = res.json() as { data: Array<{ paperclip_project_id?: string }> };
expect(body.data[0].paperclip_project_id).toBeUndefined();
});
it('paginates by incident (er_incidents) first when no q is given, incl. status=resolved (BIT-29730)', async () => {
const execute = vi.fn().mockResolvedValue([[]]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors?status=resolved&limit=50&api_key=test-recent-errors-key',
});
expect(res.statusCode).toBe(200);
expect(execute).toHaveBeenCalledTimes(1);
const [sql, params] = execute.mock.calls[0] as [string, unknown[]];
expect(sql).toContain('selected_incidents');
expect(sql).not.toContain('o.message LIKE');
// ['resolved', limit, offset]
expect(params).toEqual(['resolved', 50, 0]);
});
it('falls back to the occurrence-first scan when q is given', async () => {
const execute = vi.fn().mockResolvedValue([[]]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors?status=resolved&q=boom&limit=10&api_key=test-recent-errors-key',
});
expect(res.statusCode).toBe(200);
const [sql, params] = execute.mock.calls[0] as [string, unknown[]];
expect(sql).not.toContain('selected_incidents');
expect(sql).toContain('o.message LIKE');
// ['resolved', '%boom%', '%boom%', '%boom%', limit, offset]
expect(params).toEqual(['resolved', '%boom%', '%boom%', '%boom%', 10, 0]);
});
});
+80 -15
View File
@@ -74,6 +74,15 @@ function extractGiteaRepo(ctx: Record<string, unknown> | null): string {
return typeof raw === 'string' ? raw.trim() : '';
}
/** Paperclip error loop reads top-level `paperclip_project_id` to route issues to the correct project. */
function extractPaperclipProjectId(ctx: Record<string, unknown> | null): string {
if (!ctx) {
return '';
}
const raw = ctx.paperclip_project_id ?? ctx.paperclipProjectId;
return typeof raw === 'string' ? raw.trim() : '';
}
function parseStatusList(raw: string | undefined): string[] | null {
if (raw == null || raw.trim() === '') {
return ['open', 'investigating'];
@@ -149,28 +158,80 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
orderRaw === 'occurred_at_asc' ? 'r.occurred_at ASC, r.id ASC' : 'r.occurred_at DESC, r.id DESC';
const statePlaceholders = states.map(() => '?').join(', ');
const conditions: string[] = [`i.current_state IN (${statePlaceholders})`];
const params: Array<string | number> = [...states];
const incidentConditions: string[] = [`i.current_state IN (${statePlaceholders})`];
const incidentParams: Array<string | number> = [...states];
if (q.severity != null && q.severity !== '') {
conditions.push('i.severity = ?');
params.push(q.severity.trim().toLowerCase());
incidentConditions.push('i.severity = ?');
incidentParams.push(q.severity.trim().toLowerCase());
}
if (q.project_slug != null && q.project_slug.trim() !== '') {
conditions.push('p.slug = ?');
params.push(q.project_slug.trim().toLowerCase());
incidentConditions.push('p.slug = ?');
incidentParams.push(q.project_slug.trim().toLowerCase());
}
if (q.q != null && q.q.trim() !== '') {
const term = `%${q.q.trim()}%`;
conditions.push('(i.title LIKE ? OR o.message LIKE ? OR i.fingerprint LIKE ?)');
params.push(term, term, term);
}
const incidentWhereClause = incidentConditions.join(' AND ');
const hasSearch = q.q != null && q.q.trim() !== '';
const whereClause = conditions.join(' AND ');
let sql: string;
let params: Array<string | number>;
const sql = `
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).
const incidentOrderDir = orderRaw === 'occurred_at_asc' ? 'ASC' : 'DESC';
sql = `
WITH selected_incidents AS (
SELECT i.id AS incident_id
FROM er_incidents i
INNER JOIN er_projects p ON p.id = i.project_id
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,
p.slug AS project_slug,
i.severity AS incident_severity,
i.current_state AS incident_state,
r.message,
r.stack_trace,
r.context_json,
r.environment,
r.occurred_at
FROM ranked r
INNER JOIN er_incidents i ON i.id = r.incident_id
INNER JOIN er_projects p ON p.id = i.project_id
WHERE r.rn = 1
ORDER BY ${orderSql}
`;
params = [...incidentParams, limit, offset];
} else {
// Search path: `q` matches against occurrence message too, so an incident's
// latest occurrence isn't necessarily the one that matched. Keep the
// original occurrence-first scan for correctness; status=resolved + q can
// still be slow (not the case reported in BIT-29730, tracked separately).
const term = `%${q.q!.trim()}%`;
const conditions = [...incidentConditions, '(i.title LIKE ? OR o.message LIKE ? OR i.fingerprint LIKE ?)'];
const whereClause = conditions.join(' AND ');
sql = `
WITH ranked AS (
SELECT o.id,
o.incident_id,
@@ -202,8 +263,8 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
ORDER BY ${orderSql}
LIMIT ? OFFSET ?
`;
params.push(limit, offset);
params = [...incidentParams, term, term, term, limit, offset];
}
const [rows] = await db.execute<RowDataPacket[]>(sql, params);
@@ -211,6 +272,7 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
const ctx = parseJsonObject(row.context_json != null ? String(row.context_json) : null);
const { file_path, line_number } = extractFileLine(ctx);
const gitea_repo = extractGiteaRepo(ctx);
const paperclip_project_id = extractPaperclipProjectId(ctx);
const incSev = String(row.incident_severity ?? 'medium').toLowerCase();
const sev = ['critical', 'high', 'medium', 'low'].includes(incSev) ? incSev : 'medium';
const st = String(row.incident_state ?? 'open').toLowerCase();
@@ -238,6 +300,9 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
if (gitea_repo !== '') {
rowOut.gitea_repo = gitea_repo;
}
if (paperclip_project_id !== '') {
rowOut.paperclip_project_id = paperclip_project_id;
}
return rowOut;
});
@@ -0,0 +1,5 @@
BEGIN;
DROP INDEX IF EXISTS er_incidents_state_seen_idx ON er_incidents;
COMMIT;
@@ -0,0 +1,11 @@
BEGIN;
-- BIT-29730: GET /api/error-monitoring/recent-errors timed out for status=resolved.
-- er_incidents_project_state_seen_idx (project_id, current_state, last_seen_at DESC)
-- only helps when project_slug is also filtered. recent-errors now filters/paginates
-- er_incidents by current_state alone (no project_id) before touching occurrences,
-- so add a state-only index to support that lookup.
CREATE INDEX IF NOT EXISTS er_incidents_state_seen_idx
ON er_incidents (current_state, last_seen_at DESC);
COMMIT;
+1
View File
@@ -58,6 +58,7 @@ _run_sql "${_MIG_ER}/20260322045000_create_collectors_retention_and_audit.up.sql
_run_sql "${_MIG_ER}/20260402103000_add_occurred_at_for_stats.up.sql"
_run_sql "${_MIG_ER}/20260402140000_ingest_key_rate_limits.up.sql"
_run_sql "${_MIG_ER}/20260608150000_retire_wdmi_projects.up.sql"
_run_sql "${_MIG_ER}/20260824120000_add_incidents_state_seen_idx.up.sql"
_run_sql "${_MIG_ADMIN}/001_admin_users.sql"
_run_sql "${_MIG_ADMIN}/002_admin_refresh_tokens.sql"
_run_sql "${_MIG_ADMIN}/003_audit_logs.sql"
+22
View File
@@ -44,6 +44,28 @@ if [[ "${ER_WEBHOOK_RESTART_SERVICES:-1}" == "1" ]]; then
systemctl restart bitreport-error-reporting-admin-ui.service
systemctl restart bitreport-error-reporting-collector-worker.service
systemctl restart bitreport-error-reporting-api.service
# Auto-apply resolve-fixed-patterns after every deploy so code fixes clear stale incidents.
if [[ -n "${ERROR_RESOLVE_API_KEY:-}" ]]; then
_api_port="${ER_API_PORT:-3200}"
_ready=0
for _i in $(seq 1 20); do
if curl -sf "http://localhost:${_api_port}/health" >/dev/null 2>&1; then
_ready=1; break
fi
sleep 3
done
if [[ "${_ready}" == "1" ]]; then
curl -sf -X POST "http://localhost:${_api_port}/api/error-monitoring/resolve-fixed-patterns" \
-H "Content-Type: application/json" \
-d "{\"api_key\":\"${ERROR_RESOLVE_API_KEY}\"}" \
>/dev/null 2>&1 \
&& echo "webhook-deploy: resolve-fixed-patterns applied" \
|| echo "webhook-deploy: WARN resolve-fixed-patterns failed (non-fatal)"
else
echo "webhook-deploy: WARN API not ready after 60s, skipping resolve-fixed-patterns"
fi
fi
fi
echo "webhook-deploy: done"
+2 -2
View File
@@ -72,7 +72,7 @@ Automation or Grafana can **poll** that endpoint on an interval (with read key)
|--------|--------|---------|
| `er_ingest_request_duration_seconds` | `status_code` | End-to-end POST latency (SLO: watch p95/p99) |
| `er_ingest_requests_total` | `status_code` | Request volume by outcome class |
| `er_ingest_events_total` | `outcome` | `stored`, `skipped_noise`, `error` |
| `er_ingest_events_total` | `outcome`, `rule_id` | `stored` / `error` use empty `rule_id`; `skipped_noise` sets noise policy id (e.g. `resize_observer_loop`) |
| `er_ingest_batch_size` | — | Histogram of events per request |
| `er_ingest_active_connections` | — | In-flight requests (gauge) |
@@ -84,7 +84,7 @@ Plus `er_ingest_*` process defaults from `prom-client`.
1. **Ingest availability:** `sum(rate(er_ingest_requests_total[5m])) by (status_code)`.
2. **Ingest latency:** histogram quantiles on `er_ingest_request_duration_seconds` (e.g. `histogram_quantile(0.95, …)`).
3. **Noise vs stored:** `rate(er_ingest_events_total{outcome="stored"}[5m])` vs `skipped_noise`.
3. **Noise vs stored:** `rate(er_ingest_events_total{outcome="stored"}[5m])` vs `skipped_noise`. Per-rule noise: `sum(rate(er_ingest_events_total{outcome="skipped_noise"}[5m])) by (rule_id)`.
4. **Open incidents:** `er_incidents_total` by `state` (after stats refresh).
5. **Hub HTTP errors:** `sum(rate(er_api_http_requests_total{status_code=~"5.."}[5m]))`.
+1 -1
View File
@@ -121,7 +121,7 @@ When **`Idempotency-Key`** is reused with a **different** JSON body, the API ret
## 7. Noise rules — events “disappear”
If the response shows `results[]` entries with `"skipped": true`, the event matched a **noise rule** (`rule_id`, `reason`). This is expected for filtered traffic. Check `noise_filtered_count` and compare with `er_ingest_events_total{outcome="skipped_noise"}` in Prometheus.
If the response shows `results[]` entries with `"skipped": true`, the event matched a **noise rule** (`rule_id`, `reason`). This is expected for filtered traffic. Check `noise_filtered_count` and compare with `er_ingest_events_total{outcome="skipped_noise"}` in Prometheus (series also carry `rule_id`).
---
+3
View File
@@ -203,6 +203,9 @@ scrape_configs:
# Ingest throughput (events/sec)
sum(rate(er_ingest_events_total[5m])) by (outcome)
# Noise skips by rule (BIT-26791)
sum(rate(er_ingest_events_total{outcome="skipped_noise"}[5m])) by (rule_id)
# Ingest request rate by status
sum(rate(er_ingest_requests_total[5m])) by (status_code)
@@ -9,10 +9,20 @@ Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste
- Docker Engine 24+ e Docker Compose v2 (plugin `docker compose`), ou Podman Compose compatível.
- Portas livres no host (por omissão): **3306** → MariaDB, **3041** → ingest API, **3040** → admin UI. Ajustáveis em `.env` (`ER_PUBLISH_*`).
## Preservação de `.env` em runtime (BIT-25005)
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
- **Nunca** executar `cp .env.example .env` sobre um `.env` **já existente** em produção ou staging.
- O `cp` abaixo aplica-se **apenas** à configuração inicial num servidor novo onde não existe ainda `.env`.
- Em redeploys: `git pull` apenas; o `.env` existente **não é tocado**.
- Alterações a `ER_MYSQL_*` requerem issue explícita, plano de rollback e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo).
## Arranque reproduzível (qualquer ambiente)
```bash
cd /path/to/errors.bitreport.pt # raiz do clone (ver inventário em docs/ENVIRONMENTS.md)
# APENAS para configuração inicial — NÃO executar se já existir .env em produção (BIT-25005)
cp .env.example .env
# Editar .env: definir palavras-passe fortes antes de produção
docker compose up --build -d
@@ -2,6 +2,15 @@
Deploy nativo da stack na **raiz do repositório `errors.bitreport.pt`** num contentor **LXC** (Debian 12 ou Ubuntu 24.04 LTS, alinhado com o resto da infra BitReport): **MariaDB 10.11+** (ou MySQL 8+), **Node.js 20+**, **systemd** para **ingest-api**, **admin-ui**, **collector-worker**, env em **`/etc/error-reporting/env`**, proxy TLS opcional com **nginx**.
## Preservação de `.env` em runtime (BIT-25005)
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
- **Nunca** sobrescrever `/etc/error-reporting/env` (ou `.env` no clone) com conteúdo de exemplo num servidor de produção já configurado.
- Ficheiro de env em `/etc/error-reporting/env` é **fora do Git** — nunca incluir no repositório.
- Alterações a `ER_MYSQL_*` requerem issue explícita, plano de rollback e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo).
- Credenciais de placeholder (`CHANGE_ME_STRONG`, `changeme`) são proibidas em produção.
Comparação com Compose: variáveis e ordem de migrações espelham [`bitreport-error-reporting-compose-proxmox.md`](./bitreport-error-reporting-compose-proxmox.md) e [`docker-compose.yml`](../docker-compose.yml).
## Redis
+15 -7
View File
@@ -239,16 +239,20 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
idempotencyKey: _idempotencyKey,
bodyHash: _bodyHash,
});
// Track event outcomes
// Track event outcomes (rule_id on skipped_noise for BIT-26791)
if (_out.body && typeof _out.body === "object" && "results" in _out.body) {
const results = (_out.body as { results: Array<{ skipped?: boolean }> }).results;
const results = (
_out.body as { results: Array<{ skipped?: boolean; rule_id?: string }> }
).results;
let stored = 0;
let skipped = 0;
let _maxOccurredSec = 0;
const skippedByRule = new Map<string, number>();
for (let _i = 0; _i < results.length; _i++) {
const r = results[_i]!;
if (r.skipped) {
skipped++;
const _ruleId =
typeof r.rule_id === "string" && r.rule_id !== "" ? r.rule_id : "unknown";
skippedByRule.set(_ruleId, (skippedByRule.get(_ruleId) ?? 0) + 1);
continue;
}
stored++;
@@ -262,8 +266,12 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
}
}
}
if (stored > 0) ingestEventsTotal.inc({ outcome: "stored" }, stored);
if (skipped > 0) ingestEventsTotal.inc({ outcome: "skipped_noise" }, skipped);
if (stored > 0) {
ingestEventsTotal.inc({ outcome: "stored", rule_id: "" }, stored);
}
for (const [_ruleId, _n] of skippedByRule) {
ingestEventsTotal.inc({ outcome: "skipped_noise", rule_id: _ruleId }, _n);
}
const _slug = request.ingestAuth.projectSlug;
if (_slug !== "" && _maxOccurredSec > 0) {
errorHubLastEventTimestamp.set({ project_slug: _slug }, _maxOccurredSec);
@@ -284,7 +292,7 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
message: "occurred_at must be a valid ISO-8601 timestamp.",
});
}
ingestEventsTotal.inc({ outcome: "error" }, _body.events.length);
ingestEventsTotal.inc({ outcome: "error", rule_id: "" }, _body.events.length);
const _slugErr = request.ingestAuth?.projectSlug ?? "";
if (_slugErr !== "") {
errorHubIngestFailuresTotal.inc({ project_slug: _slugErr }, _body.events.length);
@@ -242,6 +242,11 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
expect(_body.noise_filtered_count).toBe(1);
expect(_body.results[0]?.skipped).toBe(true);
expect(_body.results[0]?.rule_id).toBe("resize_observer_loop");
const _metrics = await _app.inject({ method: "GET", url: "/metrics" });
expect(_metrics.statusCode).toBe(200);
expect(_metrics.body).toContain(
'er_ingest_events_total{outcome="skipped_noise",rule_id="resize_observer_loop"}',
);
const [after] = await _pool.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c FROM er_incidents WHERE project_id = ?`,
[_projectIdA],
+1 -13
View File
@@ -4,7 +4,7 @@ import { normalizeLevelToSeverity } from "./normalize.js";
* Versioned ruleset id (document in release notes when rules change).
* Rule inventory and validation steps: `docs/operations/ingest-hardening-runbook.md`.
*/
export const NOISE_RULESET_VERSION = "1.0.6";
export const NOISE_RULESET_VERSION = "1.0.7";
export type NoiseEvaluation =
| { matched: false }
@@ -104,18 +104,6 @@ const _RULES: NoiseRule[] = [
"Uncaught TypeError: Cannot read properties of undefined (reading 'after')",
),
},
{
id: "stale_bundle_switch_selection_tab",
reason: "filtered_stale_frontend_bundle_noise",
match: (i) =>
i.message.includes("Uncaught ReferenceError: switchSelectionEditorTab is not defined"),
},
{
id: "stale_bundle_description_editor_ready",
reason: "filtered_stale_frontend_bundle_noise",
match: (i) =>
i.message.includes("Uncaught ReferenceError: descriptionEditorReady is not defined"),
},
{
id: "transient_parser_promise",
reason: "filtered_transient_frontend_noise",
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { ingestEventsTotal, prometheusRegistry } from "./prometheus.js";
describe("er_ingest_events_total rule_id label (BIT-26791)", () => {
it("records skipped_noise with rule_id", async () => {
ingestEventsTotal.inc(
{ outcome: "skipped_noise", rule_id: "resize_observer_loop" },
1,
);
const _text = await prometheusRegistry.metrics();
expect(_text).toContain(
'er_ingest_events_total{outcome="skipped_noise",rule_id="resize_observer_loop"}',
);
});
});
+2 -1
View File
@@ -34,7 +34,8 @@ export const ingestDuration = new Histogram({
export const ingestEventsTotal = new Counter({
name: "er_ingest_events_total",
help: "Total events ingested",
labelNames: ["outcome"] as const, // stored, skipped_noise, error
// rule_id is set for skipped_noise (noise policy id); empty for stored/error
labelNames: ["outcome", "rule_id"] as const,
registers: [register],
});
+4
View File
@@ -22,6 +22,10 @@ _run_sql_file "/migrations/error_reporting/20260322043000_create_error_reporting
_run_sql_file "/migrations/error_reporting/20260322044000_create_error_occurrences_and_states.up.sql"
_run_sql_file "/migrations/error_reporting/20260322044500_add_ingest_idempotency.up.sql"
_run_sql_file "/migrations/error_reporting/20260322045000_create_collectors_retention_and_audit.up.sql"
_run_sql_file "/migrations/error_reporting/20260402103000_add_occurred_at_for_stats.up.sql"
_run_sql_file "/migrations/error_reporting/20260402140000_ingest_key_rate_limits.up.sql"
_run_sql_file "/migrations/error_reporting/20260608150000_retire_wdmi_projects.up.sql"
_run_sql_file "/migrations/error_reporting/20260824120000_add_incidents_state_seen_idx.up.sql"
_run_sql_file "/migrations/admin/001_admin_users.sql"
_run_sql_file "/migrations/admin/002_admin_refresh_tokens.sql"
_run_sql_file "/migrations/admin/003_audit_logs.sql"
+4
View File
@@ -40,6 +40,10 @@ _run "${_ROOT}/database/error_reporting/migrations/20260322043000_create_error_r
_run "${_ROOT}/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260402103000_add_occurred_at_for_stats.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260608150000_retire_wdmi_projects.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.up.sql"
_run "${_ROOT}/db/migrations/001_admin_users.sql"
_run "${_ROOT}/db/migrations/002_admin_refresh_tokens.sql"
_run "${_ROOT}/db/migrations/003_audit_logs.sql"
@@ -0,0 +1,439 @@
#!/usr/bin/env python3
"""
Fleet audit — error reporting por slug (semanal).
Verifica se todos os slugs esperados estão a reportar eventos frescos para
errors.bitreport.pt. Para cada slug silencioso ou stale, cria uma issue de
correção no Paperclip.
Env vars lidos (ver /etc/paperclip/paperclip-fleet-error-audit.env):
PAPERCLIP_ERROR_API_KEY — chave leitura do hub
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_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
PAPERCLIP_FLEET_AUDIT_ASSIGNEE_ID — Paperclip agent ID para assignar issues
PAPERCLIP_FLEET_AUDIT_PARENT_ID — (opcional) parent issue ID para sub-issues
PAPERCLIP_FLEET_AUDIT_ANCHOR_ISSUE_ID — (opcional) issue onde postar resumo
PAPERCLIP_API_URL — Paperclip API base
PAPERCLIP_API_KEY — Paperclip auth token
PAPERCLIP_COMPANY_ID — Paperclip company ID
PAPERCLIP_RUN_ID — run ID para audit trail
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from urllib import request as urllib_request
from urllib.error import HTTPError, URLError
# ---------------------------------------------------------------------------
# Env helpers
# ---------------------------------------------------------------------------
def _load_env_file(path: str) -> None:
try:
lines = Path(path).read_text(encoding="utf-8").splitlines()
except OSError:
return
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
k, _, v = line.partition("=")
k = k.strip()
v = v.strip()
# strip inline comments
if "#" in v:
v = v[: v.index("#")].strip()
if k and k not in os.environ:
os.environ[k] = v
def _env(key: str, default: str = "") -> str:
return os.environ.get(key, default).strip()
def _env_int(key: str, default: int) -> int:
raw = _env(key)
if not raw:
return default
try:
return int(raw)
except ValueError:
return default
# ---------------------------------------------------------------------------
# HTTP helpers
# ---------------------------------------------------------------------------
def _get_json(url: str, headers: dict[str, str] | None = None) -> Any:
req = urllib_request.Request(url, headers=headers or {})
try:
with urllib_request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
except HTTPError as e:
body = e.read().decode(errors="replace")
raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e
except URLError as e:
raise RuntimeError(f"URL error {url}: {e.reason}") from e
def _post_json(url: str, payload: dict[str, Any], headers: dict[str, str] | None = None) -> Any:
data = json.dumps(payload).encode()
hdrs = {"Content-Type": "application/json", **(headers or {})}
req = urllib_request.Request(url, data=data, headers=hdrs, method="POST")
try:
with urllib_request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
except HTTPError as e:
body = e.read().decode(errors="replace")
raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e
except URLError as e:
raise RuntimeError(f"URL error {url}: {e.reason}") from e
def _patch_json(url: str, payload: dict[str, Any], headers: dict[str, str] | None = None) -> Any:
data = json.dumps(payload).encode()
hdrs = {"Content-Type": "application/json", **(headers or {})}
req = urllib_request.Request(url, data=data, headers=hdrs, method="PATCH")
try:
with urllib_request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
except HTTPError as e:
body = e.read().decode(errors="replace")
raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e
except URLError as e:
raise RuntimeError(f"URL error {url}: {e.reason}") from e
# ---------------------------------------------------------------------------
# Hub query
# ---------------------------------------------------------------------------
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}"
)
# Use curl to avoid Cloudflare bot challenges on urllib
result = subprocess.run(
["curl", "-sf", "--max-time", "30", url],
capture_output=True, text=True,
)
if result.returncode != 0:
raise RuntimeError(f"curl failed (exit {result.returncode}): {result.stderr[:200]}")
try:
data = json.loads(result.stdout)
except json.JSONDecodeError as e:
raise RuntimeError(f"Invalid JSON from hub: {e} — body: {result.stdout[:200]}") from e
if not data.get("success"):
raise RuntimeError(f"Hub returned success=false: {data}")
return data.get("data", [])
def analyse_rows(
rows: list[dict[str, Any]],
expected_slugs: list[str],
max_age_hours: int,
min_rows: int,
) -> dict[str, Any]:
now = datetime.now(timezone.utc)
# Aggregate per slug
by_slug: dict[str, list[datetime]] = defaultdict(list)
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
try:
dt = datetime.fromisoformat(str(occurred_at_raw).replace("Z", "+00:00"))
by_slug[slug].append(dt)
except ValueError:
pass
total_rows = len(rows)
enforcement_active = total_rows >= min_rows
results: list[dict[str, Any]] = []
for slug in expected_slugs:
times = by_slug.get(slug, [])
if not times:
status = "silent"
hours_since = None
latest = None
else:
latest = max(times)
hours_since = (now - latest).total_seconds() / 3600
status = "stale" if hours_since > max_age_hours else "ok"
results.append(
{
"slug": slug,
"status": status,
"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,
}
)
seen_slugs = sorted(by_slug.keys())
unexpected_slugs = [s for s in seen_slugs if s not in expected_slugs]
return {
"total_rows_fetched": total_rows,
"min_rows": min_rows,
"enforcement_active": enforcement_active,
"max_age_hours": max_age_hours,
"expected_slugs": expected_slugs,
"results": results,
"unexpected_slugs": unexpected_slugs,
"audited_at": now.isoformat(),
}
# ---------------------------------------------------------------------------
# Paperclip helpers
# ---------------------------------------------------------------------------
def paperclip_create_issue(
api_url: str,
api_key: str,
run_id: str,
company_id: str,
title: str,
description: str,
project_id: str,
assignee_id: str,
parent_id: str | None,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"title": title,
"description": description,
"status": "todo",
"priority": "high",
"projectId": project_id,
"assigneeAgentId": assignee_id,
}
if parent_id:
payload["parentId"] = parent_id
headers = {
"Authorization": f"Bearer {api_key}",
"X-Paperclip-Run-Id": run_id,
}
return _post_json(f"{api_url}/api/companies/{company_id}/issues", payload, headers)
def paperclip_post_comment(
api_url: str,
api_key: str,
run_id: str,
issue_id: str,
body: str,
) -> dict[str, Any]:
headers = {
"Authorization": f"Bearer {api_key}",
"X-Paperclip-Run-Id": run_id,
}
return _post_json(
f"{api_url}/api/issues/{issue_id}/comments",
{"body": body},
headers,
)
def paperclip_update_issue(
api_url: str,
api_key: str,
run_id: str,
issue_id: str,
payload: dict[str, Any],
) -> dict[str, Any]:
headers = {
"Authorization": f"Bearer {api_key}",
"X-Paperclip-Run-Id": run_id,
}
return _patch_json(f"{api_url}/api/issues/{issue_id}", payload, headers)
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main() -> int:
# Load env files (automation.env first so fleet-audit.env can override)
_load_env_file("/etc/paperclip/automation.env")
_load_env_file("/etc/paperclip/paperclip-fleet-error-audit.env")
hub_base = _env("PAPERCLIP_FLEET_AUDIT_HUB_BASE", "https://errors.bitreport.pt").rstrip("/")
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)
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")
assignee_id = _env("PAPERCLIP_FLEET_AUDIT_ASSIGNEE_ID")
parent_id = _env("PAPERCLIP_FLEET_AUDIT_PARENT_ID") or None
anchor_issue_id = _env("PAPERCLIP_FLEET_AUDIT_ANCHOR_ISSUE_ID") or None
api_url = _env("PAPERCLIP_API_URL", "http://127.0.0.1:3100")
api_key = _env("PAPERCLIP_API_KEY")
run_id = _env("PAPERCLIP_RUN_ID", "")
company_id = _env("PAPERCLIP_COMPANY_ID")
# Validation
if not hub_api_key:
print("ERROR: PAPERCLIP_ERROR_API_KEY is not set", file=sys.stderr)
return 1
expected_slugs = [s.strip().lower() for s in expected_slugs_raw.split(",") if s.strip()]
if not expected_slugs:
print("ERROR: PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS is empty", file=sys.stderr)
return 1
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}")
# Fetch hub data
try:
rows = fetch_hub_rows(hub_base, hub_api_key, fetch_limit)
except RuntimeError as e:
print(f"ERROR fetching hub rows: {e}", file=sys.stderr)
return 1
print(f"Fetched {len(rows)} rows from hub")
# Analyse
report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows)
print(json.dumps(report, indent=2, default=str))
# Determine problems
if not report["enforcement_active"]:
print(
f"\nEnforcement SKIPPED — only {report['total_rows_fetched']} rows "
f"(threshold: {min_rows}). Hub may be quiet; no correction issues created."
)
else:
problems = [r for r in report["results"] if r["status"] in ("silent", "stale")]
if problems:
print(f"\n{len(problems)} problem slug(s) found — creating correction issues")
else:
print("\nAll expected slugs are fresh — no correction issues needed")
problems = [r for r in report["results"] if r["status"] in ("silent", "stale")]
created_issues: list[dict[str, Any]] = []
if report["enforcement_active"] and problems and project_id and assignee_id and api_key and company_id:
for p in problems:
slug = p["slug"]
status = p["status"]
if status == "silent":
title = f"[fleet-audit] {slug} — sem eventos no hub (slug silencioso)"
desc = (
f"O slug `{slug}` não tem eventos registados em `{hub_base}`.\n\n"
f"Auditoria: {report['audited_at']}\n"
f"Total de rows no hub: {report['total_rows_fetched']}"
)
else:
hours = p["hours_since_last_event"]
latest = p["latest_occurred_at"]
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"Último evento: `{latest}`\n"
f"Hub: `{hub_base}`\n"
f"Auditoria: {report['audited_at']}"
)
try:
issue = paperclip_create_issue(
api_url, api_key, run_id, company_id,
title, desc, project_id, assignee_id, parent_id,
)
issue_id = issue.get("id", "")
identifier = issue.get("identifier", "")
created_issues.append({"slug": slug, "issue_id": issue_id, "identifier": identifier})
print(f" Created correction issue {identifier} for slug '{slug}'")
except RuntimeError as e:
print(f" ERROR creating issue for slug '{slug}': {e}", file=sys.stderr)
# Build summary comment
lines = ["## Fleet Audit — Error Reporting por Slug", ""]
lines.append(f"**Auditado em:** {report['audited_at']}")
lines.append(f"**Hub:** {hub_base}")
lines.append(f"**Rows fetched:** {report['total_rows_fetched']} (min para enforcement: {min_rows})")
lines.append("")
if not report["enforcement_active"]:
lines.append("> **Enforcement inativo** — hub com poucos eventos, possível dia tranquilo.")
lines.append("")
lines.append("### Slugs esperados")
lines.append("")
for r in report["results"]:
slug = r["slug"]
st = r["status"]
if st == "ok":
hours = r["hours_since_last_event"]
icon = "✅"
detail = f"fresco — último evento há {hours:.1f}h"
elif st == "stale":
hours = r["hours_since_last_event"]
icon = "⚠️"
detail = f"stale — último evento há {hours:.1f}h (limiar: {max_age_hours}h)"
else:
icon = "🔴"
detail = "silencioso — sem eventos"
lines.append(f"- {icon} **{slug}**: {detail}")
if report["unexpected_slugs"]:
lines.append("")
lines.append("### Slugs inesperados no hub (informação)")
for s in report["unexpected_slugs"]:
lines.append(f"- `{s}`")
if created_issues:
lines.append("")
lines.append("### Issues de correção criadas")
for ci in created_issues:
identifier = ci["identifier"]
issue_id = ci["issue_id"]
lines.append(f"- [{identifier}](/BIT/issues/{identifier}) — slug `{ci['slug']}`")
if not problems or not report["enforcement_active"]:
lines.append("")
lines.append("_Sem ações corretivas necessárias nesta execução._")
summary_comment = "\n".join(lines)
print("\n--- SUMMARY ---")
print(summary_comment)
# Post summary to anchor issue if configured
if anchor_issue_id and api_key:
try:
paperclip_post_comment(api_url, api_key, run_id, anchor_issue_id, summary_comment)
print(f"\nSummary posted to issue {anchor_issue_id}")
except RuntimeError as e:
print(f"WARNING: could not post summary comment: {e}", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())