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
1 change: 1 addition & 0 deletions changelog.d/fixed-085-note-approved-head.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- The 085 "Needs a decision" note no longer asks for an owner approval the head already has when the lane stopped at an earlier gate. A fork PR parked on a fork-guard check (a `Canary` that refuses forks) never reached the review gate or the workflow fence, so nothing noted the trusted maintainer's Approve review: the note kept listing the reviewer's `requires_human` question and the workflow fence "awaiting owner approval" and asked a trusted merger to approve the head again. The stage pass now reads the head's trusted approval itself in that case (cached per head for ten minutes), drops the fence the approval released, and the same-head 085 re-park no longer re-asks the answered question; the note names only what is left (projectbluefin/utah-packages#1181, #1013).
9 changes: 8 additions & 1 deletion src/docs/hive-merge.md
Original file line number Diff line number Diff line change
Expand Up @@ -1267,7 +1267,14 @@ A PR merges through this tier only when all of the following hold:
does. When the approval is already recorded and the PR is parked for
another reason, **What to do** says there is nothing more to approve
instead of asking for it again
([Danathar/zfs-aurora-complex#254](https://github.com/Danathar/zfs-aurora-complex/pull/254)). While the
([Danathar/zfs-aurora-complex#254](https://github.com/Danathar/zfs-aurora-complex/pull/254)). That
holds when the lane stopped at an earlier gate (a fork-guard check, a
hold) before it reached the review gate or the fence: the stage pass then
reads the head's trusted approval itself (cached per head for ten
minutes), and the 085 note lists neither the reviewer's `requires_human`
question nor the fence "awaiting owner approval" that the approval
already answered, and the same-head 085 re-park does not ask it again
([projectbluefin/utah-packages#1181](https://github.com/projectbluefin/utah-packages/pull/1181)). While the
approval is still owed and a sentinel alert is open on the same PR, **What
to do** says that **Approve** on the PR's Activity monitor row (or
`approve` through the admin MCP's `repository.item_decision`) records the
Expand Down
82 changes: 82 additions & 0 deletions src/pkg/github/automerge/automerge_stage_human.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,50 @@ type humanFenceEntry struct {
fence string
}

// humanApprovalEntry is one head's trusted approval as the human route read
// it ("" when there is none), and when it was read.
type humanApprovalEntry struct {
head string
at time.Time
login string
}

// headTrustedApproval is the trusted approval on obs's head for a route
// that would ask for one when no lane noted it this pass: an APPROVED review
// that reaches the head (on it, or carried over the hive's base merges) and,
// for a requires_human verdict, a recorded `/hive decision approve`
// (trustedHumanApprovalForRequiresHuman). It is read once per head per
// humanChecksTTL, like the head's checks: a new head is a miss, and an
// approval given on a parked head shows within the TTL.
func (c *Engine) headTrustedApproval(ctx context.Context, tracker *StageTracker, key string, obs stageObservation, verdict ContributorLaneVerdict, now time.Time) string {
if c == nil || tracker == nil || strings.TrimSpace(obs.HeadSHA) == "" {
return ""
}
tracker.mu.Lock()
entry, ok := tracker.approvals[key]
tracker.mu.Unlock()
if ok && entry.head == obs.HeadSHA && now.Sub(entry.at) < humanChecksTTL {
return entry.login
}
// Only a trusted merger's approval counts, so with none configured
// there is nothing to read (as for the sign-off election's own read).
var login string
if _, configured := c.isTrustedMerger(""); configured {
if verdictNeedsHuman(stageDetail{Verdict: verdict, VerdictKnown: true}) {
login, _ = c.trustedHumanApprovalForRequiresHuman(ctx, obs.Owner, obs.Repo, obs.Number, obs.HeadSHA, verdict)
} else {
login, _ = c.latestTrustedHumanApproval(ctx, obs.Owner, obs.Repo, obs.Number, obs.HeadSHA)
}
}
tracker.mu.Lock()
if tracker.approvals == nil {
tracker.approvals = map[string]humanApprovalEntry{}
}
tracker.approvals[key] = humanApprovalEntry{head: obs.HeadSHA, at: now, login: login}
tracker.mu.Unlock()
return login
}

// headDiffFence returns the contributor lane's merge diff fence for obs's
// head (contributorLaneMergeFence: workflow / action files as
// workflow_fence_scope scopes them, tests removed), cached per head and
Expand Down Expand Up @@ -577,9 +621,18 @@ func (c *Engine) humanEvidence(ctx context.Context, tracker *StageTracker, key s
}
}
}
if e.HumanApprover == "" && e.HumanChangeRequester == "" && (e.Verdict == stagelabels.VerdictRequiresHuman || (e.ManualMerge && e.ApprovalReleasesFence)) {
// A lane that stopped at an earlier gate (a fork-guard check, a
// hold) never reached the review gate or the workflow fence, so
// nothing noted the approval on this head: read it here rather
// than ask for one a maintainer already gave
// (projectbluefin/utah-packages#1181, #1013).
e.HumanApprover = c.headTrustedApproval(ctx, tracker, key, obs, contributorVerdict, now)
}
if humanMergePath {
applyHumanMergePathFenceRoute(&e, obs)
}
e.CauseAwaitsApproval = e.ApprovalReleasesFence && strings.HasSuffix(e.CauseReason, prstage.CauseWorkflowPathAwaitingApproval)
if strings.HasPrefix(obs.Reason, stageReasonForkGuard) {
e.ForkGuard = append([]string(nil), obs.ForkGuardChecks...)
}
Expand Down Expand Up @@ -885,10 +938,39 @@ func sameHeadDecisionRoute(obs stageObservation) stagelabels.Route {
}
v := normalizeContributorLaneVerdict(obs.Detail.Verdict)
route.Verdict = stagelabels.VerdictRequiresHuman
if approver := strings.TrimSpace(obs.Detail.HumanApprover); approver != "" && obs.HeadSHA != "" && strings.TrimSpace(obs.Detail.HumanApprovalHead) == obs.HeadSHA {
// The trusted approval on this head answered the verdict, as in
// humanEvidence: the re-park does not ask the reviewer's question again.
route.HumanApprover = approver
return route
}
route.Reasons = stagelabels.RequiresHumanReasons(obs.HeadSHA, v.DecisionFinding, v.DecisionQuestion, v.HumanSummaries)
return route
}

// sameHeadApproved reports whether a trusted approval stands on obs's head
// when the same-head 085 re-park is about to keep asking for one. A lane
// that stopped before the review gate noted none this pass, so it is read
// here (headTrustedApproval) and stamped on obs; the approval answers the
// parked question, so the PR is not re-parked on it.
func (c *Engine) sameHeadApproved(ctx context.Context, tracker *StageTracker, key string, obs *stageObservation, now time.Time) bool {
if obs == nil || obs.HeadSHA == "" {
return false
}
if strings.TrimSpace(obs.Detail.HumanApprover) != "" && strings.TrimSpace(obs.Detail.HumanApprovalHead) == obs.HeadSHA {
return true
}
if strings.TrimSpace(obs.Detail.HumanChangeRequester) != "" && strings.TrimSpace(obs.Detail.HumanChangeRequestHead) == obs.HeadSHA {
return false
}
login := c.headTrustedApproval(ctx, tracker, key, *obs, normalizeContributorLaneVerdict(obs.Detail.Verdict), now)
if login == "" {
return false
}
obs.Detail.HumanApprover, obs.Detail.HumanApprovalHead = login, obs.HeadSHA
return true
}

func (c *Engine) postHumanEntry(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, role stagelabels.Role, route stagelabels.Route) (int, error) {
rec, ok := store.Get(key)
if !ok || rec.Stage != route.Stage {
Expand Down
152 changes: 152 additions & 0 deletions src/pkg/github/automerge/automerge_stage_human_approved_head_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package automerge

import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"time"

"github.com/hivecommons/hive/pkg/config"
"github.com/hivecommons/hive/pkg/stagelabels"
)

// approvedHeadStage is projectbluefin/utah-packages#1181: a fork PR that
// edits a workflow, parked by the lane at the fork guard (`Canary` refuses
// fork PRs) before it reached the review gate or the workflow fence, with
// the swarm's requires_human verdict. reviews is what GET /pulls/9/reviews
// answers; reads counts those calls.
type approvedHeadStage struct {
e *Engine
clock *contributorLaneClock
obs stageObservation
key string
reads *int
}

func newApprovedHeadStage(t *testing.T, reviews []map[string]any) (*approvedHeadStage, func()) {
t.Helper()
api, closeAPI := seededStageAPI(t)
api.prFiles = map[int][]string{9: {".github/workflows/release.yml"}}
reads := 0
api.extra = func(w http.ResponseWriter, r *http.Request) bool {
if r.Method != http.MethodGet || r.URL.Path != "/repos/acme/widget/pulls/9/reviews" {
return false
}
reads++
_ = json.NewEncoder(w).Encode(reviews)
return true
}
clock := &contributorLaneClock{at: time.Date(2026, 11, 17, 11, 26, 0, 0, time.UTC)}
verdict := ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true, DecisionQuestion: "Is the new release step safe to run?"}
e, _ := humanStageEngine(t, api.url, clock, &verdict, 0)
e.contributorLanePolicy = func() ContributorLanePolicy {
return ContributorLanePolicy{Enabled: true, RequireTiers: map[string]bool{"trusted": true}, OwnerApprovalReleasesWorkflowFence: true, WorkflowFenceScope: config.ContributorLaneWorkflowFenceScopeAll}
}
e.SetMergerAuthorizer(func(login string) bool { return testTrustedMergers[strings.ToLower(strings.TrimSpace(login))] })
obs := stageObservation{Lane: stageLaneContributor, Display: "acme/widget", Owner: "acme", Repo: "widget", Number: 9, HeadSHA: "sha",
Reason: stageReasonForkGuard + "Canary", ForkGuardChecks: []string{"Canary"}}
return &approvedHeadStage{e: e, clock: clock, obs: obs, key: stageKey("acme", "widget", 9), reads: &reads}, closeAPI
}

func (s *approvedHeadStage) evidence(at time.Time) stagelabels.Evidence {
return s.e.humanEvidence(context.Background(), s.e.stageTrackerOrShared(), s.key, s.obs, stagelabels.CauseDecision, at)
}

// The lane noted no approval (it stopped at the fork guard), so the route
// reads it: the 085 note names only the guard and says nothing is left to
// approve. The read is cached per head for humanChecksTTL.
func TestHumanEvidenceReadsApprovalALaneStoppedBefore(t *testing.T) {
s, closeAPI := newApprovedHeadStage(t, []map[string]any{
{"id": 1, "state": "APPROVED", "commit_id": "sha", "user": map[string]any{"login": "bob"}},
})
defer closeAPI()
ev := s.evidence(s.clock.now())
if ev.HumanApprover != "bob" || !ev.CauseAwaitsApproval {
t.Fatalf("approver = %q awaits = %v, want @bob read for the head", ev.HumanApprover, ev.CauseAwaitsApproval)
}
body := stagelabels.DecisionComment(stagelabels.RouteHuman(ev))
for _, gone := range []string{"the reviewer swarm returned `requires_human`", "reviewer question", "awaiting owner approval", "a trusted merger approves this head"} {
if strings.Contains(body, gone) {
t.Fatalf("085 note still says %q:\n%s", gone, body)
}
}
for _, want := range []string{"`Canary`", "nothing more to approve: @bob approved this head"} {
if !strings.Contains(body, want) {
t.Fatalf("085 note missing %q:\n%s", want, body)
}
}

if s.evidence(s.clock.now().Add(time.Minute)); *s.reads != 1 {
t.Fatalf("review reads = %d after a second pass on the head, want 1 (cached)", *s.reads)
}
if s.evidence(s.clock.now().Add(humanChecksTTL + time.Minute)); *s.reads != 2 {
t.Fatalf("review reads = %d past the TTL, want 2", *s.reads)
}
s.obs.HeadSHA = "sha2"
if s.evidence(s.clock.now().Add(humanChecksTTL + time.Minute)); *s.reads != 3 {
t.Fatalf("review reads = %d for a new head within the TTL, want a fresh read (3)", *s.reads)
}
}

// No approval on the head: the note is today's, asking for it.
func TestHumanEvidenceWithoutApprovalStillAsks(t *testing.T) {
s, closeAPI := newApprovedHeadStage(t, nil)
defer closeAPI()
ev := s.evidence(s.clock.now())
if ev.HumanApprover != "" {
t.Fatalf("approver = %q, want none", ev.HumanApprover)
}
body := stagelabels.DecisionComment(stagelabels.RouteHuman(ev))
for _, want := range []string{"`Canary`", "the reviewer swarm returned `requires_human` @sha", "awaiting owner approval", "a trusted merger approves this head"} {
if !strings.Contains(body, want) {
t.Fatalf("085 note missing %q:\n%s", want, body)
}
}
}

// An approval a lane already noted is used as is: no extra read.
func TestHumanEvidenceUsesTheNotedApproval(t *testing.T) {
s, closeAPI := newApprovedHeadStage(t, nil)
defer closeAPI()
s.obs.Detail.HumanApprover, s.obs.Detail.HumanApprovalHead = "carol", "sha"
if ev := s.evidence(s.clock.now()); ev.HumanApprover != "carol" || *s.reads != 0 {
t.Fatalf("approver = %q reads = %d, want the noted @carol and no read", ev.HumanApprover, *s.reads)
}
}

// The same-head 085 re-park reads the approval too: an approved head is
// not re-parked on the question it answered, and the approval is stamped on
// the observation for the steps after it.
func TestSameHeadApprovedReadsTheApproval(t *testing.T) {
s, closeAPI := newApprovedHeadStage(t, []map[string]any{
{"id": 1, "state": "APPROVED", "commit_id": "sha", "user": map[string]any{"login": "bob"}},
})
defer closeAPI()
obs := s.obs
obs.Detail.VerdictKnown = true
obs.Detail.Verdict = ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true, DecisionQuestion: "Is the new release step safe to run?"}
if !s.e.sameHeadApproved(context.Background(), s.e.stageTrackerOrShared(), s.key, &obs, s.clock.now()) {
t.Fatal("sameHeadApproved = false for a head @bob approved")
}
if obs.Detail.HumanApprover != "bob" || obs.Detail.HumanApprovalHead != "sha" {
t.Fatalf("detail = %+v, want the approval stamped", obs.Detail)
}
route := sameHeadDecisionRoute(obs)
if route.HumanApprover != "bob" || len(route.Reasons) != 0 {
t.Fatalf("route = %+v, want the approver and no requires_human reasons", route)
}

none, closeNone := newApprovedHeadStage(t, nil)
defer closeNone()
plain := none.obs
plain.Detail = obs.Detail
plain.Detail.HumanApprover, plain.Detail.HumanApprovalHead = "", ""
if none.e.sameHeadApproved(context.Background(), none.e.stageTrackerOrShared(), none.key, &plain, none.clock.now()) {
t.Fatal("sameHeadApproved = true with no approval on the head")
}
if r := sameHeadDecisionRoute(plain); len(r.Reasons) == 0 || !strings.Contains(r.Reasons[0], "requires_human") {
t.Fatalf("unapproved re-park route = %+v, want the requires_human reasons", r)
}
}
11 changes: 10 additions & 1 deletion src/pkg/github/automerge/automerge_stage_labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,10 @@ type StageTracker struct {
// (automerge_human_merge_path_fence.go); created on first use. Unlike
// obs it survives drain: it is per head, not per pass.
humanMergePathFence map[string]humanMergePathFenceEntry
// approvals remembers, per key, the trusted approval the human route
// read for a head no lane noted one on (headTrustedApproval); created
// on first use. Like humanMergePathFence it survives drain.
approvals map[string]humanApprovalEntry
}

// stageOwner is the lane that set a PR's current stage, for which head, and
Expand Down Expand Up @@ -1190,6 +1194,11 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error)
var evidence stagelabels.Evidence
route, evidence = c.routeHuman(ctx, tracker, key, obs, verdict.Stage, now)
pass.Route = &evidence
if approver := evidence.HumanApprover; approver != "" && obs.HeadSHA != "" && obs.Detail.HumanApprovalHead != obs.HeadSHA {
// The route read the approval no lane noted this pass
// (headTrustedApproval): the steps below see it too.
obs.Detail.HumanApprover, obs.Detail.HumanApprovalHead = approver, obs.HeadSHA
}
verdict.Stage = route.Stage
if route.LaneReason != "" {
obs.Reason = route.LaneReason
Expand Down Expand Up @@ -1458,7 +1467,7 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error)
// Only re-park when the post-steps would leave 085: an adoption
// that cleared it, or a fresher 085 reason, must stand.
if verdict.Stage != stagelabels.NeedsDecision && !pass.AdoptionLive {
if replacement, ok := preserveNeedsDecisionOnSameHead(prevRec, hadPrev, obs, verdict); ok {
if replacement, ok := preserveNeedsDecisionOnSameHead(prevRec, hadPrev, obs, verdict); ok && !c.sameHeadApproved(ctx, tracker, key, &obs, now) {
verdict = replacement
obs.Reason = replacement.Reason
route := sameHeadDecisionRoute(obs)
Expand Down
13 changes: 11 additions & 2 deletions src/pkg/stagelabels/human.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,12 @@ type Evidence struct {
// stays true until that approval, but the 085 actions must ask for the
// approval rather than say no approval helps.
ApprovalReleasesFence bool
// CauseAwaitsApproval is true when CauseReason is that fence awaiting
// the owner's approval. Once HumanApprover is set the approval has
// released it, so the 085 note stops listing it: a lane stopped at a
// fork-guard check kept "awaiting owner approval" beside the approval
// itself (projectbluefin/utah-packages#1181).
CauseAwaitsApproval bool
// ForkGuard names the red checks that refuse the PR only because it is
// from a fork (a fork-publication or fork-secrets guard). They are not
// the author's to fix: only a maintainer can clear them, so they route
Expand Down Expand Up @@ -699,9 +705,12 @@ func routeProgress(e Evidence) Route {
// (hivecommons/hive#17327): withGates rides it on whatever stage the
// head's progress earns, and the lanes refuse the merge on the label.
manualMergeApproved := e.Cause == CauseDecision && e.ManualMergeRule && approver != "" && strings.TrimSpace(e.CauseReason) != "" && len(decide) == 0
if e.Cause == CauseDecision && strings.TrimSpace(e.CauseReason) != "" && !manualMergeApproved {
// The approval on this head released the workflow-path fence: it is no
// longer a reason, and no "will not merge unattended" stands in for it.
fenceReleased := e.CauseAwaitsApproval && !e.ManualMergeRule && approver != ""
if e.Cause == CauseDecision && strings.TrimSpace(e.CauseReason) != "" && !manualMergeApproved && !fenceReleased {
decide = append(decide, e.CauseReason)
} else if e.Cause == CauseDecision && len(e.ForkGuard) == 0 && !manualMergeApproved {
} else if e.Cause == CauseDecision && len(e.ForkGuard) == 0 && !manualMergeApproved && !fenceReleased {
decide = append(decide, decisionConsequenceReason)
}
if len(decide) > 0 {
Expand Down
Loading
Loading