fix(api): store each reported check result once

A checker that lost the answer to a report, for example when its request
was cancelled while the API was still working, sent the batch again and
the API stored it twice, skewing statistics and counting failures twice
towards an incident. Results are now claimed in Redis by instance,
monitor and schedule time, and repeats are dropped. Found by CI, where
TestCheckersPerRegion saw a stopped checker's batch arrive twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 12:46:32 +01:00
1 parent d24937e584
commit d4c8fd1d42
2 files changed
+90 -1

No files matched your search

+35
View File
@@ -207,3 +207,38 @@ func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) {
time.Sleep(100 * time.Millisecond)
}
}
// A checker that lost the answer to a report sends it again; the results
// must not be stored twice.
func TestResultReportIsIdempotent(t *testing.T) {
e := newEnv(t)
tok, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("id")+".test", uniq("id-"))
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
})
monitor := uuid.MustParse(m["id"].(string))
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
at := time.Now().Truncate(time.Millisecond)
batch := []agentapi.Result{
{MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true},
{MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false},
}
for range 3 {
if err := client.Report(context.Background(), batch); err != nil {
t.Fatal(err)
}
}
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 2 {
t.Errorf("stored results = %d, want 2", n)
}
// Another instance's run of the same schedule time is its own result.
other := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
if err := other.Report(context.Background(), batch[:1]); err != nil {
t.Fatal(err)
}
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 3 {
t.Errorf("stored results = %d, want 3", n)
}
}