From 7987aa94ae2eeab2bfce23a219a5dbd1a72d8d1d Mon Sep 17 00:00:00 2001 From: David Santos Date: Mon, 24 Aug 2026 08:32:26 +0100 Subject: [PATCH] fix(hub): BIT-29730 stop timeout on GET recent-errors?status=resolved 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). --- api/src/routes/public/recentErrors.test.ts | 31 +++++++ api/src/routes/public/recentErrors.ts | 82 +++++++++++++++---- ...0000_add_incidents_state_seen_idx.down.sql | 5 ++ ...120000_add_incidents_state_seen_idx.up.sql | 11 +++ deploy/lxc/run-migrate.sh | 1 + scripts/docker-migrate.sh | 4 + scripts/run-mysql-migrations.sh | 4 + 7 files changed, 123 insertions(+), 15 deletions(-) create mode 100644 database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.down.sql create mode 100644 database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.up.sql diff --git a/api/src/routes/public/recentErrors.test.ts b/api/src/routes/public/recentErrors.test.ts index 841c50a..53ceee6 100644 --- a/api/src/routes/public/recentErrors.test.ts +++ b/api/src/routes/public/recentErrors.test.ts @@ -140,4 +140,35 @@ describe('GET /api/error-monitoring/recent-errors', () => { 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]); + }); }); diff --git a/api/src/routes/public/recentErrors.ts b/api/src/routes/public/recentErrors.ts index dc082da..f727ee1 100644 --- a/api/src/routes/public/recentErrors.ts +++ b/api/src/routes/public/recentErrors.ts @@ -158,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 = [...states]; + const incidentConditions: string[] = [`i.current_state IN (${statePlaceholders})`]; + const incidentParams: Array = [...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; - 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, @@ -211,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(sql, params); diff --git a/database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.down.sql b/database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.down.sql new file mode 100644 index 0000000..de090cb --- /dev/null +++ b/database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.down.sql @@ -0,0 +1,5 @@ +BEGIN; + +DROP INDEX IF EXISTS er_incidents_state_seen_idx ON er_incidents; + +COMMIT; diff --git a/database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.up.sql b/database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.up.sql new file mode 100644 index 0000000..52c0da2 --- /dev/null +++ b/database/error_reporting/migrations/20260824120000_add_incidents_state_seen_idx.up.sql @@ -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; diff --git a/deploy/lxc/run-migrate.sh b/deploy/lxc/run-migrate.sh index aef0812..c979e45 100755 --- a/deploy/lxc/run-migrate.sh +++ b/deploy/lxc/run-migrate.sh @@ -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" diff --git a/scripts/docker-migrate.sh b/scripts/docker-migrate.sh index 30b517a..6621dce 100755 --- a/scripts/docker-migrate.sh +++ b/scripts/docker-migrate.sh @@ -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" diff --git a/scripts/run-mysql-migrations.sh b/scripts/run-mysql-migrations.sh index ed83b0c..12a99cc 100755 --- a/scripts/run-mysql-migrations.sh +++ b/scripts/run-mysql-migrations.sh @@ -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" -- 2.47.3