Files
Niklas Ye 1dcff1267c Estimate how long an open incident will probably last
An open incident now shows "usually ~30m more (up to 1h 30m)", worked out
from how long earlier incidents with the same team and signature took.
GET /api/incidents/{id}/estimate returns the 50th and 90th percentile of
the time still to go, among earlier occurrences that lasted longer than this
one has so far. With fewer than five comparable occurrences it returns no
figures, and when this incident has outlived all of them it says
longer_than_usual instead of inventing a number.

Incidents closed by hand are left out: they record when someone gave up on
the incident, not when the problem ended. Archived incidents are left out
too, as in the stats. It is history, not a forecast; nothing about the
alert's current value is known to it, and the UI labels it as an estimate.

Added /similar to docs/api.md as well, which was missing from the table.
The stats page keeps its own median: it is the upper median, and switching
it to interpolated would change figures people already read.
2026-11-01 17:12:19 +01:00

124 lines
3.7 KiB
Go

package api
import (
"database/sql"
"math"
"net/http"
"slices"
"time"
)
const (
// minEstimateSamples is how many earlier occurrences an estimate needs. Below
// it a percentile is an anecdote, so the endpoint reports no figures.
minEstimateSamples = 5
// estimateHistory caps how many earlier occurrences feed the estimate, newest
// first, so a very noisy alert does not make the query grow without bound.
estimateHistory = 500
)
// resolveEstimate is the answer to "how long will this probably stay open".
// P50Seconds and P90Seconds are the time still to go, not the total duration,
// and are nil when there is nothing honest to say.
type resolveEstimate struct {
SampleSize int `json:"sample_size"`
ElapsedSeconds int64 `json:"elapsed_seconds"`
P50Seconds *int64 `json:"p50_seconds"`
P90Seconds *int64 `json:"p90_seconds"`
LongerThanUsual bool `json:"longer_than_usual"`
}
// handleIncidentEstimate estimates the remaining time of an open incident from
// how long earlier incidents with the same signature in the same team took.
// It is history, not a forecast: nothing about the alert's current state is
// known, and incidents a person closed by hand are left out because they say
// when someone gave up on the incident, not when the problem ended.
func handleIncidentEstimate(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, ok := incidentIDParam(w, r, db)
if !ok {
return
}
var teamID, triggered int64
var signature string
var resolved *int64
if err := db.QueryRowContext(r.Context(),
`SELECT team_id, signature, triggered_at, resolved_at FROM incidents WHERE id = $1`,
id).Scan(&teamID, &signature, &triggered, &resolved); err != nil {
serverError(w, r, err)
return
}
if resolved != nil {
respond(w, http.StatusOK, resolveEstimate{})
return
}
rows, err := db.QueryContext(r.Context(), `
SELECT resolved_at - triggered_at
FROM incidents
WHERE team_id = $1 AND signature = $2 AND id <> $3
AND resolved_at IS NOT NULL AND archived_at IS NULL
AND resolution_source IN ($4, $5)
ORDER BY triggered_at DESC
LIMIT $6`, teamID, signature, id,
incidentResolutionAlerts, incidentResolutionRecovered, estimateHistory)
if err != nil {
serverError(w, r, err)
return
}
defer rows.Close()
var durations []int64
for rows.Next() {
var d int64
if err := rows.Scan(&d); err != nil {
serverError(w, r, err)
return
}
durations = append(durations, d)
}
if err := rows.Err(); err != nil {
serverError(w, r, err)
return
}
elapsed := max(time.Now().Unix()-triggered, 0)
out := resolveEstimate{SampleSize: len(durations), ElapsedSeconds: elapsed}
if len(durations) < minEstimateSamples {
respond(w, http.StatusOK, out)
return
}
// Only the occurrences that lasted longer than this one already has say
// anything about the time still to go.
var longer []int64
for _, d := range durations {
if d > elapsed {
longer = append(longer, d)
}
}
if len(longer) < minEstimateSamples {
out.LongerThanUsual = true
respond(w, http.StatusOK, out)
return
}
p50 := int64(math.Round(percentile(longer, 0.5))) - elapsed
p90 := int64(math.Round(percentile(longer, 0.9))) - elapsed
out.P50Seconds, out.P90Seconds = &p50, &p90
respond(w, http.StatusOK, out)
}
}
// percentile returns the p-th quantile (0..1) of xs by linear interpolation
// between closest ranks. xs must not be empty; it is not modified.
func percentile(xs []int64, p float64) float64 {
s := slices.Clone(xs)
slices.Sort(s)
pos := p * float64(len(s)-1)
lo := int(math.Floor(pos))
hi := int(math.Ceil(pos))
return float64(s[lo]) + (float64(s[hi])-float64(s[lo]))*(pos-float64(lo))
}