From 1f41c5adddc951deae174bd68f4822dca7191c7d Mon Sep 17 00:00:00 2001 From: "tbhb.dev Agent" Date: Tue, 24 Nov 2026 04:43:13 -0500 Subject: [PATCH] feat(reconcile): add the daily sweep Generated-by: LLM effort=high;harness=codex:0.166.0;model=openai:gpt-6.2-sol;session=sha-256-64:579cfd52b6bed757;surface=exec --- internal/reconcile/events.go | 14 ++-- internal/reconcile/events_test.go | 11 +-- internal/reconcile/loop.go | 54 +++++++++--- internal/reconcile/loop_test.go | 125 ++++++++++++++++++++++++---- internal/reconcile/run.go | 34 ++++---- internal/reconcile/run_test.go | 131 ++++++++++++++++++++++++++++-- 6 files changed, 307 insertions(+), 62 deletions(-) diff --git a/internal/reconcile/events.go b/internal/reconcile/events.go index 37fa5b9..027881c 100644 --- a/internal/reconcile/events.go +++ b/internal/reconcile/events.go @@ -40,11 +40,11 @@ type issueEvent struct { Event string `json:"event"` } -// FirstEnd reads a pull request's issue events at incremental priority and -// returns the first end. Each page clears its tag first, because the client +// FirstEnd reads a pull request's issue events and returns the first end. +// Each page clears its tag first, because the client // would answer 304 with an empty body for a URL it saw before. -func (l *Lister) FirstEnd(ctx context.Context, repo string, number int) (End, error) { - events, pages, complete, err := l.events(ctx, repo, number) +func (l *Lister) FirstEnd(ctx context.Context, repo string, number int, priority budget.Priority) (End, error) { + events, pages, complete, err := l.events(ctx, repo, number, priority) end := End{At: time.Time{}, State: "", Pages: pages} if err != nil || !complete { @@ -76,7 +76,9 @@ func (l *Lister) FirstEnd(ctx context.Context, repo string, number int) (End, er // events returns the events of up to MaxEventPages pages. The bool is false // when more pages remain. -func (l *Lister) events(ctx context.Context, repo string, number int) ([]issueEvent, int, bool, error) { +func (l *Lister) events(ctx context.Context, repo string, number int, priority budget.Priority) ( + []issueEvent, int, bool, error, +) { var events []issueEvent target := "repos/" + repo + "/issues/" + strconv.Itoa(number) + "/events?per_page=100" @@ -84,7 +86,7 @@ func (l *Lister) events(ctx context.Context, repo string, number int) ([]issueEv for page := 1; ; page++ { l.clear(target) - resp, err := l.fetch(ctx, budget.Incremental, target, page) + resp, err := l.fetch(ctx, priority, target, page) if err != nil { return nil, page - 1, false, err } diff --git a/internal/reconcile/events_test.go b/internal/reconcile/events_test.go index bf8eeac..ae934c1 100644 --- a/internal/reconcile/events_test.go +++ b/internal/reconcile/events_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + "github.com/tbhb-dev/github-metrics/internal/budget" "github.com/tbhb-dev/github-metrics/internal/reconcile" ) @@ -56,7 +57,7 @@ func TestFirstEndRules(t *testing.T) { write(t, resp, "["+strings.Join(test.events, ",")+"]") }) - got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7) + got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental) if err != nil || !got.At.Equal(test.at) || got.State != test.state || got.Pages != 1 || !slices.Equal(fake.requests, []string{eventsPath}) { t.Errorf("got = %+v, err = %v, requests = %v", got, err, fake.requests) @@ -73,7 +74,7 @@ func TestFirstEndPastThreePagesIsAmbiguous(t *testing.T) { write(t, resp, "["+event(closedEvent, "2026-01-02T01:00:00Z")+"]") }) - got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7) + got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental) if err != nil || !got.At.IsZero() || got.State != "" || got.Pages != reconcile.MaxEventPages || len(fake.requests) != reconcile.MaxEventPages { t.Errorf("got = %+v, err = %v, requests = %v", got, err, fake.requests) @@ -86,7 +87,7 @@ func TestFirstEndClearsTags(t *testing.T) { fake := newRig(t, tagged(t, `"v1"`, "["+event(closedEvent, "2026-01-02T01:00:00Z")+"]")) for range 2 { - got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7) + got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental) if err != nil || got.At.IsZero() || got.Pages != 1 { t.Fatalf("got = %+v, err = %v", got, err) } @@ -108,7 +109,7 @@ func TestFirstEndKeepsBasePath(t *testing.T) { write(t, resp, "["+event(closedEvent, "2026-01-02T01:00:00Z")+"]") }) - got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7) + got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental) if err != nil || got.At.IsZero() || !slices.Equal(fake.requests, []string{"/api/v3" + eventsPath}) { t.Errorf("got = %+v, err = %v, requests = %v", got, err, fake.requests) } @@ -145,7 +146,7 @@ func TestFirstEndReadFailure(t *testing.T) { write(t, resp, "[") }) - got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7) + got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental) _, decodeErr := errors.AsType[*json.SyntaxError](err) if decodeErr == test.interrupted || errors.Is(err, io.ErrUnexpectedEOF) != test.interrupted || diff --git a/internal/reconcile/loop.go b/internal/reconcile/loop.go index ad7ad2d..d9d7eed 100644 --- a/internal/reconcile/loop.go +++ b/internal/reconcile/loop.go @@ -16,7 +16,12 @@ import ( const ( passInterval = 15 * time.Minute passTimeout = 14 * time.Minute + // A sweep gets 45 minutes to read the full repair window at the shared request rate. + sweepTimeout = 45 * time.Minute + sweepHour = 3 + incremental = "incremental" + sweep = "sweep" metricPrefix = "github_metrics.reconcile." seconds = "s" @@ -32,7 +37,7 @@ type LoopClock interface { NewTicker(interval time.Duration) (<-chan time.Time, func()) } -// Loop schedules and reports incremental reconciliation passes. +// Loop schedules and reports incremental passes and daily sweeps. type Loop struct { pass Pass clock LoopClock @@ -84,13 +89,26 @@ func (l *Loop) Start(ctx context.Context) error { return nil } + started := l.clock.Now() + + nextSweep := sweepTime(started) + if started.After(nextSweep) { + nextSweep = nextSweep.AddDate(0, 0, 1) + } + ticks, stop := l.clock.NewTicker(passInterval) defer stop() consecutiveErrors := 0 for { - finished, err := l.runPass(ctx) + kind := incremental + if !started.Before(nextSweep) { + kind = sweep + nextSweep = sweepTime(started).AddDate(0, 0, 1) + } + + finished, err := l.runPass(ctx, kind, started) if err != nil { consecutiveErrors++ } else { @@ -104,9 +122,17 @@ func (l *Loop) Start(ctx context.Context) error { if !waitForNextPass(ctx, ticks, finished) { return nil } + + started = l.clock.Now() } } +func sweepTime(now time.Time) time.Time { + year, month, day := now.UTC().Date() + + return time.Date(year, month, day, sweepHour, 0, 0, 0, time.UTC) +} + func waitForNextPass(ctx context.Context, ticks <-chan time.Time, finished time.Time) bool { for { select { @@ -121,9 +147,17 @@ func waitForNextPass(ctx context.Context, ticks <-chan time.Time, finished time. } } -func (l *Loop) runPass(ctx context.Context) (time.Time, error) { - started := l.clock.Now() - passCtx, cancel := context.WithTimeout(ctx, passTimeout) +// sweepPassKey marks a sweep through the pass callback that calls Run. +type sweepPassKey struct{} + +func (l *Loop) runPass(ctx context.Context, kind string, started time.Time) (time.Time, error) { + timeout := passTimeout + if kind == sweep { + timeout = sweepTimeout + ctx = context.WithValue(ctx, sweepPassKey{}, true) + } + + passCtx, cancel := context.WithTimeout(ctx, timeout) result, err := l.pass(passCtx) cancel() @@ -137,14 +171,14 @@ func (l *Loop) runPass(ctx context.Context) (time.Time, error) { level = slog.LevelError } - kind := attribute.String("kind", incremental) - kindOnly := metric.WithAttributes(kind) + kindAttr := attribute.String("kind", kind) + kindOnly := metric.WithAttributes(kindAttr) - l.runs.Add(ctx, 1, metric.WithAttributes(kind, attribute.String("result", string(result.Result)))) + l.runs.Add(ctx, 1, metric.WithAttributes(kindAttr, attribute.String("result", string(result.Result)))) l.duration.Record(ctx, elapsed.Seconds(), kindOnly) // RunResult currently counts recorded merges. First ends arrive with the issue events read. - l.repairs.Add(ctx, int64(result.Recorded), metric.WithAttributes(kind, attribute.String("milestone", "merged"))) + l.repairs.Add(ctx, int64(result.Recorded), metric.WithAttributes(kindAttr, attribute.String("milestone", "merged"))) if result.Result == RunOK { l.lastSuccess.Record(ctx, finished.Unix(), kindOnly) @@ -152,7 +186,7 @@ func (l *Loop) runPass(ctx context.Context) (time.Time, error) { l.log.LogAttrs( ctx, level, "reconcile pass finished", - slog.String("kind", incremental), slog.String("result", string(result.Result)), + slog.String("kind", kind), 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), slog.Int("already_counted", result.AlreadyCounted), slog.Int("truncated", result.Truncated), diff --git a/internal/reconcile/loop_test.go b/internal/reconcile/loop_test.go index cfe3ba1..d306c83 100644 --- a/internal/reconcile/loop_test.go +++ b/internal/reconcile/loop_test.go @@ -25,6 +25,12 @@ import ( "github.com/tbhb-dev/github-metrics/internal/reconcile" ) +const ( + incrementalKind = "incremental" + sweepKind = "sweep" + sweepStart = 3 * time.Hour +) + func TestLoopSchedule(t *testing.T) { t.Parallel() @@ -118,24 +124,32 @@ func TestLoopReportsPasses(t *testing.T) { t.Parallel() synctest.Test(t, func(t *testing.T) { + const sweepIndex = 3 + + time.Sleep(sweepStart - sweepIndex*15*time.Minute) + + started := time.Now() + due := started.Add(sweepIndex * 15 * time.Minute) reader := sdkmetric.NewManualReader() provider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)) var logs bytes.Buffer - const firstFailure = 3 + const firstFailure = sweepIndex + 1 statuses := []reconcile.RunStatus{ reconcile.RunOK, reconcile.RunPartial, reconcile.RunAuthFailed, + reconcile.RunOK, reconcile.RunPartial, reconcile.RunPartial, reconcile.RunPartial, } - firstSuccess := time.Now().Add(2 * time.Second) calls := 0 - pass := func(context.Context) (reconcile.RunResult, error) { + pass := func(ctx context.Context) (reconcile.RunResult, error) { + want := started.Add(time.Duration(calls) * 15 * time.Minute) + checkPassTime(ctx, t, want, due) time.Sleep(2 * time.Second) result := reconcile.RunResult{ @@ -164,20 +178,86 @@ func TestLoopReportsPasses(t *testing.T) { t.Fatalf("loop returned %v after %d passes", err, calls) } - checkLoopMetrics(t, reader, firstSuccess) - checkLoopLogs(t, &logs, statuses, firstFailure) + checkLoopMetrics(t, reader, started.Add(2*time.Second), due.Add(2*time.Second)) + checkLoopLogs(t, &logs, statuses, firstFailure, sweepIndex) }) } +func TestLoopFirstSweepAfterStartup(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + time.Sleep(sweepStart + 15*time.Minute) + + started := time.Now() + due := started.UTC().AddDate(0, 0, 1).Add(-15 * time.Minute) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + calls := 0 + pass := func(ctx context.Context) (reconcile.RunResult, error) { + want := started.Add(time.Duration(calls) * 15 * time.Minute) + calls++ + + checkPassTime(ctx, t, want, due) + + if !time.Now().Before(due) { + cancel() + } + + var result reconcile.RunResult + + result.Result = reconcile.RunOK + + return result, nil + } + + loop, err := reconcile.NewLoop(pass, noop.NewMeterProvider().Meter("test"), slog.New(slog.DiscardHandler), nil) + if err != nil { + t.Fatal(err) + } + + err = loop.Start(ctx) + if err != nil || !time.Now().Equal(due) || calls != 96 { + t.Fatalf("loop returned %v at %v after %d passes, want %v after 96 passes", err, time.Now(), calls, due) + } + }) +} + +func checkPassTime(ctx context.Context, t *testing.T, want, due time.Time) { + t.Helper() + + if now := time.Now(); !now.Equal(want) { + t.Errorf("pass started at %v, want %v", now, want) + } + + timeout := 14 * time.Minute + if want.Equal(due) { + timeout = 45 * time.Minute + } + + deadline, ok := ctx.Deadline() + if !ok || time.Until(deadline) != timeout { + t.Errorf("pass deadline = %v, want %v from now", deadline, timeout) + } +} + func TestLoopResetsConsecutivePassErrors(t *testing.T) { t.Parallel() synctest.Test(t, func(t *testing.T) { + time.Sleep(sweepStart - time.Hour) + + started := time.Now() + due := started.Add(time.Hour) passErrors := []error{ io.ErrClosedPipe, io.ErrClosedPipe, nil, io.ErrClosedPipe, io.ErrClosedPipe, io.ErrUnexpectedEOF, } calls := 0 - pass := func(context.Context) (reconcile.RunResult, error) { + pass := func(ctx context.Context) (reconcile.RunResult, error) { + checkPassTime(ctx, t, started.Add(time.Duration(calls)*15*time.Minute), due) + var result reconcile.RunResult result.Result = reconcile.RunPartial @@ -205,12 +285,13 @@ func TestLoopResetsConsecutivePassErrors(t *testing.T) { }) } -func checkLoopMetrics(t *testing.T, reader *sdkmetric.ManualReader, lastSuccess time.Time) { +func checkLoopMetrics(t *testing.T, reader *sdkmetric.ManualReader, incrementalSuccess, sweepSuccess time.Time) { t.Helper() const ( prefix = "github_metrics.reconcile." - kind = "kind=incremental" + kind = "kind=" + incrementalKind + swept = "kind=" + sweepKind runs = prefix + "runs//counter/" + kind ) @@ -256,20 +337,25 @@ func checkLoopMetrics(t *testing.T, reader *sdkmetric.ManualReader, lastSuccess } want := map[string]float64{ - runs + ",result=ok": 1, - runs + ",result=partial": 4, - runs + ",result=auth_failed": 1, - 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()), + runs + ",result=ok": 1, + runs + ",result=partial": 4, + runs + ",result=auth_failed": 1, + 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(incrementalSuccess.Unix()), + prefix + "runs//counter/" + swept + ",result=ok": 1, + prefix + "duration/s/" + swept: 2, + prefix + "duration/s/" + swept + "/count": 1, + prefix + "repairs//counter/" + swept + ",milestone=merged": 2, + prefix + "last_success/s/gauge/" + swept: float64(sweepSuccess.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, firstFailure int) { +func checkLoopLogs(t *testing.T, logs io.Reader, statuses []reconcile.RunStatus, firstFailure, sweepIndex int) { t.Helper() decoder := json.NewDecoder(logs) @@ -289,9 +375,14 @@ func checkLoopLogs(t *testing.T, logs io.Reader, statuses []reconcile.RunStatus, level = slog.LevelError } + kind := incrementalKind + if index == sweepIndex { + kind = sweepKind + } + want := map[string]any{ slog.LevelKey: level.String(), slog.MessageKey: "reconcile pass finished", - "kind": "incremental", "result": string(status), + "kind": kind, "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), } diff --git a/internal/reconcile/run.go b/internal/reconcile/run.go index e12e27c..d800821 100644 --- a/internal/reconcile/run.go +++ b/internal/reconcile/run.go @@ -32,7 +32,7 @@ type RepositoryLister interface { // EndReader reads the first end of a pull request from its issue events. type EndReader interface { - FirstEnd(ctx context.Context, repo string, number int) (End, error) + FirstEnd(ctx context.Context, repo string, number int, priority budget.Priority) (End, error) } // ClosedRecorder claims and records pull request milestones. @@ -74,16 +74,19 @@ type RunResult struct { EndedTooOld, EndedPreFloor, Ambiguous int } -// Run walks the installation once and repairs merge and ended counts. A -// watermark moves forward only after the whole window has been walked and its -// items processed. +// Run walks the installation once and repairs merge and ended counts. A sweep +// from Loop walks the full repair window. A watermark moves forward only when +// the walk reaches the stop time and processes every item. func Run( ctx context.Context, lister RepositoryLister, events EndReader, record ClosedRecorder, store Watermarks, clock Clock, ) (RunResult, error) { var result RunResult - floor := clock.Now().Add(-repairWindow) + opts := WalkOptions{Stop: clock.Now().Add(-repairWindow), MaxPages: DefaultMaxPages, Priority: budget.Incremental} + if ctx.Value(sweepPassKey{}) != nil { + opts.MaxPages, opts.Priority = SweepMaxPages, budget.Sweep + } repos, truncated, err := lister.Repositories(ctx) if err != nil { @@ -104,7 +107,7 @@ func Run( break } - stop, repairErr := repairRepository(ctx, lister, events, record, store, repository.FullName, floor, &result) + stop, repairErr := repairRepository(ctx, lister, events, record, store, repository.FullName, opts, &result) if repairErr != nil { result.Result = RunPartial @@ -121,20 +124,20 @@ func Run( func repairRepository( ctx context.Context, lister RepositoryLister, events EndReader, record ClosedRecorder, store Watermarks, - repo string, floor time.Time, result *RunResult, + repo string, opts WalkOptions, result *RunResult, ) (bool, error) { watermark, err := store.Watermark(repo) if err != nil { return false, fmt.Errorf("read reconcile watermark: %w", err) } - stop := floor - if overlap := watermark.Add(-watermarkOverlap); overlap.After(stop) { - stop = overlap + if opts.Priority == budget.Sweep { + lister.ClearUpdated(repo) + } else if overlap := watermark.Add(-watermarkOverlap); overlap.After(opts.Stop) { + opts.Stop = overlap } result.Repositories++ - opts := WalkOptions{Stop: stop, MaxPages: DefaultMaxPages, Priority: budget.Incremental} walked, err := lister.Updated(ctx, repo, opts) result.Pages += walked.Pages @@ -153,9 +156,9 @@ func repairRepository( result.Result = RunPartial } - // A 304 would hide items this pass couldn't finish, so clear the tag first. - read, err := recordItems(ctx, events, record, walked.Items, result) + read, err := recordItems(ctx, events, record, walked.Items, opts.Priority, result) if read != readsComplete || err != nil { + // A 304 would hide items this pass couldn't finish. lister.ClearUpdated(repo) return read == stopPass, err @@ -202,7 +205,8 @@ func handleReadError(result *RunResult, err error) readOutcome { // recordItems records each item's merge and first end. An events read failure // reports whether to skip the repository or stop the pass. func recordItems( - ctx context.Context, events EndReader, record ClosedRecorder, items []ClosedPR, result *RunResult, + ctx context.Context, events EndReader, record ClosedRecorder, items []ClosedPR, priority budget.Priority, + result *RunResult, ) (readOutcome, error) { for _, item := range items { if item.ClosedAt.IsZero() { @@ -211,7 +215,7 @@ func recordItems( continue } - end, err := events.FirstEnd(ctx, item.Repository, item.Number) + end, err := events.FirstEnd(ctx, item.Repository, item.Number, priority) result.Pages += end.Pages if err != nil { diff --git a/internal/reconcile/run_test.go b/internal/reconcile/run_test.go index dcf4da8..d1c0741 100644 --- a/internal/reconcile/run_test.go +++ b/internal/reconcile/run_test.go @@ -9,12 +9,16 @@ import ( "errors" "fmt" "io" + "log/slog" "net/http" + "net/url" "slices" "testing" "testing/synctest" "time" + "go.opentelemetry.io/otel/metric/noop" + "github.com/tbhb-dev/github-metrics/internal/budget" "github.com/tbhb-dev/github-metrics/internal/ghclient" "github.com/tbhb-dev/github-metrics/internal/reconcile" @@ -22,9 +26,10 @@ import ( ) const ( - firstRepo = "o/first" - nextRepo = "o/next" - lastRepo = "o/last" + firstRepo = "o/first" + nextRepo = "o/next" + lastRepo = "o/last" + listedRepo = "o/r" closedState = "closed" ) @@ -51,7 +56,7 @@ func ended(reconcile.ClosedPR) reconcile.End { func (fake *runFake) ClearUpdated(repo string) { fake.cleared = append(fake.cleared, repo) } -func (fake *runFake) FirstEnd(_ context.Context, repo string, number int) (reconcile.End, error) { +func (fake *runFake) FirstEnd(_ context.Context, repo string, number int, _ budget.Priority) (reconcile.End, error) { item := reconcile.ClosedPR{ CreatedAt: time.Time{}, MergedAt: time.Time{}, ClosedAt: time.Time{}, UpdatedAt: time.Time{}, NodeID: "", Body: "", Repository: repo, Number: number, Merged: false, @@ -180,6 +185,116 @@ func TestRunRepairsMerges(t *testing.T) { } } +type getFunc func(ctx context.Context, priority budget.Priority, target string) (*ghclient.Response, error) + +func (get getFunc) Get(ctx context.Context, priority budget.Priority, target string) (*ghclient.Response, error) { + return get(ctx, priority, target) +} + +func TestSweepRepairsPastTheWatermark(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + time.Sleep(sweepStart) + + now := time.Now() + missed := closedItem(now.Add(-time.Hour), true) + lister := newSweepLister(t, now.Add(-24*time.Hour), missed) + + var fake runFake + + fake.watermarks = map[string]time.Time{listedRepo: now} + fake.record = func(got recorder.ClosedPR) (recorder.Outcome, error) { + if !got.MergedAt.Equal(missed.MergedAt) || !got.EndedAt.Equal(missed.ClosedAt) { + t.Errorf("record = %+v, want the missed pull request", got) + } + + return recorder.Outcome{Merged: recorder.ResultRecorded, Ended: recorder.ResultRecorded}, nil + } + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + pass := func(ctx context.Context) (reconcile.RunResult, error) { + defer cancel() + + got, runErr := reconcile.Run(ctx, lister, lister, &fake, &fake, runClock(now)) + if runErr != nil || got.Result != reconcile.RunOK || got.Pages != 2 || got.Recorded != 1 || + got.EndedRecorded != 1 || len(fake.wrote) != 0 { + t.Errorf("result = %+v, err = %v, watermark writes = %v", got, runErr, fake.wrote) + } + + return got, nil + } + + loop, err := reconcile.NewLoop(pass, noop.NewMeterProvider().Meter("test"), slog.New(slog.DiscardHandler), nil) + if err != nil { + t.Fatal(err) + } + + err = loop.Start(ctx) + if err != nil { + t.Fatal(err) + } + }) +} + +func newSweepLister(t *testing.T, floor time.Time, missed reconcile.ClosedPR) *reconcile.Lister { + t.Helper() + + older := closedItem(floor.Add(-time.Second), true) + + pulls, err := json.Marshal([]reconcile.ClosedPR{missed, older}) + if err != nil { + t.Fatal(err) + } + + tags := ghclient.NewETags() + ready := false + get := getFunc(func(_ context.Context, priority budget.Priority, target string) (*ghclient.Response, error) { + resp := ghclient.Response{ETag: "", Next: "", Body: nil, Status: http.StatusOK} + + switch target { + case repoPage[1:]: + resp.Body = []byte(`{"repositories":[{"full_name":"` + listedRepo + `"}]}`) + case firstPage[1:]: + if ready && (priority != budget.Sweep || tags.Get(firstPage) != "") { + t.Errorf("pulls priority = %v, tag = %q, want sweep priority and no tag", priority, tags.Get(firstPage)) + } + + tags.Set(firstPage, `"first"`) + resp.Body, resp.Next = pulls, firstPage+"&page=2" + case eventsPath[1:]: + if priority != budget.Sweep { + t.Errorf("events priority = %v, want sweep priority", priority) + } + + resp.Body = []byte("[" + event(closedEvent, missed.ClosedAt.Format(time.RFC3339)) + "]") + default: + t.Fatalf("unexpected request for %s", target) + } + + return &resp, nil + }) + + var base url.URL + + base.Path = "/" + lister := reconcile.NewLister(get, tags, &base) + + // Prime the tag with a clean walk at the same floor. + _, err = lister.Updated(t.Context(), listedRepo, reconcile.WalkOptions{ + Stop: floor, MaxPages: reconcile.DefaultMaxPages, Priority: budget.Incremental, + }) + if err != nil || tags.Get(firstPage) == "" { + t.Fatalf("prime first-page tag: err = %v, tag = %q", err, tags.Get(firstPage)) + } + + ready = true + + return lister +} + type failure struct { err error result reconcile.RunStatus @@ -292,8 +407,6 @@ func TestRunStoreErrors(t *testing.T) { func TestRunRetriesWatermarkWrite(t *testing.T) { t.Parallel() - const repo = "o/r" - now := time.Date(2026, time.January, 2, 4, 0, 0, 0, time.UTC) servePulls := tagged(t, `"first"`, "["+item("open", now.Format(time.RFC3339), "", "")+"]") rig := newRig(t, func(resp http.ResponseWriter, req *http.Request, host string) { @@ -309,19 +422,19 @@ func TestRunRetriesWatermarkWrite(t *testing.T) { var fake runFake previous := now.Add(-time.Hour) - fake.watermarks = map[string]time.Time{repo: previous} + fake.watermarks = map[string]time.Time{listedRepo: previous} fake.writeErr = io.ErrClosedPipe got, err := reconcile.Run(t.Context(), rig.lister, &fake, &fake, &fake, runClock(now)) if !errors.Is(err, io.ErrClosedPipe) || got.Result != reconcile.RunPartial || - !fake.watermarks[repo].Equal(previous) || rig.etags.Get(rig.base+firstPage) != "" { + !fake.watermarks[listedRepo].Equal(previous) || rig.etags.Get(rig.base+firstPage) != "" { t.Fatalf("first pass = %+v, err = %v, watermarks = %v", got, err, fake.watermarks) } fake.writeErr = nil got, err = reconcile.Run(t.Context(), rig.lister, &fake, &fake, &fake, runClock(now)) - if err != nil || got.Result != reconcile.RunOK || got.NotModified != 0 || !fake.watermarks[repo].Equal(now) { + if err != nil || got.Result != reconcile.RunOK || got.NotModified != 0 || !fake.watermarks[listedRepo].Equal(now) { t.Errorf("retry = %+v, err = %v, watermarks = %v", got, err, fake.watermarks) } }