Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/design/reconciler-backfill.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ Under the 24-hour and creation-time gates, a backfill over history records no me
| `*StatusError` 403 or 404 for one repository | Log it, skip the repository, finish the run with result `partial` |
| `ErrGaveUp`, or the run deadline | Stop the run with result `partial`. The budget has already backed off (`internal/ghclient/ghclient.go:216-222`) |
| `ErrBodyTooLarge`, or a decode error | Skip the repository, clear its first-page tag, result `partial` |
| A store error from a claim or a watermark write | Return the error and stop the service, as the worker does (`internal/worker/worker.go:66-69`, `cmd/github-metrics/main.go:126-130`). The restart policy brings it back (`deploy/compose.yaml:51`) |
| A store error from a claim or a watermark write | Clear the first-page tag and return the error. Count the pass as `partial` and retry on the next tick. After three consecutive pass errors, return the last error to stop the service. The restart policy brings it back (`deploy/compose.yaml:51`) |
| Collector down | Records go into cumulative memory and leave at the next accepted export. A crash during the outage loses them, as appendix A accepts (`docs/architecture/appendix-a-trace-and-metric-catalog.md:186-190`) |

## 9. What the service reports about itself
Expand All @@ -113,7 +113,7 @@ Metrics, on the meter from `telemetry.Setup`, with no repository attribute so th

`repairs` runs a little above the true miss count: a delivery still in the queue when the run reaches its PR loses the race. The worker polls every second, so the window is small.

Logs, through the existing JSON handler (`cmd/github-metrics/main.go:67`): one info line per run with `kind`, `result`, `repos`, `pages`, `not_modified`, `recorded`, `already_counted`, `truncated` and `duration`; one warn line per skipped or truncated repository with its numeric repository ID and the status, never its name; and one error line on `auth_failed`, alongside the token source's own line. No line carries a token, a body, a title or a PR number.
The existing JSON handler (`cmd/github-metrics/main.go:67`) writes one summary per run with `kind`, `result`, `repos`, `pages`, `not_modified`, `recorded`, `already_counted`, `truncated` and `duration`. A run that returns an error logs its summary at error level and omits the error text. Other run summaries log at info level. Each skipped or truncated repository gets a warning with its numeric repository ID and status. An `auth_failed` result gets an error line alongside the token source's own line. No line carries a repository name, a token, a body, a title or a PR number.

## 10. Pull request split

Expand Down
46 changes: 46 additions & 0 deletions internal/reconcile/events_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
package reconcile_test

import (
"encoding/json"
"errors"
"io"
"net/http"
"slices"
"strings"
Expand Down Expand Up @@ -110,3 +113,46 @@ func TestFirstEndKeepsBasePath(t *testing.T) {
t.Errorf("got = %+v, err = %v, requests = %v", got, err, fake.requests)
}
}

func TestFirstEndReadFailure(t *testing.T) {
t.Parallel()

const secondPage = eventsPath + "&page=2"

for _, test := range []struct {
name string
pages int
interrupted bool
}{
{name: "decode", pages: 2, interrupted: false},
{name: "transport", pages: 1, interrupted: true},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()

fake := newRig(t, func(resp http.ResponseWriter, req *http.Request, host string) {
if req.URL.RequestURI() == eventsPath {
resp.Header().Set("Link", "<"+host+secondPage+`>; rel="next"`)
write(t, resp, "["+event(closedEvent, "2026-01-02T01:00:00Z")+"]")

return
}

if test.interrupted {
resp.Header().Set("Content-Length", "10")
}

write(t, resp, "[")
})

got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7)
_, decodeErr := errors.AsType[*json.SyntaxError](err)

if decodeErr == test.interrupted || errors.Is(err, io.ErrUnexpectedEOF) != test.interrupted ||
!got.At.IsZero() || got.State != "" || got.Pages != test.pages ||
!slices.Equal(fake.requests, []string{eventsPath, secondPage}) {
t.Errorf("got = %+v, err = %v, requests = %v", got, err, fake.requests)
}
})
}
}
34 changes: 30 additions & 4 deletions internal/reconcile/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package reconcile_test

