From ae4db0676c1e1bad663b363a4bd29d69c2452462 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Thu, 29 Oct 2026 23:40:06 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Adopt=20stuck=20contributor=20PR?= =?UTF-8?q?s=20automatically=20from=20the=20tracker's=20offer=20predicate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The engine, the tracker's takeover offer and its presence pill each kept their own adoption clock. The sweep counted the offline wait from the author's freshest heartbeat, so every reconnect or acknowledgement restarted the 15m window; a mode=queued nudge marked an offline clanker online (2h grace); the tracker offered Adopt at 072 with no clock at all. PRs by an offline clanker (conflicting, changes requested, optional check red, fork not editable) sat at 072 until a person pressed Adopt. One predicate, automerge.AutoAdoption, now drives the sweep, the offer and the adopt-at projection: a heartbeat after the nudge extends the wait by one window at most, queued nudges count as offline, the adoption log names its trigger, the row says when hive adopts, and fork-not-editable rows name their blocker. Adopt now remains the manual override. Signed-off-by: Andrew Anderson --- .../fixed-auto-adopt-offer-predicate.md | 1 + src/docs/labels-and-control-signals.md | 35 ++++ src/pkg/dashboard/stage_tracker_adoption.go | 14 +- .../dashboard/stage_tracker_adoption_test.go | 89 ++++++++- src/pkg/dashboard/stage_tracker_build.go | 6 +- src/pkg/dashboard/stage_tracker_caption.go | 5 + src/pkg/dashboard/stage_tracker_presence.go | 85 ++++---- .../dashboard/stage_tracker_presence_test.go | 15 +- src/pkg/dashboard/stage_tracker_takeover.go | 51 ++--- .../automerge/automerge_adoption_clock.go | 185 ++++++++++++++++++ .../automerge/automerge_auto_adoption_test.go | 171 ++++++++++++++++ .../automerge/automerge_contributor_adopt.go | 109 ++++------- .../automerge_contributor_adopt_test.go | 6 +- .../automerge/automerge_contributor_nudge.go | 5 +- 14 files changed, 613 insertions(+), 164 deletions(-) create mode 100644 changelog.d/fixed-auto-adopt-offer-predicate.md create mode 100644 src/pkg/github/automerge/automerge_adoption_clock.go create mode 100644 src/pkg/github/automerge/automerge_auto_adoption_test.go diff --git a/changelog.d/fixed-auto-adopt-offer-predicate.md b/changelog.d/fixed-auto-adopt-offer-predicate.md new file mode 100644 index 0000000000..93411c5bca --- /dev/null +++ b/changelog.d/fixed-auto-adopt-offer-predicate.md @@ -0,0 +1 @@ +- Adoption of a stuck contributor-clanker PR is automatic: the predicate that makes the activity monitor offer Adopt (`automerge.AutoAdoption`) is the sweep's trigger, so a PR at 072 whose author is offline past the grace (one heartbeat buys one window, `mode=queued` nudges count as offline) is adopted by hive on that sweep for conflicts, requested changes, failing required or optional checks and `fork-not-editable` forks; the row says when (`hive adopts it in 3m unless a new head lands`), names the fork blocker, and the log carries the trigger. Adopt now stays as the override. diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index 360176392a..e4ad0e9662 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -1897,6 +1897,41 @@ When a contributor-agent PR goes red the hive does not just relabel it (a human- base tip — is updated from the base when behind, or has its failed jobs re-run when current, once per (head, base tip), before the dwell escalates it to 085 (hivecommons/hive#14500). + **When hive adopts automatically.** One predicate — + `automerge.AutoAdoption` — answers both "may the activity monitor offer + Adopt / say when hive adopts" and "does this sweep adopt". Whenever the + tracker would say `hive adopts it on the next sweep`, that sweep does it; + no click is needed (owner rule, 2026-10-29 on hivecommons/hive#15565, + #15566, #15609 and #15312: PRs by an offline clanker sat at 072 with + "waiting on @author (offline 13m, 1 nudge)" until a person pressed + Adopt, while the sweep's own clock ran from a later heartbeat). The hive + adopts an `author/clanker` PR on its own when **all** of these hold: + - the PR is at 072 with work its author's clanker is not doing: a + conflict with the base, changes requested by the review swarm, a + failing check — required, or an optional one the merge gate reads + (`optional-check-failing:`), DCO / sign-off, a diff the lane + cannot read, or a fork the App cannot push to (`fork-not-editable`: + hive cannot rebase it, so re-authoring on a hive branch is the only + mover; the caption reads *fork not editable by hive*); + - the author was nudged on **this** head and the head has not moved + since — a clanker that is pushing is never adopted; a new head + restarts the nudge and the clock; + - the author is unavailable by the clock above: offline for + `adoption.after_offline` (15m) counted from the later of the first + nudge and the last heartbeat, where a heartbeat after the nudge + ("acknowledged") buys **one** window at most — a relay that + reconnects every few minutes without pushing no longer resets it; + online but silent for `contributor_grace_online` (2h); unregistered + for `adoption.after_unregistered` (15m). A `mode=queued` nudge (the + task waits server-side) counts as offline, not online; + - nothing holds it: no `hold` / `do-not-merge`, not person-authored, and + `maintainer_policy` is `adopt` (the default) or the owner answered `ask`. + The adoption log line carries `trigger=automatic:` + (`operator-forced` / `operator-requested` for the manual paths); the + tracker's 072 pill reads `… — hive adopts it in 3m unless a new head + lands` while the clock runs and `… — hive adopts it on the next sweep` + once it has. **Adopt now** stays as the override for a clock that has + not run out yet. A PR carrying `hold`, `do-not-merge` or `do-not-merge/hold` is never adopted (a human parked it; one log line, the stage stays 072). A PR whose diff trips the contributor lane's diff fences — it touches diff --git a/src/pkg/dashboard/stage_tracker_adoption.go b/src/pkg/dashboard/stage_tracker_adoption.go index 09c8e55c72..44430b8925 100644 --- a/src/pkg/dashboard/stage_tracker_adoption.go +++ b/src/pkg/dashboard/stage_tracker_adoption.go @@ -56,6 +56,11 @@ type StageTrackerAdoption struct { // the row is in its acted state ("Adopting… (queued by @x)") and no // blocker or adopt action is shown. QueuedBy string `json:"queued_by,omitempty"` + // AutoAdoptAt is when the engine's predicate (automerge.AutoAdoption) + // adopts this head on its own, while its clock runs and nothing holds + // it; AutoDue is true once it has fired (the next sweep adopts). + AutoAdoptAt *time.Time `json:"auto_adopt_at,omitempty"` + AutoDue bool `json:"auto_due,omitempty"` // Text is the plain-words pill/tooltip: "waiting on @hanthor // (maintainer, offline 26h) — adopt?". Text string `json:"text"` @@ -105,7 +110,7 @@ func (s *Server) stageTrackerMaintainerPolicy() string { // stage/072 from its stage record and the author's live presence; nil // when the row was never nudged at its current head (nothing to adopt // yet) or is already adopted. -func stageTrackerAdoption(it StageTrackerItem, rec stagelabels.Record, hasRec bool, presence func(login string) (automerge.ContributorPresence, bool), policy string, now time.Time) *StageTrackerAdoption { +func stageTrackerAdoption(it StageTrackerItem, rec stagelabels.Record, hasRec bool, presence func(login string) (automerge.ContributorPresence, bool), policy string, clock stageTrackerAdoptionClock, now time.Time) *StageTrackerAdoption { if it.Kind != "pr" || !hasRec { return nil } @@ -163,6 +168,9 @@ func stageTrackerAdoption(it StageTrackerItem, rec stagelabels.Record, hasRec bo if by == stagelabels.AdoptBlockedAuthorMaintainer && policy == config.AdoptionMaintainerPolicyAsk { out.Action = decisionActionAdopt } + } else if v := stageTrackerAutoAdoption(it, rec, hasRec, presence, clock, now); v.Running { + at := v.At + out.AutoAdoptAt, out.AutoDue = &at, v.Due } out.Text = stageTrackerAdoptionText(it.Author, *out, now) return out @@ -206,6 +214,10 @@ func stageTrackerAdoptionText(author string, a StageTrackerAdoption, now time.Ti text += " — not adopted: a maintainer approved this head; the hive merges it as-is" case a.BlockedBy != "": text += " — not adopted: " + a.BlockedBy + case a.AutoDue: + text += " — hive adopts it on the next sweep" + case a.AutoAdoptAt != nil && a.AutoAdoptAt.After(now): + text += " — hive adopts it in " + stageTrackerShortDuration(max(a.AutoAdoptAt.Sub(now), time.Minute)) + " unless a new head lands" } return text } diff --git a/src/pkg/dashboard/stage_tracker_adoption_test.go b/src/pkg/dashboard/stage_tracker_adoption_test.go index 4e3da98ec0..071036df24 100644 --- a/src/pkg/dashboard/stage_tracker_adoption_test.go +++ b/src/pkg/dashboard/stage_tracker_adoption_test.go @@ -110,25 +110,38 @@ func TestStageTrackerAdoptionNeverSaysSo(t *testing.T) { } } -// adopt (default): nothing is held, so the row only reports the wait, the -// nudges and the presence; no Adopt is offered. +// adopt (default): nothing is held, so the row reports the wait, the +// nudges, the presence and — since the engine's own predicate +// (automerge.AutoAdoption) is what the row reads — that the hive adopts +// on its next sweep; no Adopt click is asked for. func TestStageTrackerAdoptionDefaultReportsWait(t *testing.T) { now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) s, store, status := adoptionFixture(t, now, "", offlinePresence(now.Add(-3*time.Hour))) a := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524).Adoption - if a == nil || a.Due || a.BlockedBy != "" || a.Action != "" || a.Policy != "adopt" { + if a == nil || a.Due || a.BlockedBy != "" || a.Action != "" || a.Policy != "adopt" || !a.AutoDue { t.Fatalf("adoption = %+v", a) } - if a.Text != "waiting on @hanthor (offline 3h, 2 nudges)" { + if a.Text != "waiting on @hanthor (offline 3h, 2 nudges) — hive adopts it on the next sweep" { t.Fatalf("text = %q", a.Text) } - // Online author: no offline span. + // Online author: no offline span; 26h past the first nudge is past the + // 2h online grace too. s.presenceLookup = func(string) (automerge.ContributorPresence, bool) { return automerge.ContributorPresence{Registered: true, Online: true}, true } - if a = trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524).Adoption; a == nil || a.Text != "waiting on @hanthor (online, 2 nudges)" { + if a = trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524).Adoption; a == nil || a.Text != "waiting on @hanthor (online, 2 nudges) — hive adopts it on the next sweep" { t.Fatalf("online text = %+v", a) } + // Nudged 13 minutes ago, offline: the row says when the hive adopts. + store2 := stagelabels.NewStore("", func() time.Time { return now }) + key := stagelabels.Key("hivecommons/hive", 14524) + store2.Observe(key, stagelabels.ReturnedToContributor, "conflicting") + store2.MarkNudged(key, "feed", 1, false, now.Add(-13*time.Minute)) + s.stageStore = store2 + s.presenceLookup = offlinePresence(now.Add(-13 * time.Minute)) + if a = trackerItem(t, s.buildStageTracker(status, store2, now), "pr", 14524).Adoption; a == nil || a.AutoDue || a.AutoAdoptAt == nil || !a.AutoAdoptAt.Equal(now.Add(2*time.Minute)) || a.Text != "waiting on @hanthor (offline 13m, 1 nudge) — hive adopts it in 2m unless a new head lands" { + t.Fatalf("pending text = %+v", a) + } } // A stale blocked mark (head moved) and an adopted record carry nothing. @@ -402,3 +415,67 @@ func TestStageTrackerReturnedToHiveCaption(t *testing.T) { t.Errorf("no author changed the caption: %q", got) } } + +// hive#15565/#15566/#15609 and #15312: PRs by an offline clanker sat at 072 +// with "waiting on @Karibhou (offline 13m, 1 nudge)" until a person clicked +// Adopt. The row now says when the hive adopts, offers Adopt now only as an +// override, and the fork-not-editable row names its blocker. +func TestStageTrackerAutoAdoptionExampleCaptions(t *testing.T) { + now := time.Date(2026, 10, 29, 22, 45, 0, 0, time.UTC) + s := newTestServer() + store := stagelabels.NewStore("", func() time.Time { return now }) + s.stageStore = store + s.deps = &Dependencies{Config: &config.Config{}} + nudged := now.Add(-13 * time.Minute) + s.presenceLookup = func(login string) (automerge.ContributorPresence, bool) { + // One heartbeat a minute after the nudge: acknowledged, then gone. + return automerge.ContributorPresence{Registered: true, Online: false, LastSeen: nudged.Add(time.Minute)}, true + } + rows := []struct { + number int + reason string + author string + want string + }{ + {15565, "conflicting", "Karibhou", "conflicting"}, + {15566, "contributor-lane:changes-requested", "Karibhou", "changes requested"}, + {15609, "optional-check-failing:overlayfs-exec-guard", "Karibhou", "overlayfs-exec-guard"}, + {15312, "fork-not-editable", "odttlnt", "fork not editable by hive"}, + } + status := minimalPayload() + status.HiveID = "hive" + var prs []any + for _, r := range rows { + key := stagelabels.Key("hivecommons/hive", r.number) + store.Observe(key, stagelabels.ReturnedToContributor, r.reason) + store.MarkNudged(key, "feed", 1, false, nudged) + prs = append(prs, FrontendPR{PullRequest: github.PullRequest{Number: r.number, Title: "Change", Author: r.author, HeadSHA: "feed", Labels: []string{"stage/072-returned-to-contributor", "author/clanker", "role/contributor"}}}) + } + status.Repos = []FrontendRepo{{Name: "hive", Full: "hivecommons/hive", OpenPrs: prs}} + s.UpdateStatus(status) + + for _, r := range rows { + it := trackerItem(t, s.buildStageTracker(status, store, now), "pr", r.number) + wantTail := "waiting on @" + r.author + " (offline 12m, 1 nudge) — hive adopts it in 3m unless a new head lands" + if !strings.Contains(it.Caption, r.want) || !strings.HasSuffix(it.Caption, wantTail) { + t.Fatalf("#%d caption = %q, want %q … %q", r.number, it.Caption, r.want, wantTail) + } + if strings.Contains(it.Caption, "No stage recorded yet") { + t.Fatalf("#%d caption keeps the empty-stage clause: %q", r.number, it.Caption) + } + if it.Adoption == nil || it.Adoption.AutoDue || it.Adoption.AutoAdoptAt == nil || !it.Adoption.AutoAdoptAt.Equal(nudged.Add(16*time.Minute)) { + t.Fatalf("#%d adoption = %+v", r.number, it.Adoption) + } + if it.Takeover == nil || !it.Takeover.AdoptNow || it.Takeover.GraceElapsed || it.Takeover.AutoAdoptAt == nil { + t.Fatalf("#%d takeover = %+v", r.number, it.Takeover) + } + } + // Three minutes on: the sweep's clock has run out; the row says so. + later := nudged.Add(16 * time.Minute) + for _, r := range rows { + it := trackerItem(t, s.buildStageTracker(status, store, later), "pr", r.number) + if !strings.HasSuffix(it.Caption, "— hive adopts it on the next sweep") || it.Adoption == nil || !it.Adoption.AutoDue || it.Takeover == nil || !it.Takeover.GraceElapsed { + t.Fatalf("#%d at +16m: caption=%q adoption=%+v takeover=%+v", r.number, it.Caption, it.Adoption, it.Takeover) + } + } +} diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index ca56b40c4c..b4c0d11a35 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -90,7 +90,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto workers := stageTrackerWorkersFromStatus(status) isClankerOwner := stageTrackerIsClankerOwner() adoptionClock := s.stageTrackerAdoptionClock() - rerouteCandidates, adoptionEnabled, takeoverGrace := s.stageTrackerRerouteCandidates(), s.stageAdoptionEnabled(), s.takeoverGrace() + rerouteCandidates := s.stageTrackerRerouteCandidates() finish := func(it *StageTrackerItem, labels []string, stage stagelabels.Stage, rec stagelabels.Record, hasRec bool, draft bool) { // "Needs human decision" is read from the item's current labels, not // a store record that outlived them: once the park label is gone @@ -182,7 +182,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto // (hivecommons/hive#15202): that row says "not adopted" wherever it sits. personRefused := hasRec && it.Kind == "pr" && rec.AdoptionBlocked(it.Head) == stagelabels.AdoptBlockedAuthorPerson if personRefused || (stage == stagelabels.ReturnedToContributor && it.Kind == "pr" && it.AuthorKind != authorKindHuman) { - if it.Adoption = stageTrackerAdoption(*it, rec, hasRec, presence, maintainerPolicy, now); it.Adoption != nil { + if it.Adoption = stageTrackerAdoption(*it, rec, hasRec, presence, maintainerPolicy, adoptionClock, now); it.Adoption != nil { it.Caption = stageTrackerAdoptionCaption(it.Caption, it.Adoption) } } @@ -190,7 +190,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.Presence = stageTrackerPresenceFor(*it, login, stage, rec, hasRec, presence, adoptionClock, now) it.Rework = stageTrackerReworkFor(*it, login, stage, rec, hasRec, fixWork, now) } - if it.Takeover = stageTrackerTakeover(*it, rec, hasRec, presence, rerouteCandidates, adoptionEnabled, takeoverGrace, now); it.Takeover != nil { + if it.Takeover = stageTrackerTakeover(*it, rec, hasRec, presence, rerouteCandidates, adoptionClock, now); it.Takeover != nil { it.Caption = stageTrackerTakeoverCaption(it.Caption, it.Takeover) } base, approver := stagelabels.HumanApprovedReason(it.Reason) diff --git a/src/pkg/dashboard/stage_tracker_caption.go b/src/pkg/dashboard/stage_tracker_caption.go index 5407a9d673..7dee67dc3b 100644 --- a/src/pkg/dashboard/stage_tracker_caption.go +++ b/src/pkg/dashboard/stage_tracker_caption.go @@ -415,6 +415,11 @@ func humanizeStageReason(reason string) string { return "human-merge path" case stageengineprstage.AutoMergeReasonHumanMergeRequired: return "human merge" + case stageengineprstage.AutoMergeReasonForkNotEditable: + // The App cannot update a fork the author did not open to + // maintainer edits; only adoption (hive re-authoring on its own + // branch) moves it (hivecommons/hive#15312). + return "fork not editable by hive" } if rest, ok := strings.CutPrefix(lower, "contributor-lane:"); ok { return strings.ReplaceAll(strings.ReplaceAll(rest, "-", " "), "_", " ") diff --git a/src/pkg/dashboard/stage_tracker_presence.go b/src/pkg/dashboard/stage_tracker_presence.go index 322bca0aa0..232d41fd49 100644 --- a/src/pkg/dashboard/stage_tracker_presence.go +++ b/src/pkg/dashboard/stage_tracker_presence.go @@ -61,13 +61,13 @@ type StageTrackerPresence struct { } // stageTrackerAdoptionClock is the slice of governor.labels.stage the -// adopt-at projection needs, mirroring what cmd/hive hands the adoption -// engine as automerge.StageLabelPolicy. +// adopt-at projection and the takeover offer need: the same +// automerge.AdoptionClock cmd/hive hands the adoption engine, so the +// tracker's "adopt?" and the sweep's adoption are one verdict +// (automerge.AutoAdoption). type stageTrackerAdoptionClock struct { - Enabled bool - GraceOnline time.Duration - AdoptAfterOffline time.Duration - AdoptAfterUnregistered time.Duration + Enabled bool + automerge.AdoptionClock } func (s *Server) stageTrackerAdoptionClock() stageTrackerAdoptionClock { @@ -76,13 +76,37 @@ func (s *Server) stageTrackerAdoptionClock() stageTrackerAdoptionClock { stage = s.deps.Config.Governor.Labels.Stage } return stageTrackerAdoptionClock{ - Enabled: stage.Adoption.IsEnabled(), - GraceOnline: stage.EffectiveContributorGraceOnline(), - AdoptAfterOffline: stage.Adoption.EffectiveAfterOffline(), - AdoptAfterUnregistered: stage.Adoption.EffectiveAfterUnregistered(), + Enabled: s.stageAdoptionEnabled(), + AdoptionClock: automerge.AdoptionClock{ + GraceOnline: stage.EffectiveContributorGraceOnline(), + GraceOffline: stage.EffectiveContributorGraceOffline(), + AdoptAfterOffline: stage.Adoption.EffectiveAfterOffline(), + AdoptAfterUnregistered: stage.Adoption.EffectiveAfterUnregistered(), + AdoptOfflineGrace: stage.Adoption.EffectiveOfflineGrace(), + }, } } +// stageTrackerAutoAdoption is the engine's verdict for a row: whether the +// adoption clock runs on its head and when (or that) it fires. It is the +// one predicate the sweep acts on, so a row that says "adopting" is one +// the hive adopts on its next sweep without a click. +func stageTrackerAutoAdoption(it StageTrackerItem, rec stagelabels.Record, hasRec bool, presence func(string) (automerge.ContributorPresence, bool), clock stageTrackerAdoptionClock, now time.Time) automerge.AdoptionVerdict { + if !hasRec || !clock.Enabled || it.Kind != "pr" || it.AuthorKind == authorKindHuman { + return automerge.AdoptionVerdict{} + } + head := it.Head + if head == "" { + head = rec.NudgeHead + } + var p automerge.ContributorPresence + hasPresence := false + if presence != nil && it.Author != "" { + p, hasPresence = presence(it.Author) + } + return automerge.AutoAdoption(rec, head, clock.AdoptionClock, now, p, hasPresence) +} + // stageTrackerWaitingOn names the person a PR row waits on: its author at // the stages whose caption says "@author must act", and a clanker's PR the // engine has not classified yet (the row reads "PR in progress · @@ -149,10 +173,9 @@ func stageTrackerPresenceFor(it StageTrackerItem, login string, stage stagelabel } out := &StageTrackerPresence{Login: login, State: presenceStateUnknown, Kind: presenceKindHuman, Next: presenceNextWait} var p automerge.ContributorPresence + hasPresence := false if presence != nil { - if got, ok := presence(login); ok { - p = got - } + p, hasPresence = presence(login) } switch { case p.Registered && p.Online: @@ -180,46 +203,28 @@ func stageTrackerPresenceFor(it StageTrackerItem, login string, stage stagelabel } // The adoption clock runs only where adoption itself does: a nudged // clanker PR at 072 whose head has not moved since the nudge, not yet - // adopted, with nothing holding it. + // adopted, with nothing holding it — automerge.AutoAdoption, the + // sweep's own predicate. if stage != stagelabels.ReturnedToContributor || !clock.Enabled || it.AuthorKind == authorKindHuman || out.Kind != presenceKindClanker { return out } - if !hasRec || rec.NudgeCount == 0 || rec.NudgeStart().IsZero() { - return out - } head := it.Head if head == "" { head = rec.NudgeHead } - if rec.NudgeHead != "" && head != rec.NudgeHead { - return out - } - if rec.AdoptedHead != "" && (rec.Adopted(head) || rec.AdoptedInPlace()) { - return out - } - if rec.AdoptionBlocked(head) != "" { + if hasRec && rec.AdoptionBlocked(head) != "" { // Held (maintainer_policy ask / never): the adoption text says so; // the engine will not adopt on its own. return out } - nudged := rec.NudgeStart() - var at time.Time - switch out.State { - case presenceStateOnline: - // Mirrors adoptionDue: an online clanker keeps the online grace; the - // hive waits for it meanwhile. - at = nudged.Add(orDefault(clock.GraceOnline, config.DefaultContributorGraceOnline)) - case presenceStateOffline: - since := nudged - if p.LastSeen.After(since) { - since = p.LastSeen - } - at = since.Add(orDefault(clock.AdoptAfterOffline, config.DefaultAdoptAfterOffline)) - out.Next = presenceNextAdopt - default: - at = nudged.Add(orDefault(clock.AdoptAfterUnregistered, config.DefaultAdoptAfterUnregistered)) + v := automerge.AutoAdoption(rec, head, clock.AdoptionClock, now, p, hasPresence) + if !v.Running { + return out + } + if v.Reason != automerge.AdoptReasonGrace || out.State != presenceStateOnline { out.Next = presenceNextAdopt } + at := v.At out.AdoptAt = &at return out } diff --git a/src/pkg/dashboard/stage_tracker_presence_test.go b/src/pkg/dashboard/stage_tracker_presence_test.go index 83a27911f8..7866b24626 100644 --- a/src/pkg/dashboard/stage_tracker_presence_test.go +++ b/src/pkg/dashboard/stage_tracker_presence_test.go @@ -54,8 +54,10 @@ func TestStageTrackerPresenceOnlineWaits(t *testing.T) { } } -// Offline clanker: red square, next=adopt, adopt_at = last heartbeat (when -// later than the nudge) + after_offline — adoptionDue's offline rule. +// Offline clanker: red square, next=adopt, adopt_at per +// automerge.AutoAdoption's offline rule: a heartbeat after the nudge +// extends the wait by at most one window (nudge + after_offline), so a +// heartbeat 23h after the first nudge does not restart a 4h clock. func TestStageTrackerPresenceOfflineAdopts(t *testing.T) { now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) seen := now.Add(-3 * time.Hour) @@ -65,9 +67,16 @@ func TestStageTrackerPresenceOfflineAdopts(t *testing.T) { if p == nil || p.State != "offline" || p.Kind != "clanker" || p.Next != "adopt" { t.Fatalf("presence = %+v", p) } - if p.AdoptAt == nil || !p.AdoptAt.Equal(seen.Add(4*time.Hour)) { + nudged := now.Add(-26 * time.Hour) + if p.AdoptAt == nil || !p.AdoptAt.Equal(nudged.Add(8*time.Hour)) { + t.Fatalf("adopt_at = %v, want nudge+4h (one-window cap)+4h", p.AdoptAt) + } + // A heartbeat inside the first window counts from the heartbeat. + s.presenceLookup = offlinePresence(nudged.Add(time.Hour)) + if p = presenceOf(t, s, store, status, now, 14524); p.AdoptAt == nil || !p.AdoptAt.Equal(nudged.Add(5*time.Hour)) { t.Fatalf("adopt_at = %v, want last_seen+4h", p.AdoptAt) } + s.presenceLookup = offlinePresence(seen) // A heartbeat older than the first nudge: the clock counts from the nudge. s.presenceLookup = offlinePresence(now.Add(-40 * time.Hour)) if p = presenceOf(t, s, store, status, now, 14524); p.AdoptAt == nil || !p.AdoptAt.Equal(now.Add(-26*time.Hour).Add(4*time.Hour)) { diff --git a/src/pkg/dashboard/stage_tracker_takeover.go b/src/pkg/dashboard/stage_tracker_takeover.go index 79d2c6cf28..0f93f37d8a 100644 --- a/src/pkg/dashboard/stage_tracker_takeover.go +++ b/src/pkg/dashboard/stage_tracker_takeover.go @@ -1,7 +1,6 @@ package dashboard import ( - "github.com/hivecommons/hive/pkg/config" "slices" "strings" "time" @@ -39,10 +38,14 @@ type StageTrackerTakeover struct { // FallbackAt is when a reroute's pickup window lapsed and the hive fell // back to Adopt now. FallbackAt *time.Time `json:"fallback_at,omitempty"` - // GraceElapsed is true once the author's offline grace has run out - // (adoption is due but something holds it): the delegated "Let hive - // decide" picks Adopt now then. + // GraceElapsed is true once the engine's own predicate + // (automerge.AutoAdoption) says adoption is due at this head: the hive + // adopts on its next sweep without a click, and the delegated "Let hive + // decide" picks Adopt now. It is also true when adoption is due but + // held (maintainer_policy ask / never, a person's admission). GraceElapsed bool `json:"grace_elapsed,omitempty"` + // AutoAdoptAt is when the same predicate fires, while its clock runs. + AutoAdoptAt *time.Time `json:"auto_adopt_at,omitempty"` } // StageTrackerRerouted is a pending reroute on the row. @@ -92,7 +95,8 @@ func (s *Server) stageTrackerRerouteCandidates() func(author string) []RerouteCa // stageTrackerTakeover builds the `takeover` field for a clanker PR row at // 072 / 071; nil for other rows and for an adopted head. -func stageTrackerTakeover(it StageTrackerItem, rec stagelabels.Record, hasRec bool, presence func(string) (automerge.ContributorPresence, bool), candidates func(string) []RerouteCandidate, adoptionEnabled bool, grace takeoverGrace, now time.Time) *StageTrackerTakeover { +func stageTrackerTakeover(it StageTrackerItem, rec stagelabels.Record, hasRec bool, presence func(string) (automerge.ContributorPresence, bool), candidates func(string) []RerouteCandidate, clock stageTrackerAdoptionClock, now time.Time) *StageTrackerTakeover { + adoptionEnabled := clock.Enabled if it.Kind != "pr" || it.AuthorKind == authorKindHuman || (it.Stage != trackerNumberReturned && it.Stage != trackerNumberNeedsAuthor) { return nil } @@ -169,41 +173,16 @@ func stageTrackerTakeover(it StageTrackerItem, rec stagelabels.Record, hasRec bo t := rec.RerouteFallbackAt out.FallbackAt = &t } - out.GraceElapsed = rec.AdoptionBlocked(it.Head) != "" || (it.Adoption != nil && it.Adoption.Due) || grace.elapsed(it.Adoption, now) + v := stageTrackerAutoAdoption(it, rec, hasRec, presence, clock, now) + if v.Running { + at := v.At + out.AutoAdoptAt = &at + } + out.GraceElapsed = rec.AdoptionBlocked(it.Head) != "" || (it.Adoption != nil && it.Adoption.Due) || v.Due } return out } -// takeoverGrace is the configured nudge grace (online / offline) the -// tracker measures the wait against; zero values mean "unknown". -type takeoverGrace struct { - Online, Offline time.Duration -} - -func (s *Server) takeoverGrace() takeoverGrace { - if s == nil || s.deps == nil || s.deps.Config == nil { - return takeoverGrace{Online: config.DefaultContributorGraceOnline, Offline: config.DefaultContributorGraceOffline} - } - stage := s.deps.Config.Governor.Labels.Stage - return takeoverGrace{Online: stage.EffectiveContributorGraceOnline(), Offline: stage.EffectiveContributorGraceOffline()} -} - -// elapsed: the nudge grace that applies to the author's presence has run -// out since the first nudge at this head. -func (g takeoverGrace) elapsed(a *StageTrackerAdoption, now time.Time) bool { - if a == nil || a.Since == nil || a.Since.IsZero() { - return false - } - window := g.Offline - if a.AuthorOnline { - window = g.Online - } - if window <= 0 { - return false - } - return now.Sub(*a.Since) >= window -} - // takeoverDecisionOptions are the popover options the takeover adds to a // waiting-on-contributor decision: Adopt now (lead) and Reroute. func takeoverDecisionOptions(t *StageTrackerTakeover, held bool) []StageTrackerDecisionOption { diff --git a/src/pkg/github/automerge/automerge_adoption_clock.go b/src/pkg/github/automerge/automerge_adoption_clock.go new file mode 100644 index 0000000000..b40aa98686 --- /dev/null +++ b/src/pkg/github/automerge/automerge_adoption_clock.go @@ -0,0 +1,185 @@ +package automerge + +import ( + "time" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// One predicate for "hive adopts this PR" (hivecommons/hive#15565, +// #15566, #15609, #15312: PRs by an offline contributor clanker sat at +// 072 — conflicting, changes requested, an optional check red, a fork the +// App cannot update — while the tracker offered Adopt now and the operator +// had to click it). The sweep and the tracker used to keep separate +// clocks: the engine measured the offline wait from the author's freshest +// heartbeat (which a reconnect or a task completion moves, so the window +// restarted every time the clanker flapped), the tracker measured the +// nudge grace from the first nudge, and the presence pill projected a +// third variant. They are one function now, AutoAdoption: when it says the +// adoption is due the sweep performs it on that cycle, attributed to the +// hive with the trigger; the tracker's "adopt?" / grace-elapsed offer and +// its adopt-at projection are the same verdict. The operator's Adopt now +// stays as the manual override for a row the predicate has not reached. + +// AdoptionClock is the timing slice of StageLabelPolicy the predicate +// needs; the dashboard builds one from governor.labels.stage so the two +// sides cannot drift. +type AdoptionClock struct { + // GraceOnline / GraceOffline are the nudge graces when no live presence + // source exists (and GraceOnline is the online wait with one). + GraceOnline time.Duration + GraceOffline time.Duration + // AdoptAfterOffline / AdoptAfterUnregistered are the waits with live + // presence for a registered-but-offline relay and for an author with no + // profile on this hive. + AdoptAfterOffline time.Duration + AdoptAfterUnregistered time.Duration + // AdoptOfflineGrace is the retry wait after an adoption attempt that + // opened nothing (hivecommons/hive#15307). + AdoptOfflineGrace time.Duration +} + +// Defaults applied where the clock is zero (mirroring pkg/config). +const ( + defaultGraceOnline = 2 * time.Hour + defaultGraceOffline = 15 * time.Minute + defaultAdoptAfterOffline = 15 * time.Minute + defaultAdoptAfterUnregistered = 15 * time.Minute + defaultAdoptOfflineGrace = 30 * time.Minute +) + +func (c AdoptionClock) graceOnline() time.Duration { + return durationOr(c.GraceOnline, defaultGraceOnline) +} + +func (c AdoptionClock) graceOffline() time.Duration { + return durationOr(c.GraceOffline, defaultGraceOffline) +} + +func (c AdoptionClock) afterOffline() time.Duration { + return durationOr(c.AdoptAfterOffline, defaultAdoptAfterOffline) +} + +func (c AdoptionClock) afterUnregistered() time.Duration { + return durationOr(c.AdoptAfterUnregistered, defaultAdoptAfterUnregistered) +} + +func (c AdoptionClock) offlineGrace() time.Duration { + return durationOr(c.AdoptOfflineGrace, defaultAdoptOfflineGrace) +} + +func durationOr(d, def time.Duration) time.Duration { + if d > 0 { + return d + } + return def +} + +// AdoptionClock is the policy's timing slice. +func (p StageLabelPolicy) AdoptionClock() AdoptionClock { + return AdoptionClock{ + GraceOnline: p.GraceOnline, + GraceOffline: p.GraceOffline, + AdoptAfterOffline: p.AdoptAfterOffline, + AdoptAfterUnregistered: p.AdoptAfterUnregistered, + AdoptOfflineGrace: p.AdoptOfflineGrace, + } +} + +// AdoptionVerdict is what AutoAdoption decided for a head. +type AdoptionVerdict struct { + // Running is true when the adoption clock is running on this head: a + // nudged clanker PR whose head has not moved since the nudge and that + // is not already adopted (or whose recorded attempt opened nothing and + // is retried). At is zero when it is not. + Running bool + // Due is true when hive adopts on this sweep. + Due bool + // Reason is the AdoptReason* that fires (or will fire at At). + Reason string + // At is when the verdict turns due. + At time.Time +} + +// AutoAdoption is the one predicate behind automatic adoption, the +// tracker's Adopt offer and its adopt-at projection. The clock runs once +// the author was nudged at head (a new head restarts it: a clanker that is +// pushing keeps its PR). Then: +// +// - a registered relay that is online keeps the online grace from the +// first nudge (its hive may be mid-fix); +// - a registered relay that is offline is adopted after AdoptAfterOffline. +// A heartbeat after the nudge — a reconnect, a queued task completing, +// an acknowledgement — extends the wait by at most one window: the +// clock counts from min(last heartbeat, nudge+wait), never from every +// fresh heartbeat (that is how #15566 slid for an hour); +// - an author with no profile here is adopted after AdoptAfterUnregistered; +// - without a presence source the nudge-time grace applies. +// +// An adoption already recorded for the head that opened nothing is retried +// under AdoptOfflineGrace from the attempt, with the same one-window +// heartbeat cap, while the clanker stays offline or unregistered. +func AutoAdoption(rec stagelabels.Record, head string, clock AdoptionClock, now time.Time, presence ContributorPresence, hasPresence bool) AdoptionVerdict { + start := rec.NudgeStart() + if head == "" || rec.NudgeHead != head || rec.NudgeCount == 0 || start.IsZero() { + return AdoptionVerdict{} + } + if rec.Adopted(head) || rec.AdoptedInPlace() { + return adoptionRetryVerdict(rec, head, clock, now, presence, hasPresence) + } + var v AdoptionVerdict + switch { + case !hasPresence: + grace := clock.graceOffline() + if rec.NudgeOnline { + grace = clock.graceOnline() + } + v = AdoptionVerdict{Running: true, Reason: AdoptReasonGrace, At: start.Add(grace)} + case presence.Registered && presence.Online: + v = AdoptionVerdict{Running: true, Reason: AdoptReasonGrace, At: start.Add(clock.graceOnline())} + case presence.Registered: + wait := clock.afterOffline() + v = AdoptionVerdict{Running: true, Reason: AdoptReasonOffline, At: cappedSince(start, presence.LastSeen, wait).Add(wait)} + default: + v = AdoptionVerdict{Running: true, Reason: AdoptReasonUnregistered, At: start.Add(clock.afterUnregistered())} + } + v.Due = !now.Before(v.At) + return v +} + +// cappedSince is where an offline wait counts from: the later of start +// and the last heartbeat, but a heartbeat buys at most one window past +// start. +func cappedSince(start, lastSeen time.Time, wait time.Duration) time.Time { + if !lastSeen.After(start) { + return start + } + if cap := start.Add(wait); lastSeen.After(cap) { + return cap + } + return lastSeen +} + +// adoptionRetryVerdict is AutoAdoption for a head whose recorded adoption +// attempt opened nothing (hivecommons/hive#15307): the supersede's replay +// conflicted and the attempt was recorded, so the plain clock never fired +// again while the PR sat at 072/085. With the clanker offline or +// unregistered the head is admitted again after AdoptOfflineGrace; an +// online clanker keeps the PR. A live adoption (a copy open, the branch +// held in place) is never re-admitted here. +func adoptionRetryVerdict(rec stagelabels.Record, head string, clock AdoptionClock, now time.Time, presence ContributorPresence, hasPresence bool) AdoptionVerdict { + if !rec.AdoptionAttemptedNothingOpened(head) || rec.AdoptedAt.IsZero() { + return AdoptionVerdict{} + } + if hasPresence && presence.Registered && presence.Online { + return AdoptionVerdict{} + } + wait := clock.offlineGrace() + since := rec.AdoptedAt + if hasPresence { + since = cappedSince(since, presence.LastSeen, wait) + } + v := AdoptionVerdict{Running: true, Reason: adoptionRetryReason(presence, hasPresence), At: since.Add(wait)} + v.Due = !now.Before(v.At) + return v +} diff --git a/src/pkg/github/automerge/automerge_auto_adoption_test.go b/src/pkg/github/automerge/automerge_auto_adoption_test.go new file mode 100644 index 0000000000..c0fa3df62a --- /dev/null +++ b/src/pkg/github/automerge/automerge_auto_adoption_test.go @@ -0,0 +1,171 @@ +package automerge + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// The trigger matrix behind automatic adoption (hivecommons/hive#15565, +// #15566, #15609, #15312: PRs by an offline clanker sat at 072 — +// conflicting, changes requested, an optional check red, a fork hive +// cannot update — until the operator clicked Adopt now). Every 072 reason +// the nudge fires for × the author's presence × whether a new head landed, +// asserting adopt vs wait through the real sweep (ApplyStageLabels), with +// the default 15m offline wait. +func TestAutoAdoptionTriggerMatrix(t *testing.T) { + // optionalRed is the lane snapshot for an optional check red on the + // head: the engine derives optional-check-failing: from the check + // digest, not from the recorded lane reason. + const optionalRed = "optional-check-failing:overlayfs-exec-guard" + reasons := []string{ + "conflicting", + contributorLaneReasonChangesRequested, + optionalRed, + "required-check-failing:changelog-fragment-guard", + autoMergeReasonForkNotEditable, + } + type presenceCase struct { + name string + // presence is the author's live presence read after the nudge; + // lastSeenAfterNudge is the heartbeat offset (0 = none). + online bool + lastSeenAfterNudge time.Duration + // adoptAt16m / adoptAt31m: adopted when the sweep runs 16m / 31m + // after the nudge with the same head. + adoptAt16m, adoptAt31m bool + } + presences := []presenceCase{ + // Online clanker: the 2h online grace holds (it may be mid-fix). + {name: "online", online: true}, + // Offline since the nudge: adopted once the 15m wait is out. + {name: "offline", adoptAt16m: true, adoptAt31m: true}, + // Acknowledged — a heartbeat (reconnect, queued task completing) 5m + // after the nudge — buys one window, not a sliding one: not yet at + // 16m, adopted by 31m. + {name: "acknowledged", lastSeenAfterNudge: 5 * time.Minute, adoptAt31m: true}, + } + for _, reason := range reasons { + for _, pc := range presences { + for _, headMoved := range []bool{false, true} { + name := reason + "/" + pc.name + if headMoved { + name += "/head-moved" + } + t.Run(name, func(t *testing.T) { + policy := adoptPolicy() + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "queued"}, policy) + defer done() + start := h.clock.at + h.sink.presence = &ContributorPresence{Registered: true, Online: pc.online} + laneReason := reason + if reason == optionalRed { + laneReason = "queued" + h.e.noteStageRedChecks("acme", "widget", 7, "aaa", []string{"overlayfs-exec-guard"}) + } + h.observe(adoptPR(7, "aaa"), laneReason) + if len(nudgeComments(h.api)) != 1 { + t.Fatalf("no nudge for %q: %v", reason, h.api.comments) + } + labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + p := ContributorPresence{Registered: true, Online: pc.online} + if pc.lastSeenAfterNudge > 0 { + p.LastSeen = start.Add(pc.lastSeenAfterNudge) + } + h.sink.presence = &p + head := "aaa" + if headMoved { + // The clanker pushed: the hive never adopts a PR + // whose author is pushing; the clock restarts. + head = "bbb" + } + for _, step := range []struct { + at time.Duration + adopt bool + }{{16 * time.Minute, pc.adoptAt16m}, {31 * time.Minute, pc.adoptAt31m}} { + h.api.reset() + h.clock.at = start.Add(step.at) + if reason == optionalRed { + // The lane re-reports the red optional check on + // every sweep; the note is consumed by each pass. + h.e.noteStageRedChecks("acme", "widget", 7, head, []string{"overlayfs-exec-guard"}) + } + h.observe(adoptPR(7, head, labels...), laneReason) + want := step.adopt + if headMoved { + // The new head is nudged afresh on the 16m sweep; + // 15m later it is adopted unless the clanker is + // online. + want = step.at > 16*time.Minute && !pc.online + } + got := len(h.adopt.pulls) > 0 || len(adoptionComments(h.api)) > 0 + if got != want { + t.Fatalf("at +%v adopted=%v want %v (pulls=%d comments=%v)", step.at, got, want, len(h.adopt.pulls), h.api.comments) + } + if got { + if c := adoptionComments(h.api); len(c) != 1 || !strings.Contains(c[0], "reason="+AdoptReasonOffline) { + t.Fatalf("adoption note: %v", c) + } + break + } + } + }) + } + } + } +} + +// Regression for the three example rows (hive's spoke, 2026-10-29): each +// nudged once at its head, author registered and offline 13m, with a +// heartbeat (acknowledgement) just after the nudge. Under the old clock +// the heartbeat restarted the 15m wait and the operator had to click; the +// one predicate says adoption is due 15m after the nudge-capped heartbeat. +func TestAutoAdoptionExampleRows(t *testing.T) { + now := time.Date(2026, 10, 29, 22, 48, 0, 0, time.UTC) + nudged := now.Add(-13 * time.Minute) + clock := StageLabelPolicy{}.AdoptionClock() + for _, tc := range []struct { + pr int + head string + }{{15565, "1f5a879f"}, {15566, "7336cd99"}, {15609, "4cd8b23c"}} { + rec := stagelabels.Record{NudgeHead: tc.head, NudgeCount: 1, FirstNudgeAt: nudged, LastNudgeAt: nudged} + // The clanker pinged once right after the nudge, then went quiet. + p := ContributorPresence{Registered: true, LastSeen: nudged.Add(time.Minute)} + v := AutoAdoption(rec, tc.head, clock, now, p, true) + if !v.Running || v.Due || v.Reason != AdoptReasonOffline || !v.At.Equal(nudged.Add(16*time.Minute)) { + t.Fatalf("#%d at 13m: %+v", tc.pr, v) + } + if v = AutoAdoption(rec, tc.head, clock, now.Add(3*time.Minute), p, true); !v.Due { + t.Fatalf("#%d not due at 16m: %+v", tc.pr, v) + } + // A heartbeat long after the nudge cannot push the wait past one + // window: still due at nudge+30m. + late := ContributorPresence{Registered: true, LastSeen: nudged.Add(29 * time.Minute)} + if v = AutoAdoption(rec, tc.head, clock, nudged.Add(30*time.Minute), late, true); !v.Due { + t.Fatalf("#%d: late heartbeat extended the wait: %+v", tc.pr, v) + } + // Head moved: nothing until the new head is nudged. + if v = AutoAdoption(rec, "newhead", clock, now.Add(time.Hour), p, true); v.Running || v.Due { + t.Fatalf("#%d: moved head judged: %+v", tc.pr, v) + } + } + // "queued" is a registered relay's queue, not its presence: a nudge + // answered with mode queued by an offline relay records NudgeOnline + // false, so without a presence source the offline grace applies. + store := stagelabels.NewStore("", func() time.Time { return now }) + store.Observe("hivecommons/hive#15566", stagelabels.ReturnedToContributor, "conflicting") + store.MarkNudged("hivecommons/hive#15566", "7336cd99", 1, false, nudged) + rec, _ := store.Get("hivecommons/hive#15566") + if v := AutoAdoption(rec, "7336cd99", clock, nudged.Add(15*time.Minute), ContributorPresence{}, false); !v.Due || v.Reason != AdoptReasonGrace { + t.Fatalf("no-presence offline grace: %+v", v) + } + // Trigger names on the adoption log line. + if got := adoptionTrigger(AdoptReasonOffline, "conflicting"); got != "automatic:conflicting" { + t.Fatalf("trigger %q", got) + } + if got := adoptionTrigger(AdoptReasonOperatorForced, "conflicting"); got != AdoptTriggerForced { + t.Fatalf("forced trigger %q", got) + } +} diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index 601597c1d7..ed6080c942 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -155,84 +155,21 @@ func (c *Engine) contributorPresence(ctx context.Context, login string) (Contrib return src.Presence(ctx, login), true } -// adoptionDue reports whether the PR at head has sat nudged long enough with -// no new head, and was not already adopted at this head; reason says which -// rule fired. With live presence: a registered relay that is online keeps -// the online grace (its hive may be mid-fix); a registered relay that is -// offline is adopted once it has been gone AdoptAfterOffline (counted from -// its last heartbeat or the first nudge, whichever is later); an author with -// no profile here (another hive posted the PR) is adopted after -// AdoptAfterUnregistered. Without presence the nudge-time graces apply. +// adoptionDue reports whether the PR at head is due for automatic +// adoption and which rule fired. It is AutoAdoption — the one predicate +// the tracker's Adopt offer and adopt-at projection also read +// (automerge_adoption_clock.go) — under the policy's clock. func adoptionDue(rec stagelabels.Record, head string, policy StageLabelPolicy, now time.Time, presence ContributorPresence, hasPresence bool) (bool, string) { - start := rec.NudgeStart() - if head == "" || rec.NudgeHead != head || rec.NudgeCount == 0 || start.IsZero() { + v := AutoAdoption(rec, head, policy.AdoptionClock(), now, presence, hasPresence) + if !v.Due { return false, "" } - if rec.Adopted(head) || rec.AdoptedInPlace() { - if adoptionRetryDue(rec, head, policy, now, presence, hasPresence) { - return true, adoptionRetryReason(presence, hasPresence) - } - return false, "" - } - if !hasPresence { - return now.Sub(start) >= adoptionGrace(rec, policy), AdoptReasonGrace - } - switch { - case presence.Registered && presence.Online: - grace := policy.GraceOnline - if grace <= 0 { - grace = 2 * time.Hour - } - return now.Sub(start) >= grace, AdoptReasonGrace - case presence.Registered: - wait := policy.AdoptAfterOffline - if wait <= 0 { - wait = 15 * time.Minute - } - since := start - if presence.LastSeen.After(since) { - since = presence.LastSeen - } - return now.Sub(since) >= wait, AdoptReasonOffline - default: - wait := policy.AdoptAfterUnregistered - if wait <= 0 { - wait = 15 * time.Minute - } - return now.Sub(start) >= wait, AdoptReasonUnregistered - } + return true, v.Reason } // adoptionOfflineGrace is policy.AdoptOfflineGrace with its default. func adoptionOfflineGrace(policy StageLabelPolicy) time.Duration { - if policy.AdoptOfflineGrace > 0 { - return policy.AdoptOfflineGrace - } - return 30 * time.Minute -} - -// adoptionRetryDue is the stage-stalled escape for a recorded adoption -// attempt that opened nothing (hivecommons/hive#15307: the supersede's -// replay onto the base conflicted and the attempt was recorded for the -// head, so adoptionDue never fired again while the PR sat at 072/085). -// When the author's clanker is still offline or unregistered — nobody on -// the contributor side can rebase — the head is admitted again once -// AdoptOfflineGrace has passed since the attempt or the clanker's last -// heartbeat, whichever is later. An online clanker keeps the PR: it can -// still push. An adoption that opened a copy or holds the branch in place -// is live, not stalled, and is never re-admitted here. -func adoptionRetryDue(rec stagelabels.Record, head string, policy StageLabelPolicy, now time.Time, presence ContributorPresence, hasPresence bool) bool { - if !rec.AdoptionAttemptedNothingOpened(head) || rec.AdoptedAt.IsZero() { - return false - } - if hasPresence && presence.Registered && presence.Online { - return false - } - since := rec.AdoptedAt - if hasPresence && presence.LastSeen.After(since) { - since = presence.LastSeen - } - return now.Sub(since) >= adoptionOfflineGrace(policy) + return policy.AdoptionClock().offlineGrace() } // adoptionRetryReason names why a retried adoption fired. @@ -777,7 +714,11 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor c.warn("stage labels: cannot adopt contributor PR, App login unknown", "repo", obs.Display, "pr", obs.Number) return 0, nil } - c.info("stage labels: adopting contributor PR", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "reason", reason, "registered", presence.Registered, "online", presence.Online, "lane_reason", obs.Reason, "fence", fence) + // One line per adoption naming the trigger: automatic (the + // AutoAdoption predicate fired on this sweep — the offer the tracker + // showed, performed by the hive itself), operator-forced, or an + // operator's adoption/supersede request. + c.info("stage labels: adopting contributor PR", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "reason", reason, "trigger", adoptionTrigger(reason, obs.Reason), "registered", presence.Registered, "online", presence.Online, "lane_reason", obs.Reason, "fence", fence) if policy.AdoptInPlace && canPushInPlace && !dcoRehome { store.MarkAdoptedInPlace(key, obs.HeadSHA, reason, now) @@ -798,6 +739,30 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor return c.supersedeAdoptedPR(ctx, store, key, obs, rec, policy, reason, grace, online, dcoRehome, now) } +// Adoption triggers, the `trigger` field of the adoption log line. +const ( + AdoptTriggerAutomatic = "automatic" + AdoptTriggerForced = "operator-forced" + AdoptTriggerRequested = "operator-requested" +) + +// adoptionTrigger names what fired an adoption: the operator's forced +// Adopt now, the operator's adoption/supersede request, or the automatic +// predicate — qualified by the lane reason that returned the PR to its +// author ("automatic:conflicting", "automatic:fork-not-editable"). +func adoptionTrigger(reason, laneReason string) string { + switch reason { + case AdoptReasonOperatorForced: + return AdoptTriggerForced + case AdoptReasonOperator: + return AdoptTriggerRequested + } + if laneReason = strings.TrimSpace(laneReason); laneReason != "" { + return AdoptTriggerAutomatic + ":" + laneReason + } + return AdoptTriggerAutomatic +} + // AdoptionSelfRefusedMarker stamps the note a delegated supersede of the // hive App's own PR gets: the request is consumed, nothing is re-homed. const AdoptionSelfRefusedMarker = "