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).
This commit is contained in:
1 parent
308ff624cf
commit
7987aa94ae
7 files changed
+123
-15
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]);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
|
||||
Reference in new issue
Block a user