diff --git a/docs/architecture/appendix-a-trace-and-metric-catalog.md b/docs/architecture/appendix-a-trace-and-metric-catalog.md index e3bbaba..17db380 100644 --- a/docs/architecture/appendix-a-trace-and-metric-catalog.md +++ b/docs/architecture/appendix-a-trace-and-metric-catalog.md @@ -134,9 +134,20 @@ The start is the earliest of all those times, so a non-agent commit that predate Only the first end of a PR counts. If a reopened PR ends again, the stored `ended` milestone blocks a second observation. -Every histogram is an exponential (native) histogram, with the SDK's default limit of 160 buckets. Over a range of 1 second to 30 days, 160 buckets give a scale of 2, which means each bucket spans a ratio of about 1.19 and a quantile estimate is off by about 9% at most. Goal thresholds of 600 s and 900 s sit inside a bucket, not on an edge, so a goal check has the same error. D15 records the choice, the fallback, and the backend check. Each attribute set exports one native histogram series, with the count and sum inside it, if Mimir ingests native histograms (unverified). +Completed CI jobs record queue and run durations for every conclusion: -The metric attributes are `vcs.repository.name`, and `github.author.type` with the values `user` or `bot`. The review counter adds `github.review.state`, and the cycle time histogram adds `vcs.change.state` and `github.pull_request.start_source`. +| Instrument | Unit | Start | End | Attributes | +| --- | --- | --- | --- | --- | +| `github.ci.job.queue_seconds` | `s` | Job `created_at` | Job `started_at` | `repository`, `workflow`, `job`, `conclusion`, `event_class` and `runner` | +| `github.ci.job.run_seconds` | `s` | Job `started_at` | Job `completed_at` | `repository`, `workflow`, `job`, `conclusion`, `event_class` and `runner` | + +The workflow and job names come from `workflow_name` and `name`. The runner comes from the first `labels` entry or `none` for an empty or missing array. Each attribute removes line breaks and keeps at most 64 characters. Both histograms use explicit boundaries of 5, 15, 30, 60, 120, 300, 600, 900, 1200, 1800, 2700, 3600, 5400 and 7200 seconds. A missing or invalid timestamp skips that duration. A negative duration also skips that observation. The ledger claims the decimal job ID followed by a zero byte and `ci_job` before recording. Jobs without an ID skip recording. A duplicate claim skips all metrics and logs for that delivery; a claim error leaves it for retry. + +The `event_class` attribute approximates the trigger because the payload has no triggering event. A `head_branch` with the prefix `gh-readonly-queue/` counts as `merge_group`. The repository's default branch counts as `push`; any other branch counts as `pull_request`. Scheduled and manual runs on the default branch count as `push`, and runs on a non-default branch from other triggers count as `pull_request`. + +Every PR histogram is an exponential (native) histogram, with the SDK's default limit of 160 buckets. Over a range of 1 second to 30 days, 160 buckets give a scale of 2, which means each bucket spans a ratio of about 1.19 and a quantile estimate is off by about 9% at most. Goal thresholds of 600 s and 900 s sit inside a bucket, not on an edge, so a goal check has the same error. D15 records the choice, the fallback, and the backend check. Each attribute set exports one native histogram series, with the count and sum inside it, if Mimir ingests native histograms (unverified). + +The PR metric attributes are `vcs.repository.name`, and `github.author.type` with the values `user` or `bot`. The review counter adds `github.review.state`, and the cycle time histogram adds `vcs.change.state` and `github.pull_request.start_source`. ### Direct metrics, not derived from traces diff --git a/internal/recorder/recorder.go b/internal/recorder/recorder.go index e80f05e..9fcfade 100644 --- a/internal/recorder/recorder.go +++ b/internal/recorder/recorder.go @@ -11,6 +11,7 @@ import ( "fmt" "log/slog" "regexp" + "strconv" "strings" "time" @@ -76,7 +77,7 @@ type ClosedPR struct { type Recorder struct { events, merges, conclusions, dropped metric.Int64Counter ciJobFailures metric.Int64Counter - cycleTime metric.Float64Histogram + cycleTime, ciJobQueue, ciJobRun metric.Float64Histogram mainRed metric.Int64Gauge ledger Ledger log *slog.Logger @@ -92,17 +93,20 @@ type checkRun struct { } type workflowJob struct { - WorkflowName string `json:"workflow_name"` //nolint:tagliatelle // GitHub uses this field name. - Name string `json:"name"` - Conclusion string `json:"conclusion"` - HeadBranch string `json:"head_branch"` //nolint:tagliatelle // GitHub uses this field name. - HeadSHA string `json:"head_sha"` //nolint:tagliatelle // GitHub uses this field name. - StartedAt string `json:"started_at"` //nolint:tagliatelle // GitHub uses this field name. - CompletedAt string `json:"completed_at"` //nolint:tagliatelle // GitHub uses this field name. + CreatedAt string `json:"created_at"` //nolint:tagliatelle // GitHub uses this field name. + Labels []string `json:"labels"` + WorkflowName string `json:"workflow_name"` //nolint:tagliatelle // GitHub uses this field name. + Name string `json:"name"` + Conclusion string `json:"conclusion"` + HeadBranch string `json:"head_branch"` //nolint:tagliatelle // GitHub uses this field name. + HeadSHA string `json:"head_sha"` //nolint:tagliatelle // GitHub uses this field name. + StartedAt string `json:"started_at"` //nolint:tagliatelle // GitHub uses this field name. + CompletedAt string `json:"completed_at"` //nolint:tagliatelle // GitHub uses this field name. Steps []struct { Name string `json:"name"` Conclusion string `json:"conclusion"` } `json:"steps"` + ID int64 `json:"id"` RunID int64 `json:"run_id"` //nolint:tagliatelle // GitHub uses this field name. } @@ -118,7 +122,7 @@ type pullRequest struct { // New creates the instruments used to record deliveries. The ledger claims // each milestone before it counts. // -//nolint:mnd // The histogram has fixed cycle time buckets in seconds. +//nolint:mnd // The histograms have fixed duration buckets in seconds. func New(meter metric.Meter, ledger Ledger, log *slog.Logger) (*Recorder, error) { if ledger == nil { return nil, ErrNoLedger @@ -162,6 +166,22 @@ func New(meter metric.Meter, ledger Ledger, log *slog.Logger) (*Recorder, error) return nil, fmt.Errorf("create github.pr.cycle_time histogram: %w", err) } + for _, histogram := range []struct { + target *metric.Float64Histogram + name string + }{ + {&recorder.ciJobQueue, "github.ci.job.queue_seconds"}, + {&recorder.ciJobRun, "github.ci.job.run_seconds"}, + } { + instrument, histErr := meter.Float64Histogram(histogram.name, metric.WithUnit("s"), + metric.WithExplicitBucketBoundaries(5, 15, 30, 60, 120, 300, 600, 900, 1200, 1800, 2700, 3600, 5400, 7200)) + if histErr != nil { + return nil, fmt.Errorf("create %s histogram: %w", histogram.name, histErr) + } + + *histogram.target = instrument + } + recorder.mainRed, err = meter.Int64Gauge("github.main.red") if err != nil { return nil, fmt.Errorf("create github.main.red gauge: %w", err) @@ -215,19 +235,20 @@ func (r *Recorder) Record(ctx context.Context, event string, body []byte) error } } - repo := attribute.String("repository", repository) - r.merges.Add(ctx, 0, metric.WithAttributes(repo)) + if event == "workflow_job" && delivery.Action == actionCompleted { + return r.recordJob(ctx, repository, delivery.Repository.DefaultBranch, delivery.WorkflowJob) + } - eventAttrs := metric.WithAttributes(repo, - attribute.String("event", event), attribute.String("action", delivery.Action)) - r.events.Add(ctx, 0, eventAttrs) - r.events.Add(ctx, 1, eventAttrs) + r.recordEvent(ctx, repository, event, delivery.Action) - switch { - case event == "check_run": - r.recordCheckRun(ctx, repo, delivery.Action, delivery.Repository.DefaultBranch, delivery.CheckRun) - case event == "workflow_job" && delivery.Action == actionCompleted: - r.recordFailedJob(ctx, repository, delivery.WorkflowJob) + if event == "check_run" { + r.recordCheckRun( + ctx, + attribute.String("repository", repository), + delivery.Action, + delivery.Repository.DefaultBranch, + delivery.CheckRun, + ) } return nil @@ -272,6 +293,16 @@ func (r *Recorder) RecordClosed(ctx context.Context, closed ClosedPR) (Outcome, return out, err } +func (r *Recorder) recordEvent(ctx context.Context, repository, event, action string) { + repo := attribute.String("repository", repository) + r.merges.Add(ctx, 0, metric.WithAttributes(repo)) + + eventAttrs := metric.WithAttributes(repo, + attribute.String("event", event), attribute.String("action", action)) + r.events.Add(ctx, 0, eventAttrs) + r.events.Add(ctx, 1, eventAttrs) +} + // recordPullRequest handles a closed or reopened delivery. For a PR created // at or before the repair floor, a reopen claims ended to guard against // counting a first close the old recorder may already have counted. @@ -334,14 +365,98 @@ func (r *Recorder) recordCheckRun( r.mainRed.Record(ctx, red, metric.WithAttributes(repo)) } -func (r *Recorder) recordFailedJob(ctx context.Context, repository string, body json.RawMessage) { +func (r *Recorder) recordJob( + ctx context.Context, + repository, defaultBranch string, + body json.RawMessage, +) error { var job workflowJob err := json.Unmarshal(body, &job) - if err != nil || job.Conclusion != failure { - return + if err != nil || job.ID == 0 { + return nil //nolint:nilerr // Invalid job data may leave the queue. + } + + claimed, err := r.ledger.ClaimMilestone(strconv.FormatInt(job.ID, 10) + "\x00ci_job") + if err != nil { + return fmt.Errorf("claim ci job milestone: %w", err) + } + + if !claimed { + return nil + } + + r.recordJobTiming(ctx, repository, defaultBranch, job) + + if job.Conclusion == failure { + r.recordFailedJob(ctx, repository, job) } + r.recordEvent(ctx, repository, "workflow_job", actionCompleted) + + return nil +} + +func (r *Recorder) recordJobTiming(ctx context.Context, repository, defaultBranch string, job workflowJob) { + eventClass, runner := jobEventClass(job.HeadBranch, defaultBranch), "none" + if len(job.Labels) > 0 { + runner = job.Labels[0] + } + + values := []struct{ key, value string }{ + {"repository", repository}, + {"workflow", job.WorkflowName}, + {"job", job.Name}, + {"conclusion", job.Conclusion}, + {"event_class", eventClass}, + {"runner", runner}, + } + attrs := make([]attribute.KeyValue, 0, len(values)) + fields := []any{} + + for _, field := range values { + attrs = append(attrs, attribute.String(field.key, cleanText(field.value, metricNameLimit))) + fields = append(fields, field.key, cleanText(field.value, logTextLimit)) + } + + fields = append(fields, + "head_branch", cleanText(job.HeadBranch, logTextLimit), + "head_sha", cleanText(job.HeadSHA, logTextLimit), "run_id", job.RunID, "job_id", job.ID) + + for _, duration := range []struct { + histogram metric.Float64Histogram + name, start, end string + }{ + {r.ciJobQueue, "queue_seconds", job.CreatedAt, job.StartedAt}, + {r.ciJobRun, "run_seconds", job.StartedAt, job.CompletedAt}, + } { + start, end := parseTime(duration.start), parseTime(duration.end) + if start.IsZero() || end.IsZero() || end.Before(start) { + continue + } + + seconds := end.Sub(start).Seconds() + duration.histogram.Record(ctx, seconds, metric.WithAttributes(attrs...)) + fields = append(fields, duration.name, seconds) + } + + r.log.InfoContext(ctx, "ci job finished", fields...) +} + +// jobEventClass approximates the trigger: scheduled and manual runs on the default +// branch count as push, and other triggers on non-default branches count as pull_request. +func jobEventClass(branch, defaultBranch string) string { + switch { + case strings.HasPrefix(branch, "gh-readonly-queue/"): + return "merge_group" + case branch == defaultBranch: + return "push" + default: + return "pull_request" + } +} + +func (r *Recorder) recordFailedJob(ctx context.Context, repository string, job workflowJob) { var failedSteps []string for _, step := range job.Steps { diff --git a/internal/recorder/recorder_test.go b/internal/recorder/recorder_test.go index 5357c1b..a4c8124 100644 --- a/internal/recorder/recorder_test.go +++ b/internal/recorder/recorder_test.go @@ -86,9 +86,9 @@ func recordCycleFixture(t *testing.T, test cycleTimeTest) (*sdkmetric.ManualRead } body, err := json.Marshal(map[string]any{ - "repository": map[string]string{"full_name": repositoryName}, - "action": test.action, - "pull_request": map[string]any{ + repositoryKey: map[string]string{fullNameKey: repositoryName}, + "action": test.action, + pullRequestEvent: map[string]any{ "node_id": nodeID, "merged": test.merged, "created_at": test.createdAt, "merged_at": test.end, "closed_at": test.end, "body": test.body, }, @@ -245,6 +245,8 @@ const ( eventKey = "event" eventsName = "github.events" repositoryKey = "repository" + fullNameKey = "full_name" + mainBranch = "main" unknownRepository = "unknown" buildName = "build" conclusionKey = "conclusion" @@ -484,8 +486,6 @@ type mainRedStep struct { func TestRecordMainRed(t *testing.T) { t.Parallel() - const mainBranch = "main" - for _, test := range []struct { name string steps []mainRedStep @@ -525,8 +525,8 @@ func TestRecordMainRed(t *testing.T) { for _, step := range test.steps { body, err := json.Marshal(map[string]any{ - "repository": map[string]string{ - "full_name": repositoryName, + repositoryKey: map[string]string{ + fullNameKey: repositoryName, "default_branch": step.defaultBranch, }, "action": step.action, diff --git a/internal/recorder/workflow_job_test.go b/internal/recorder/workflow_job_test.go index 9d55546..ed1ee40 100644 --- a/internal/recorder/workflow_job_test.go +++ b/internal/recorder/workflow_job_test.go @@ -6,10 +6,15 @@ package recorder_test import ( "bytes" "encoding/json" + "errors" "log/slog" "reflect" "strings" "testing" + + "go.opentelemetry.io/otel/sdk/metric/metricdata" + + sdkmetric "go.opentelemetry.io/otel/sdk/metric" ) const ( @@ -21,13 +26,30 @@ const ( jobKey = "job" completedAtKey = "completed_at" headSHAKey = "head_sha" + queueMetric = "github.ci.job.queue_seconds" + runMetric = "github.ci.job.run_seconds" + finishedMessage = "ci job finished" + eventClassKey = "event_class" + runnerKey = "runner" + queueSecondsKey = "queue_seconds" + runSecondsKey = "run_seconds" + createdAtKey = "created_at" + pushEvent = "push" + noRunner = "none" + jobIDKey = "job_id" + runIDKey = "run_id" + jobSHA = "123abc" + queueStart = "11:59:45" + jobStart = "12:00:00" + jobEnd = "12:01:00" ) func TestRecordFailedWorkflowJob(t *testing.T) { t.Parallel() const body = `{"action":"completed","repository":{"full_name":"tbhb-dev/github-metrics"},"workflow_job":{ - "workflow_name":"CI","name":"build","head_branch":"main","head_sha":"123abc","run_id":493, + "id":42,"created_at":"2026-11-15T11:59:45Z","workflow_name":"CI","name":"build", + "head_branch":"main","head_sha":"123abc","run_id":493, "started_at":"2026-11-15T12:00:00Z","completed_at":"2026-11-15T12:01:00Z","conclusion":"failure", "html_url":"omit job URL","steps":[{"name":"checkout","conclusion":"success"}, {"name":"compile","conclusion":"failure"},{"name":"test","conclusion":"failure"}, @@ -48,13 +70,50 @@ func TestRecordFailedWorkflowJob(t *testing.T) { assertFailedJobLog(t, &logs, map[string]any{ repositoryKey: repositoryName, workflowKey: "CI", jobKey: buildName, "failed_steps": "compile, test, three, four, five, six, seven, eight", - headBranchKey: "main", headSHAKey: "123abc", "run_id": float64(493), + headBranchKey: mainBranch, headSHAKey: jobSHA, runIDKey: float64(493), startedAtKey: "2026-11-15T12:00:00Z", completedAtKey: "2026-11-15T12:01:00Z", }) - checkMetrics(t, reader, map[string]map[string]string{ - eventsName: {repositoryKey: repositoryName, eventKey: workflowJobEvent, actionKey: completedAction}, - ciFailuresName: {repositoryKey: repositoryName, workflowKey: "CI", jobKey: buildName}, + checkJobHistograms( + t, + reader, + pullRequestEvent, + noRunner, + failureResult, + map[string]float64{queueMetric: 15, runMetric: 60}, + ) + assertJobLog(t, &logs, finishedMessage, map[string]any{ + repositoryKey: repositoryName, workflowKey: "CI", jobKey: buildName, conclusionKey: failureResult, + eventClassKey: pullRequestEvent, runnerKey: noRunner, headBranchKey: mainBranch, headSHAKey: jobSHA, + runIDKey: float64(493), jobIDKey: float64(42), queueSecondsKey: float64(15), runSecondsKey: float64(60), }) + + if got := collectCounters(t, reader)[ciFailuresName]; !reflect.DeepEqual( + got, + map[string]int64{"job=build,repository=tbhb-dev/github-metrics,workflow=CI": 1}, + ) { + t.Fatalf("failure counter = %v", got) + } + + before, counters := logs.String(), collectCounters(t, reader) + + err = consumer.Record(t.Context(), workflowJobEvent, []byte(body)) + if err != nil { + t.Fatal(err) + } + + checkJobHistograms( + t, + reader, + pullRequestEvent, + noRunner, + failureResult, + map[string]float64{queueMetric: 15, runMetric: 60}, + ) + + if logs.String() != before || !reflect.DeepEqual(collectCounters(t, reader), counters) || + len(strings.Split(strings.TrimSpace(before), "\n")) != 2 { + t.Fatal("redelivery changed logs or counters, or first delivery did not log twice") + } } func TestNonFailureWorkflowJobs(t *testing.T) { @@ -64,7 +123,7 @@ func TestNonFailureWorkflowJobs(t *testing.T) { {workflowJobEvent, completedAction, successResult}, {workflowJobEvent, completedAction, "cancelled"}, {workflowJobEvent, "in_progress", failureResult}, - {"push", completedAction, failureResult}, + {pushEvent, completedAction, failureResult}, } { t.Run(test.event+"/"+test.action+"/"+test.conclusion, func(t *testing.T) { t.Parallel() @@ -72,14 +131,20 @@ func TestNonFailureWorkflowJobs(t *testing.T) { var logs bytes.Buffer consumer, reader := newRecorderWithLogger(t, newLedger(nil), slog.New(slog.NewJSONHandler(&logs, nil))) - body := `{"action":"` + test.action + `","workflow_job":{"conclusion":"` + test.conclusion + `"}}` + body := `{"action":"` + test.action + `","workflow_job":{"id":42,"conclusion":"` + test.conclusion + `"}}` err := consumer.Record(t.Context(), test.event, []byte(body)) if err != nil { t.Fatal(err) } - if logs.Len() != 0 { + if test.event == workflowJobEvent && test.action == completedAction { + assertJobLog(t, &logs, finishedMessage, map[string]any{ + repositoryKey: unknownRepository, workflowKey: "", jobKey: "", conclusionKey: test.conclusion, + eventClassKey: pushEvent, runnerKey: noRunner, headBranchKey: "", headSHAKey: "", + runIDKey: float64(0), jobIDKey: float64(42), + }) + } else if logs.Len() != 0 { t.Fatalf("unexpected job log: %s", &logs) } @@ -103,7 +168,7 @@ func TestFailedWorkflowJobCleansText(t *testing.T) { body, err := json.Marshal(map[string]any{ actionKey: completedAction, workflowJobEvent: map[string]any{ - "workflow_name": longText, nameKey: longText, conclusionKey: failureResult, + "id": 42, "workflow_name": longText, nameKey: longText, conclusionKey: failureResult, headBranchKey: longText, headSHAKey: longText, startedAtKey: longText, completedAtKey: longText, "steps": []map[string]string{{nameKey: longText, conclusionKey: failureResult}}, }, @@ -123,7 +188,7 @@ func TestFailedWorkflowJobCleansText(t *testing.T) { assertFailedJobLog(t, &logs, map[string]any{ repositoryKey: unknownRepository, workflowKey: logText, jobKey: logText, "failed_steps": logText, - headBranchKey: logText, headSHAKey: logText, "run_id": float64(0), + headBranchKey: logText, headSHAKey: logText, runIDKey: float64(0), startedAtKey: logText, completedAtKey: logText, }) checkMetrics(t, reader, map[string]map[string]string{ @@ -135,18 +200,214 @@ func TestFailedWorkflowJobCleansText(t *testing.T) { func assertFailedJobLog(t *testing.T, logs *bytes.Buffer, want map[string]any) { t.Helper() - var got map[string]any + assertJobLog(t, logs, "ci job failed", want) +} - err := json.Unmarshal(logs.Bytes(), &got) +func assertJobLog(t *testing.T, logs *bytes.Buffer, message string, want map[string]any) { + t.Helper() + + for line := range strings.SplitSeq(strings.TrimSpace(logs.String()), "\n") { + var got map[string]any + + err := json.Unmarshal([]byte(line), &got) + if err != nil { + t.Fatal(err) + } + + if got["msg"] != message { + continue + } + + delete(got, "time") + + want["level"], want["msg"] = "INFO", message + + if !reflect.DeepEqual(got, want) { + t.Fatalf("log = %v, want %v", got, want) + } + + return + } + + t.Fatalf("missing %q log: %s", message, logs) +} + +type workflowTimingTest struct { + want map[string]float64 + branch, class, created, started, completed, runner string +} + +func TestWorkflowJobTimings(t *testing.T) { + t.Parallel() + + both := map[string]float64{queueMetric: 15, runMetric: 60} + + for _, test := range []workflowTimingTest{ + {both, "gh-readonly-queue/main/pr-1", "merge_group", queueStart, jobStart, jobEnd, "ubuntu-latest"}, + {both, mainBranch, pushEvent, queueStart, jobStart, jobEnd, noRunner}, + {both, "feature", pullRequestEvent, queueStart, jobStart, jobEnd, noRunner}, + {map[string]float64{runMetric: 60}, "missing created", pullRequestEvent, "", jobStart, jobEnd, noRunner}, + {map[string]float64{queueMetric: 15}, "invalid end", pullRequestEvent, queueStart, jobStart, "invalid", noRunner}, + {map[string]float64{}, "missing started", pullRequestEvent, queueStart, "", jobEnd, noRunner}, + {map[string]float64{runMetric: 60}, "negative queue", pullRequestEvent, "12:00:01", jobStart, jobEnd, noRunner}, + {map[string]float64{queueMetric: 15}, "negative run", pullRequestEvent, queueStart, jobStart, "11:59:59", noRunner}, + } { + t.Run(test.branch, func(t *testing.T) { + t.Parallel() + + reader, logs, ledger := recordJobTimingFixture(t, test) + + checkJobHistograms(t, reader, test.class, test.runner, successResult, test.want) + wantLog := map[string]any{ + repositoryKey: repositoryName, workflowKey: "CI", jobKey: buildName, conclusionKey: successResult, + eventClassKey: test.class, runnerKey: test.runner, headBranchKey: test.branch, headSHAKey: jobSHA, + runIDKey: float64(493), jobIDKey: float64(42), + } + + for metricName, seconds := range test.want { + wantLog[strings.TrimPrefix(metricName, "github.ci.job.")] = seconds + } + + assertJobLog(t, logs, finishedMessage, wantLog) + + if !ledger.claimed["42\x00ci_job"] || len(strings.Split(strings.TrimSpace(logs.String()), "\n")) != 1 { + t.Fatal("expected job claim and one finished log") + } + }) + } +} + +func recordJobTimingFixture( + t *testing.T, + test workflowTimingTest, +) (*sdkmetric.ManualReader, *bytes.Buffer, *fakeLedger) { + t.Helper() + + job := map[string]any{ + "id": 42, "workflow_name": "CI", nameKey: buildName, conclusionKey: successResult, + headBranchKey: test.branch, headSHAKey: jobSHA, runIDKey: 493, + } + + for key, value := range map[string]string{ + createdAtKey: test.created, startedAtKey: test.started, completedAtKey: test.completed, + } { + if value != "" { + job[key] = "2026-11-15T" + value + "Z" + } + } + + if test.runner != noRunner { + job["labels"] = []string{test.runner, "ignored"} + } else if test.branch == mainBranch { + job["labels"] = []string{} + } + + body, err := json.Marshal(map[string]any{ + actionKey: completedAction, workflowJobEvent: job, + repositoryKey: map[string]string{fullNameKey: repositoryName, "default_branch": mainBranch}, + }) + if err != nil { + t.Fatal(err) + } + + var logs bytes.Buffer + + ledger := newLedger(nil) + consumer, reader := newRecorderWithLogger(t, ledger, slog.New(slog.NewJSONHandler(&logs, nil))) + + err = consumer.Record(t.Context(), workflowJobEvent, body) + if err != nil { + t.Fatal(err) + } + + return reader, &logs, ledger +} + +func checkJobHistograms( + t *testing.T, + reader *sdkmetric.ManualReader, + class, runner, conclusion string, + want map[string]float64, +) { + t.Helper() + + var data metricdata.ResourceMetrics + + err := reader.Collect(t.Context(), &data) if err != nil { - t.Fatalf("want one JSON log, got %q: %v", logs, err) + t.Fatal(err) } - delete(got, "time") + got := map[string]float64{} + + for _, scope := range data.ScopeMetrics { + for _, measurement := range scope.Metrics { + if measurement.Name != queueMetric && measurement.Name != runMetric { + continue + } - want["level"], want["msg"] = "INFO", "ci job failed" + got[measurement.Name] = checkJobHistogramPoint(t, measurement, class, runner, conclusion) + } + } if !reflect.DeepEqual(got, want) { - t.Fatalf("log = %v, want %v", got, want) + t.Fatalf("histograms = %v, want %v", got, want) + } +} + +func checkJobHistogramPoint(t *testing.T, measurement metricdata.Metrics, class, runner, conclusion string) float64 { + t.Helper() + + histogram, ok := measurement.Data.(metricdata.Histogram[float64]) + if !ok || measurement.Unit != "s" || len(histogram.DataPoints) != 1 { + t.Fatalf("unexpected histogram: %v", measurement) + } + + point := histogram.DataPoints[0] + attrs := map[string]string{} + + for _, attr := range point.Attributes.ToSlice() { + attrs[string(attr.Key)] = attr.Value.AsString() + } + + wantAttrs := map[string]string{ + repositoryKey: repositoryName, workflowKey: "CI", jobKey: buildName, + conclusionKey: conclusion, eventClassKey: class, runnerKey: runner, + } + bounds := []float64{5, 15, 30, 60, 120, 300, 600, 900, 1200, 1800, 2700, 3600, 5400, 7200} + + if point.Count != 1 || !reflect.DeepEqual(attrs, wantAttrs) || !reflect.DeepEqual(point.Bounds, bounds) { + t.Fatalf("unexpected histogram point: %v", point) + } + + return point.Sum +} + +func TestWorkflowJobClaimSkips(t *testing.T) { + t.Parallel() + + for _, test := range []struct { + claimErr error + name, id string + }{ + {errClaim, "claim error", `"id":42,`}, {nil, "zero id", `"id":0,`}, {nil, "missing id", ""}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + var logs bytes.Buffer + + ledger := newLedger(func(l *fakeLedger) { l.claimErr = test.claimErr }) + consumer, reader := newRecorderWithLogger(t, ledger, slog.New(slog.NewJSONHandler(&logs, nil))) + body := `{"action":"completed","workflow_job":{` + test.id + `"conclusion":"failure",` + + `"created_at":"2026-11-15T11:59:45Z","started_at":"2026-11-15T12:00:00Z","completed_at":"2026-11-15T12:01:00Z"}}` + + err := consumer.Record(t.Context(), workflowJobEvent, []byte(body)) + if !errors.Is(err, test.claimErr) || logs.Len() != 0 || len(ledger.claims) != 0 { + t.Fatalf("error = %v, logs = %s, claims = %v", err, &logs, ledger.claims) + } + + checkMetrics(t, reader, map[string]map[string]string{}) + }) } }