import (
"context"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -145,10 +146,17 @@ func TestUpdatedUncleanWalkClearsTag(t *testing.T) {
name string
maxPages int32
failPage int32
status int
pages int
truncated bool
}{
{name: "truncated at the cap", maxPages: 3, failPage: 0, truncated: true},
{name: "error mid-walk", maxPages: 50, failPage: 2, truncated: false},
{name: "truncated at the cap", maxPages: 3, failPage: 0, status: 0, pages: 3, truncated: true},
{
name: "error mid-walk", maxPages: 50, failPage: 2,
status: http.StatusInternalServerError, pages: 1, truncated: false,
},
{name: "decode failure", maxPages: 50, failPage: 2, status: http.StatusOK, pages: 2, truncated: false},
{name: "budget gave up", maxPages: 50, failPage: 2, status: http.StatusForbidden, pages: 1, truncated: false},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
Expand All @@ -158,7 +166,7 @@ func TestUpdatedUncleanWalkClearsTag(t *testing.T) {
fake := newRig(t, func(resp http.ResponseWriter, _ *http.Request, host string) {
page := served.Add(1)
if page == test.failPage {
resp.WriteHeader(http.StatusInternalServerError)
failPullPage(t, resp, test.status)

return
}
Expand All @@ -169,7 +177,8 @@ func TestUpdatedUncleanWalkClearsTag(t *testing.T) {
})

got, err := fake.lister.Updated(t.Context(), "o/r", opts(int(test.maxPages)))
if (err != nil) == test.truncated || got.Truncated != test.truncated || !got.Newest.IsZero() {
if (err != nil) == test.truncated || got.Truncated != test.truncated || !got.Newest.IsZero() ||
got.Pages != test.pages || (test.status == http.StatusForbidden && !errors.Is(err, ghclient.ErrGaveUp)) {
t.Fatalf("got = %+v, err = %v", got, err)
}

Expand All @@ -180,6 +189,23 @@ func TestUpdatedUncleanWalkClearsTag(t *testing.T) {
}
}

func failPullPage(t *testing.T, resp http.ResponseWriter, status int) {
t.Helper()

if status == http.StatusOK {
write(t, resp, "[")

return
}

if status == http.StatusForbidden {
resp.Header().Set("X-Ratelimit-Resource", "search")
resp.Header().Set("X-Ratelimit-Remaining", "0")
}

resp.WriteHeader(status)
}

func TestUpdatedFirstPageTagOnly(t *testing.T) {
t.Parallel()

Expand Down
46 changes: 34 additions & 12 deletions internal/reconcile/loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ const (
incremental = "incremental"
metricPrefix = "github_metrics.reconcile."
seconds = "s"

maxConsecutivePassErrors = 3
)

// Pass runs one reconciliation. A store error stops the scheduler.
// Pass runs one reconciliation and returns any store error.
type Pass func(ctx context.Context) (RunResult, error)

// LoopClock supplies pass times and a ticker with a stop function.
Expand Down Expand Up @@ -75,8 +77,8 @@ func NewLoop(pass Pass, meter metric.Meter, log *slog.Logger, clock LoopClock) (
return &loop, nil
}

// Start runs passes serially until cancellation or a store error. Call it once
// from the goroutine that owns the loop.
// Start runs passes serially until cancellation or three consecutive pass
// errors. Call it once from the goroutine that owns the loop.
func (l *Loop) Start(ctx context.Context) error {
if ctx.Err() != nil {
return nil
Expand All @@ -85,20 +87,38 @@ func (l *Loop) Start(ctx context.Context) error {
ticks, stop := l.clock.NewTicker(passInterval)
defer stop()

finished, err := l.runPass(ctx)
for err == nil && ctx.Err() == nil {
consecutiveErrors := 0

for {
finished, err := l.runPass(ctx)
if err != nil {
consecutiveErrors++
} else {
consecutiveErrors = 0
}

if consecutiveErrors == maxConsecutivePassErrors || ctx.Err() != nil {
return err
}

if !waitForNextPass(ctx, ticks, finished) {
return nil
}
}
}

func waitForNextPass(ctx context.Context, ticks <-chan time.Time, finished time.Time) bool {
for {
select {
case <-ctx.Done():
return nil
return false
case tick := <-ticks:
// The ticker may still hold a tick from the previous pass.
if tick.After(finished) && ctx.Err() == nil {
finished, err = l.runPass(ctx)
if tick.After(finished) {
return ctx.Err() == nil
}
}
}

return err
}

func (l *Loop) runPass(ctx context.Context) (time.Time, error) {
Expand All @@ -110,9 +130,11 @@ func (l *Loop) runPass(ctx context.Context) (time.Time, error) {

finished := l.clock.Now()
elapsed := finished.Sub(started)
level := slog.LevelInfo

if err != nil {
result.Result = RunPartial
level = slog.LevelError
}

kind := attribute.String("kind", incremental)
Expand All @@ -128,8 +150,8 @@ func (l *Loop) runPass(ctx context.Context) (time.Time, error) {
l.lastSuccess.Record(ctx, finished.Unix(), kindOnly)
}

l.log.InfoContext(
ctx, "reconcile pass finished",
l.log.LogAttrs(
ctx, level, "reconcile pass finished",
slog.String("kind", incremental), slog.String("result", string(result.Result)),
slog.Int("repos", result.Repositories), slog.Int("pages", result.Pages),
slog.Int("not_modified", result.NotModified), slog.Int("recorded", result.Recorded),
Expand Down
63 changes: 54 additions & 9 deletions internal/reconcile/loop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,15 @@ func TestLoopReportsPasses(t *testing.T) {

var logs bytes.Buffer

const firstFailure = 3

statuses := []reconcile.RunStatus{
reconcile.RunOK,
reconcile.RunPartial,
reconcile.RunAuthFailed,
reconcile.RunPartial,
reconcile.RunPartial,
reconcile.RunPartial,
}
firstSuccess := time.Now().Add(2 * time.Second)
calls := 0
Expand All @@ -141,7 +145,7 @@ func TestLoopReportsPasses(t *testing.T) {
}
calls++

if calls == len(statuses) {
if calls > firstFailure {
result.Result = ""

return result, fmt.Errorf("store error with request details: %w", io.ErrClosedPipe)
Expand All @@ -161,7 +165,43 @@ func TestLoopReportsPasses(t *testing.T) {
}

checkLoopMetrics(t, reader, firstSuccess)
checkLoopLogs(t, &logs, statuses)
checkLoopLogs(t, &logs, statuses, firstFailure)
})
}

func TestLoopResetsConsecutivePassErrors(t *testing.T) {
t.Parallel()

synctest.Test(t, func(t *testing.T) {
passErrors := []error{
io.ErrClosedPipe, io.ErrClosedPipe, nil, io.ErrClosedPipe, io.ErrClosedPipe, io.ErrUnexpectedEOF,
}
calls := 0
pass := func(context.Context) (reconcile.RunResult, error) {
var result reconcile.RunResult

result.Result = reconcile.RunPartial
err := passErrors[calls]
calls++

return result, err
}

loop, err := reconcile.NewLoop(pass, noop.NewMeterProvider().Meter("test"), slog.New(slog.DiscardHandler), nil)
if err != nil {
t.Fatal(err)
}

err = loop.Start(t.Context())
if !errors.Is(err, io.ErrUnexpectedEOF) || calls != len(passErrors) {
t.Fatalf(
"loop returned %v after %d passes, want %v after %d",
err,
calls,
io.ErrUnexpectedEOF,
len(passErrors),
)
}
})
}

Expand Down Expand Up @@ -217,24 +257,24 @@ func checkLoopMetrics(t *testing.T, reader *sdkmetric.ManualReader, lastSuccess

want := map[string]float64{
runs + ",result=ok": 1,
runs + ",result=partial": 2,
runs + ",result=partial": 4,
runs + ",result=auth_failed": 1,
prefix + "duration/s/" + kind: 8,
prefix + "duration/s/" + kind + "/count": 4,
prefix + "repairs//counter/" + kind + ",milestone=merged": 8,
prefix + "duration/s/" + kind: 12,
prefix + "duration/s/" + kind + "/count": 6,
prefix + "repairs//counter/" + kind + ",milestone=merged": 12,
prefix + "last_success/s/gauge/" + kind: float64(lastSuccess.Unix()),
}
if !maps.Equal(got, want) {
t.Errorf("metrics = %v, want %v", got, want)
}
}

func checkLoopLogs(t *testing.T, logs io.Reader, statuses []reconcile.RunStatus) {
func checkLoopLogs(t *testing.T, logs io.Reader, statuses []reconcile.RunStatus, firstFailure int) {
t.Helper()

decoder := json.NewDecoder(logs)

for _, status := range statuses {
for index, status := range statuses {
var got map[string]any

err := decoder.Decode(&got)
Expand All @@ -244,8 +284,13 @@ func checkLoopLogs(t *testing.T, logs io.Reader, statuses []reconcile.RunStatus)

delete(got, slog.TimeKey)

level := slog.LevelInfo
if index >= firstFailure {
level = slog.LevelError
}

want := map[string]any{
slog.LevelKey: "INFO", slog.MessageKey: "reconcile pass finished",
slog.LevelKey: level.String(), slog.MessageKey: "reconcile pass finished",
"kind": "incremental", "result": string(status),
"repos": float64(3), "pages": float64(4), "not_modified": float64(1), "recorded": float64(2),
"already_counted": float64(5), "truncated": float64(1), "duration": float64(2 * time.Second),
Expand Down
Loading
Loading