From dce09c3ea6bc95db5afcdaaa842b2296fc683ed7 Mon Sep 17 00:00:00 2001 From: "tbhb.dev Agent" Date: Tue, 24 Nov 2026 20:23:59 +0000 Subject: [PATCH 1/2] feat(recorder): record completed CI job timings Generated-by: LLM effort=high;harness=codex:0.171.0;model=openai:gpt-6.1-sol;session=sha-256-64:524a7bd302fd1c59;surface=exec --- .../appendix-a-trace-and-metric-catalog.md | 15 +- internal/recorder/recorder.go | 161 ++++++++-- internal/recorder/recorder_test.go | 14 +- internal/recorder/workflow_job_test.go | 293 +++++++++++++++++- 4 files changed, 435 insertions(+), 48 deletions(-) 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{}) + }) } } From 255d421d6473ec3b056627b205b1e2dcb0aba22d Mon Sep 17 00:00:00 2001 From: "tbhb.dev Agent" Date: Tue, 24 Nov 2026 15:53:54 -0500 Subject: [PATCH 2/2] feat(backfill): log recent CI jobs with original timestamps Generated-by: LLM effort=high;harness=codex:0.166.0;model=openai:gpt-6.1-sol;session=sha-256-64:87811731daa659c7;surface=exec --- .cspell-words.txt | 2 + cmd/github-metrics/main.go | 23 +- cmd/github-metrics/main_test.go | 20 ++ cmd/github-metrics/reconciler.go | 48 +++- deploy/compose.yaml | 1 + .../11-risks-and-technical-debt.md | 2 + internal/reconcile/BUILD.bazel | 4 + internal/reconcile/cibackfill.go | 236 ++++++++++++++++++ internal/reconcile/cibackfill_test.go | 210 ++++++++++++++++ internal/reconcile/testdata/ci_jobs.json | 7 + internal/recorder/recorder.go | 6 + 11 files changed, 546 insertions(+), 13 deletions(-) create mode 100644 internal/reconcile/cibackfill.go create mode 100644 internal/reconcile/cibackfill_test.go create mode 100644 internal/reconcile/testdata/ci_jobs.json diff --git a/.cspell-words.txt b/.cspell-words.txt index bfc0acd..10b6324 100644 --- a/.cspell-words.txt +++ b/.cspell-words.txt @@ -223,3 +223,5 @@ sdkmetric stdr metricdata nilerr +cibackfill +embedsrcs diff --git a/cmd/github-metrics/main.go b/cmd/github-metrics/main.go index bc48237..31c5655 100644 --- a/cmd/github-metrics/main.go +++ b/cmd/github-metrics/main.go @@ -36,6 +36,7 @@ import ( "go.opentelemetry.io/otel/metric" "github.com/tbhb-dev/github-metrics/internal/receiver" + "github.com/tbhb-dev/github-metrics/internal/reconcile" "github.com/tbhb-dev/github-metrics/internal/recorder" "github.com/tbhb-dev/github-metrics/internal/store" "github.com/tbhb-dev/github-metrics/internal/telemetry" @@ -83,12 +84,18 @@ func main() { } } +//nolint:funlen // Startup owns service shutdown ordering. func run(ctx context.Context, addr string, log *slog.Logger) error { cfg, err := reconcilerConfig(os.Getenv) if err != nil { return err } + backfillCfg, err := ciBackfillConfig(os.Getenv) + if err != nil { + return err + } + file := os.Getenv("WEBHOOK_SECRET_FILE") if file == "" { return errNoSecretFile @@ -131,7 +138,7 @@ func run(ctx context.Context, addr string, log *slog.Logger) error { endpoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") - consumer, loop, err := newConsumers(ctx, endpoint, cfg, meter, repo, log) + consumer, loop, client, err := newConsumers(ctx, endpoint, cfg, meter, repo, log) if err != nil { shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout) defer cancel() @@ -155,6 +162,18 @@ func run(ctx context.Context, addr string, log *slog.Logger) error { log.InfoContext(ctx, "listening", "addr", addr) + backfillDone := make(chan struct{}) + + if client != nil && backfillCfg.Days > 0 { + go func() { + defer close(backfillDone) + + reconcile.BackfillCI(ctx, client, repo, log, backfillCfg, time.Now()) + }() + } else { + close(backfillDone) + } + select { case err = <-serveErr: // Shut down the worker and reconciler before closing their store. @@ -166,6 +185,8 @@ func run(ctx context.Context, addr string, log *slog.Logger) error { shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout) defer cancel() + <-backfillDone + return errors.Join( err, srv.Shutdown(shutdownCtx), <-workerErr, <-reconcileErr, shutdownTelemetry(shutdownCtx), repo.Close(), ) diff --git a/cmd/github-metrics/main_test.go b/cmd/github-metrics/main_test.go index adfa5b1..b3483a7 100644 --- a/cmd/github-metrics/main_test.go +++ b/cmd/github-metrics/main_test.go @@ -271,3 +271,23 @@ func TestReconcilerConfigComplete(t *testing.T) { } } } + +func TestCIBackfillConfig(t *testing.T) { + t.Parallel() + + for _, value := range []string{ + "", "o/r:7", "o/r:1", "o/r:8", "o/r:0", "o/r:-1", + "o/r:day", "o/r", "o:7", "o/r/extra:7", "o/..:7", "o/r:7\n", + } { + cfg, err := ciBackfillConfig(func(string) string { return value }) + valid := value == "" || value == "o/r:7" || value == "o/r:1" + + if valid { + if err != nil || (value != "" && (cfg.Repository != "o/r" || cfg.Days < 1 || cfg.Days > 7)) { + t.Fatalf("config = %+v, error = %v", cfg, err) + } + } else if err == nil || err.Error() != "GITHUB_CI_BACKFILL must name a repository and days from 1 to 7" { + t.Fatalf("expected redacted variable error, got %v", err) + } + } +} diff --git a/cmd/github-metrics/reconciler.go b/cmd/github-metrics/reconciler.go index 20f66bf..06f7bbd 100644 --- a/cmd/github-metrics/reconciler.go +++ b/cmd/github-metrics/reconciler.go @@ -12,6 +12,7 @@ import ( "net/http" "net/url" "os" + "regexp" "strconv" "strings" "time" @@ -40,6 +41,7 @@ var ( errInvalidAppID = errors.New(appIDEnv + " must be a positive integer") errInvalidInstallationID = errors.New(installationIDEnv + " must be a positive integer") errInvalidBaseURL = errors.New(apiURLEnv + " must be a valid HTTPS API base URL") + errInvalidCIBackfill = errors.New("GITHUB_CI_BACKFILL must name a repository and days from 1 to 7") errReadAppKey = errors.New("read " + appKeyFileEnv) ) @@ -93,14 +95,36 @@ func reconcilerConfig(env func(string) string) (reconcileConfig, error) { }, nil } +// ciBackfillConfig validates the trigger even when reconciliation is disabled. +func ciBackfillConfig(env func(string) string) (reconcile.CIConfig, error) { + const name = "GITHUB_CI_BACKFILL" + + var cfg reconcile.CIConfig + + value := env(name) + if value == "" { + return cfg, nil + } + + match := regexp.MustCompile(`^([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*/[A-Za-z0-9_.-]+):([1-7])$`).FindStringSubmatch(value) + if match == nil || strings.HasSuffix(match[1], "/.") || strings.HasSuffix(match[1], "/..") { + return cfg, errInvalidCIBackfill + } + + cfg.Repository = match[1] + cfg.Days = int(match[2][0] - '0') + + return cfg, nil +} + //nolint:ireturn // The worker accepts either recorder through its interface. func newConsumers( ctx context.Context, endpoint string, cfg reconcileConfig, meter metric.Meter, repo *store.Bolt, log *slog.Logger, -) (worker.Recorder, *reconcile.Loop, error) { +) (worker.Recorder, *reconcile.Loop, *ghclient.Client, error) { // cspell:ignore contextcheck consumer, err := newRecorder(endpoint, meter, repo, log) //nolint:contextcheck // Recorder setup seeds its counters. if err != nil { - return nil, nil, err + return nil, nil, nil, err } log.InfoContext(ctx, "recorder mode", "configured", endpoint != "") @@ -109,26 +133,26 @@ func newConsumers( if !configured || cfg.keyFile == "" { log.InfoContext(ctx, "reconciler disabled") - return consumer, nil, nil + return consumer, nil, nil, nil } - loop, err := newReconciler(cfg, meter, record, repo, log) + loop, client, err := newReconciler(cfg, meter, record, repo, log) - return consumer, loop, err + return consumer, loop, client, err } func newReconciler( cfg reconcileConfig, meter metric.Meter, record *recorder.Recorder, repo reconcile.Watermarks, log *slog.Logger, -) (*reconcile.Loop, error) { +) (*reconcile.Loop, *ghclient.Client, error) { // Relative request paths must resolve inside the API base path. base, err := url.Parse(strings.TrimRight(cfg.apiURL, "/") + "/") if err != nil || base.Scheme != "https" { - return nil, errInvalidBaseURL + return nil, nil, errInvalidBaseURL } key, err := os.ReadFile(cfg.keyFile) if err != nil { - return nil, errReadAppKey + return nil, nil, errReadAppKey } source, err := appauth.New(appauth.Config{ @@ -136,14 +160,14 @@ func newReconciler( AppID: cfg.appID, InstallationID: cfg.installationID, }) if err != nil { - return nil, fmt.Errorf("create installation token source: %w", err) + return nil, nil, fmt.Errorf("create installation token source: %w", err) } tags := ghclient.NewETags() client, err := ghclient.New(base.String(), http.DefaultClient, budget.New(), source, tags) if err != nil { - return nil, errInvalidBaseURL + return nil, nil, errInvalidBaseURL } lister := reconcile.NewLister(client, tags, base) @@ -153,10 +177,10 @@ func newReconciler( loop, err := reconcile.NewLoop(pass, meter, log, nil) if err != nil { - return nil, fmt.Errorf("create reconciler loop: %w", err) + return nil, nil, fmt.Errorf("create reconciler loop: %w", err) } - return loop, nil + return loop, client, nil } func startReconciler(ctx context.Context, loop *reconcile.Loop, stop context.CancelFunc) <-chan error { diff --git a/deploy/compose.yaml b/deploy/compose.yaml index 4b87519..3b96e7a 100644 --- a/deploy/compose.yaml +++ b/deploy/compose.yaml @@ -57,6 +57,7 @@ services: STORE_FILE: /var/lib/github-metrics/store.db GITHUB_APP_ID: ${GITHUB_APP_ID:-} GITHUB_INSTALLATION_ID: ${GITHUB_INSTALLATION_ID:-} + GITHUB_CI_BACKFILL: ${GITHUB_CI_BACKFILL:-} GITHUB_API_URL: ${GITHUB_API_URL:-} GITHUB_APP_KEY_FILE: ${GITHUB_APP_ID:+/run/secrets/github_app_key} WEBHOOK_SECRET_FILE: /run/secrets/webhook_secret diff --git a/docs/architecture/11-risks-and-technical-debt.md b/docs/architecture/11-risks-and-technical-debt.md index f08ebfb..430ed92 100644 --- a/docs/architecture/11-risks-and-technical-debt.md +++ b/docs/architecture/11-risks-and-technical-debt.md @@ -21,6 +21,8 @@ | The operator never retires the previous webhook secret or never rotates the App key | An old credential keeps working | Gates of the threat-model follow-up, plan step 6 | New, deferred to step 6 | | Backend access and retention for private-repository names and logins | Wider exposure than the operator intends | The operator confirms it in the threat-model follow-up | Unverified | +Tech debt: CI history backfill caps run and job pages without a resume cursor. A crash after a durable claim can lose a log. Backfilled claims also suppress later live timing metrics. The one-off Loki pass accepts these limits. + ## Plan Step 1 finished. Steps 2, 3, and 5 to 8 remain open work. Today `main` has the receiver, the request budget, and the GitHub client, which are parts of steps 3 and 5. diff --git a/internal/reconcile/BUILD.bazel b/internal/reconcile/BUILD.bazel index 8170f58..85512c9 100644 --- a/internal/reconcile/BUILD.bazel +++ b/internal/reconcile/BUILD.bazel @@ -9,6 +9,7 @@ repo_files() go_library( name = "reconcile", srcs = [ + "cibackfill.go", "events.go", "list.go", "loop.go", @@ -28,11 +29,14 @@ go_library( go_test( name = "reconcile_test", srcs = [ + "cibackfill_test.go", "events_test.go", "list_test.go", "loop_test.go", "run_test.go", ], + data = glob(["testdata/**"]), + embedsrcs = ["testdata/ci_jobs.json"], visibility = ["//:__pkg__"], deps = [ ":reconcile", diff --git a/internal/reconcile/cibackfill.go b/internal/reconcile/cibackfill.go new file mode 100644 index 0000000..fc6100e --- /dev/null +++ b/internal/reconcile/cibackfill.go @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright Tony Burns + +package reconcile + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/url" + "strconv" + "time" + + "github.com/tbhb-dev/github-metrics/internal/budget" + "github.com/tbhb-dev/github-metrics/internal/ghclient" + "github.com/tbhb-dev/github-metrics/internal/recorder" +) + +const ( + completed = "completed" + runPageLimit = 30 + jobPageLimit = 3 +) + +// CIConfig selects one repository and a window of up to seven days. +type CIConfig struct { + Repository string + Days int +} + +// Ledger shares the live recorder's durable job claims. +type Ledger interface { + ClaimMilestone(key string) (bool, error) +} + +type ciPass struct { + client *ghclient.Client + ledger Ledger + log *slog.Logger + start, end time.Time + repository, defaultBranch string + runs, logged, pages, skipped int +} + +// BackfillCI logs exactly one terminal summary, including on cancellation or a claim error. +func BackfillCI( + ctx context.Context, client *ghclient.Client, ledger Ledger, log *slog.Logger, cfg CIConfig, now time.Time, +) { + state := ciPass{ + client: client, ledger: ledger, log: log, repository: cfg.Repository, + defaultBranch: "", start: now.Add(-time.Duration(cfg.Days) * 24 * time.Hour), end: now, + runs: 0, logged: 0, skipped: 0, pages: 0, + } + + log.InfoContext(ctx, "ci backfill started", "repository", cfg.Repository, "days", cfg.Days) + + err := state.walk(ctx, "/repos/"+cfg.Repository+"/actions/runs?per_page=100&created="+ + url.QueryEscape(">="+state.start.Format(time.RFC3339)), runPageLimit, state.recordRuns) + if err == nil { + err = ctx.Err() + } + + fields := []any{ + "repository", cfg.Repository, "runs", state.runs, "jobs_logged", state.logged, + "jobs_skipped", state.skipped, "pages", state.pages, "duration", time.Since(now), + } + + if err != nil { + status := 0 + + if response, ok := errors.AsType[*ghclient.StatusError](err); ok { + status = response.Status + } + + // Error text from dependencies may contain operator configuration; keep only status. + log.ErrorContext(ctx, "ci backfill failed", append(fields, "status", status, "errors", 1)...) + + return + } + + log.InfoContext(ctx, "ci backfill finished", fields...) +} + +func (p *ciPass) walk(ctx context.Context, target string, limit int, visit func(context.Context, []byte) error) error { + for range limit { + response, err := p.client.Get(ctx, budget.Backfill, target) + + p.pages++ + + if err != nil { + return fmt.Errorf("read CI history: %w", err) + } + + if response.NotModified() { + return nil + } + + err = visit(ctx, response.Body) + if err != nil { + return err + } + + if response.Next == "" { + return nil + } + + target = response.Next + } + + return nil +} + +func (p *ciPass) recordRuns(ctx context.Context, body []byte) error { + var page struct { + Runs []struct { + Status string `json:"status"` + Event string `json:"event"` + ID int64 `json:"id"` + } `json:"workflow_runs"` //nolint:tagliatelle // GitHub field name. + } + + err := json.Unmarshal(body, &page) + if err != nil { + return fmt.Errorf("decode runs: %w", err) + } + + for _, run := range page.Runs { + p.runs++ + + if run.Status != completed { + continue + } + + if p.defaultBranch == "" { + response, readErr := p.client.Get(ctx, budget.Backfill, "/repos/"+p.repository) + + p.pages++ + + if readErr != nil { + return fmt.Errorf("read repository: %w", readErr) + } + + var repo struct { + DefaultBranch string `json:"default_branch"` //nolint:tagliatelle // GitHub field name. + } + + err = json.Unmarshal(response.Body, &repo) + if err != nil { + return fmt.Errorf("decode repository: %w", err) + } + + p.defaultBranch = repo.DefaultBranch + } + + err = p.walk(ctx, "/repos/"+p.repository+"/actions/runs/"+strconv.FormatInt(run.ID, 10)+ + "/jobs?per_page=100&filter=all", jobPageLimit, func(ctx context.Context, body []byte) error { + return p.recordJobs(ctx, body, run.Event) + }) + if err != nil { + return err + } + } + + return nil +} + +//nolint:gocognit,cyclop // Keep filtering, claiming and logging in order. +func (p *ciPass) recordJobs(ctx context.Context, body []byte, event string) error { + var page struct { + Jobs []recorder.WorkflowJob `json:"jobs"` + } + + err := json.Unmarshal(body, &page) + if err != nil { + return fmt.Errorf("decode jobs: %w", err) + } + + for _, job := range page.Jobs { + if ctx.Err() != nil { + return fmt.Errorf("cancel backfill: %w", ctx.Err()) + } + + end, parseErr := time.Parse(time.RFC3339, job.CompletedAt) + + if parseErr != nil || end.IsZero() || end.Before(p.start) || end.After(p.end) { + p.skipped++ + + continue + } + + claimed, claimErr := p.ledger.ClaimMilestone(strconv.FormatInt(job.ID, 10) + "\x00ci_job") + if claimErr != nil { + return fmt.Errorf("claim CI job: %w", claimErr) + } + + if !claimed { + p.skipped++ + + continue + } + + record := slog.NewRecord(end, slog.LevelInfo, "ci job finished", 0) + runner := "none" + + if len(job.Labels) > 0 { + runner = job.Labels[0] + } + + record.Add("repository", p.repository, "workflow", job.WorkflowName, "job", job.Name, + "conclusion", job.Conclusion, "event_class", recorder.JobEventClass(job.HeadBranch, p.defaultBranch), + "runner", runner, "head_branch", job.HeadBranch, "head_sha", job.HeadSHA, + "run_id", job.RunID, "job_id", job.ID, "event", event, "source", "backfill") + + for _, duration := range []struct{ name, start, end string }{ + {"queue_seconds", job.CreatedAt, job.StartedAt}, {"run_seconds", job.StartedAt, job.CompletedAt}, + } { + start, startErr := time.Parse(time.RFC3339, duration.start) + finish, endErr := time.Parse(time.RFC3339, duration.end) + + if startErr == nil && endErr == nil && !start.IsZero() && !finish.IsZero() && !finish.Before(start) { + record.Add(duration.name, finish.Sub(start).Seconds()) + } + } + + err = p.log.Handler().Handle(ctx, record) + if err != nil { + return fmt.Errorf("log CI job: %w", err) + } + + p.logged++ + } + + return nil +} diff --git a/internal/reconcile/cibackfill_test.go b/internal/reconcile/cibackfill_test.go new file mode 100644 index 0000000..f53f2eb --- /dev/null +++ b/internal/reconcile/cibackfill_test.go @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright Tony Burns + +package reconcile_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + _ "embed" + + "github.com/tbhb-dev/github-metrics/internal/budget" + "github.com/tbhb-dev/github-metrics/internal/ghclient" + ci "github.com/tbhb-dev/github-metrics/internal/reconcile" +) + +type ledger struct { + claims map[string]bool + err error +} + +func (l ledger) ClaimMilestone(key string) (bool, error) { + if l.err != nil { + return false, l.err + } + + previous := l.claims[key] + l.claims[key] = true + + return !previous, nil +} + +//go:embed testdata/ci_jobs.json +var jobs string + +const ( + capMode = "cap" + forbiddenMode = "forbidden" + runs = `{"workflow_runs":[{"id":1,"status":"completed","event":"schedule"},{"id":2,"status":"in_progress"}]}` +) + +func TestCIBackfill(t *testing.T) { + t.Parallel() + + for _, mode := range []string{"success", forbiddenMode, "decode_error", "claim_error", "cancelled", capMode} { + t.Run(mode, func(t *testing.T) { + t.Parallel() + + var ( + logs bytes.Buffer + calls atomic.Int32 + ) + + server := httptest.NewTLSServer(history(t, mode, &calls)) + + defer server.Close() + + client, err := ghclient.New(server.URL, server.Client(), budget.New(), fakeTokens{}, ghclient.NewETags()) + if err != nil { + t.Fatal(err) + } + + claims := ledger{claims: map[string]bool{"2\x00ci_job": true}, err: nil} + + if mode == "claim_error" { + claims.err = errors.ErrUnsupported + } + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + if mode == "cancelled" { + cancel() + } + + ci.BackfillCI(ctx, client, claims, slog.New(slog.NewJSONHandler(&logs, nil)), + ci.CIConfig{Repository: listedRepo, Days: 7}, time.Date(2000, time.January, 1, 1, 0, 0, 0, time.UTC)) + checkLogs(t, mode, calls.Load(), claims, logs.String()) + }) + } +} + +//nolint:gocognit,cyclop // The fake server covers pagination and failure responses. +func history(t *testing.T, mode string, calls *atomic.Int32) http.HandlerFunc { + t.Helper() + + return func(resp http.ResponseWriter, req *http.Request) { + calls.Add(1) + + if mode == forbiddenMode { + resp.WriteHeader(http.StatusForbidden) + + return + } + + body := runs + + switch { + case strings.HasSuffix(req.URL.Path, "/jobs"): + body = jobs + + if req.URL.Query().Get("page") == "" && req.URL.Query().Get("filter") != "all" { + t.Error("missing all attempts filter") + } + + if req.URL.Query().Get("page") == "" { + resp.Header().Set("Link", "; rel="next"`) + } + + case strings.HasSuffix(req.URL.Path, "/actions/runs"): + if req.URL.Query().Get("page") == "" && + req.URL.Query().Get("created") != ">=1999-12-25T01:00:00Z" && + mode != capMode { + t.Errorf("created = %s", req.URL.Query().Get("created")) + } + + if req.URL.Query().Get("page") != "" || mode == capMode { + body = `{"workflow_runs":[]}` + } + + if req.URL.Query().Get("page") == "" || mode == capMode { + resp.Header().Set("Link", "; rel="next"`) + } + + default: + body = `{"default_branch":"main"}` + } + + if mode == "decode_error" { + body = "{" + } + + write(t, resp, body) + } +} + +//nolint:gocognit,cyclop // Each case checks its terminal summary and job records. +func checkLogs(t *testing.T, mode string, calls int32, claims ledger, logs string) { + t.Helper() + + entries := map[string][]map[string]any{} + + for line := range strings.SplitSeq(strings.TrimSpace(logs), "\n") { + var entry map[string]any + + err := json.Unmarshal([]byte(line), &entry) + if err != nil { + t.Fatal(err) + } + + message := fmt.Sprint(entry["msg"]) + + entries[message] = append(entries[message], entry) + } + + finished, failed := entries["ci backfill finished"], entries["ci backfill failed"] + + if len(entries["ci backfill started"]) != 1 || len(finished)+len(failed) != 1 { + t.Fatalf("terminal logs: %s", logs) + } + + if mode != "success" && mode != capMode { + if len(failed) != 1 || len(entries["ci job finished"]) != 0 { + t.Fatalf("want failure without job logs: %s", logs) + } + + if mode == forbiddenMode && (failed[0]["status"] != float64(403) || calls != 1) { + t.Fatalf("403 evidence: %s", logs) + } + + return + } + + if mode == capMode { + if calls != 30 || finished[0]["pages"] != float64(30) { + t.Fatalf("cap: calls=%d logs=%s", calls, logs) + } + + return + } + + logged := entries["ci job finished"] + + if len(logged) != 1 || !claims.claims["1\x00ci_job"] || len(claims.claims) != 2 { + t.Fatalf("claims or duplicates: %s %v", logs, claims.claims) + } + + for key, want := range map[string]any{ + "time": "2000-01-01T00:02:00Z", "event": "schedule", "event_class": "push", + "source": "backfill", "runner": "linux", "queue_seconds": float64(60), "run_seconds": float64(60), + } { + if logged[0][key] != want { + t.Errorf("%s = %v, want %v", key, logged[0][key], want) + } + } + + if finished[0]["pages"] != float64(5) || finished[0]["jobs_skipped"] != float64(9) { + t.Fatalf("summary: %s", logs) + } +} diff --git a/internal/reconcile/testdata/ci_jobs.json b/internal/reconcile/testdata/ci_jobs.json new file mode 100644 index 0000000..2ce52f0 --- /dev/null +++ b/internal/reconcile/testdata/ci_jobs.json @@ -0,0 +1,7 @@ +{"jobs":[ +{"id":1,"run_id":1,"status":"completed","workflow_name":"CI","name":"test","conclusion":"success","head_branch":"main", +"head_sha":"abc","labels":["linux"],"created_at":"2000-01-01T00:00:00Z","started_at":"2000-01-01T00:01:00Z","completed_at":"2000-01-01T00:02:00Z"}, +{"id":2,"status":"completed","completed_at":"2000-01-01T00:02:00Z"}, +{"id":3,"status":"completed","completed_at":"1999-12-01T00:00:00Z"}, +{"id":4,"status":"completed"}, +{"id":5,"status":"completed","completed_at":"2000-01-02T00:00:00Z"}]} diff --git a/internal/recorder/recorder.go b/internal/recorder/recorder.go index 9fcfade..b8cc2bd 100644 --- a/internal/recorder/recorder.go +++ b/internal/recorder/recorder.go @@ -110,6 +110,12 @@ type workflowJob struct { RunID int64 `json:"run_id"` //nolint:tagliatelle // GitHub uses this field name. } +// WorkflowJob is the shared GitHub job payload. +type WorkflowJob = workflowJob + +// JobEventClass uses the live recorder's branch classification. +func JobEventClass(branch, defaultBranch string) string { return jobEventClass(branch, defaultBranch) } + type pullRequest struct { Body string `json:"body"` NodeID string `json:"node_id"` //nolint:tagliatelle // GitHub uses this field name.