fix(hub): BIT-29730 stop timeout on GET recent-errors?status=resolved #12

Merged
spark merged 1 commits from fix/BIT-29730-recent-errors-resolved-timeout into master 2026-08-24 09:02:41 +01:00
7 changed files with 123 additions and 15 deletions

No files matched your search

@@ -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]);
});
});
+67 -15
View File
@@ -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<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,
@@ -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<RowDataPacket[]>(sql, params);
@@ -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"
+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"