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-has-open-pr-cleared-when-unlinked.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `has-open-pr` now comes off an issue once no open PR links it. The pre-dispatch open-PR guard added the label when it refused a dispatch, but nothing ever removed it, so after the linking PR merged or closed the issue kept saying "An open PR already links this issue" beside `stage/010` or `stage/045`. The issue stage-label sweep now asks the guard's own open-PR listing for every open issue wearing the label and removes it in the same write as the stage, without a comment, only when the listing succeeds and shows no linking PR. A failed listing keeps it, `scanner.skip_issues_with_open_pr: false` leaves it alone, and if another writer puts it back while still no PR links the issue, the hive leaves it there.
9 changes: 8 additions & 1 deletion src/docs/operator-reference/sweeps-and-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,14 @@ between. Two mechanisms close that gap
logged as `claim skipped: open PR already linked` with the PR number, URL
and author, and the tracker's withheld list shows *An open pull request
already links this issue (claim skipped)* with the PR as evidence
(reason `open_pr_linked`). A failed listing fails **open**: the
(reason `open_pr_linked`). The label comes off once the PR is gone: the
issue stage-label sweep asks the same listing for every open issue
wearing it and, when the listing succeeds and no open PR links the issue
any more (the PR merged or closed), removes it in the same write as the
stage, with no comment. A failed listing keeps it, and with the guard off
the sweep leaves it alone. The hive removes it once per linking PR: if it
comes back while still no PR links the issue, another writer owns it and
the hive logs that once and leaves it. A failed listing fails **open**: the
ledger-backed guards still apply, and a flaky listing must not stall every
claim. The gate also refuses an issue the confirming read says is already
**closed** (`issue closed`), so an issue closed between enumerations is
Expand Down
2 changes: 1 addition & 1 deletion src/docs/running-at-level-6.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ Config keys to cross-check: `project.issue_filter.require_labels`, `project.issu
| `user-feedback` | Dashboard/hub | Feedback provenance. | Triage reporter input; apply trust/hold policy as needed. |
| `dco` / `no-dco` (Prow's `dco-signoff: yes|no` coexist on Prow-gated repos; the hive never adds or removes them) | Hive stage pass (commit check) | Merge-eligibility display on every managed repo. Where DCO is required (detected from required/head checks or configured via `governor.labels.stage.dco.required`), `no-dco` routes by author kind: `070` (hive/self-authored), `071` (human), or `072` (clanker); the 072 nudge includes the rebase command. On ungated repos it is informational only: the lane's stage is unchanged and no DCO rebase is requested. See [DCO routing](labels-and-control-signals/stage-labels.md#dco--no-dco--the-hive-owned-sign-off-signal). | Fix commit sign-offs (`git rebase --signoff`) rather than hand-editing labels. |
| `conflicts-with-open-pr` | PR-overlap workflow | Overlap signal (the companion `<!-- hive-pr-overlap -->` comment appears only when there is a conflict or same-file overlap). | Resolve or close conflicting work before merging; same-file overlap alone may be harmless. Two open PRs that both `Fixes` one issue are resolved by the duplicate-fix sweep without a decision: the earlier green/pending PR stays, the later hive PR is closed as `duplicate-of:<keeper>`, a person's later PR is commented on and left open ([#14799](https://github.com/hivecommons/hive/issues/14799)). |
| `has-open-pr` | Pre-dispatch guard | An open PR already links the issue with a closing keyword; the hive skipped the claim. | Nothing — the label is a tracker signal, not a park; see `scanner.skip_issues_with_open_pr` in [operator-reference.md](operator-reference.md#open-pr-dispatch-guard-and-duplicate-fix-sweep-scanner). |
| `has-open-pr` | Pre-dispatch guard | An open PR already links the issue with a closing keyword; the hive skipped the claim. | Nothing — the label is a tracker signal, not a park, and the issue stage-label sweep takes it off once no open PR links the issue; see `scanner.skip_issues_with_open_pr` in [operator-reference.md](operator-reference.md#open-pr-dispatch-guard-and-duplicate-fix-sweep-scanner). |
| `no-changelog` | Dependabot/maintainer | Repo changelog exception, not a Hive safety gate. | Apply only under repo policy. |
| `human-only` remainder text (not a default label) | Agent/reviewer | Task-list sweep can park remaining issue work as `needs-human`. | Treat as a handoff; add PR `hold` if merging must stop. |

Expand Down
54 changes: 54 additions & 0 deletions src/pkg/github/issue_stage_labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,53 @@ func settleTriageClear(store *stagelabels.Store, key, repo string, number int, l
return remove, rec.TriageClearYielded || yieldNow
}

// openPRLabelClearAllowed is the once-per-issue rule for taking a stale
// `has-open-pr` off, the same shape as triageClearAllowed: already yielded
// → leave it; removed once and back now (still no linking PR) → yield and
// leave it; otherwise → remove. ResetOpenPRLabelClear starts it over when a
// linking PR is seen beside the label again.
func openPRLabelClearAllowed(rec stagelabels.Record) (remove, yieldNow bool) {
switch {
case rec.OpenPRLabelClearYielded:
return false, false
case !rec.OpenPRLabelClearedAt.IsZero():
return false, true
}
return true, false
}

// settleOpenPRLabelClear decides whether the issue sweep takes
// `has-open-pr` off an open issue, returning the label to clear ("" to
// keep it). The open-PR guard adds the label and nothing else touched it,
// so after the linking PR merged or closed the issue kept claiming an open
// PR (projectbluefin/bluefin-bling#82, projectbluefin/common#1656). It asks
// the guard's own evidence, OpenPRLinkingIssue, and removes the label only
// on a positive answer: the listing succeeded and no open PR links the
// issue. A failed listing keeps it, and with the guard off
// (scanner.skip_issues_with_open_pr: false) the label is left alone.
func (c *Client) settleOpenPRLabelClear(ctx context.Context, store *stagelabels.Store, key string, in IssueStageInput, logger *slog.Logger) string {
if store == nil || !issueHasLabel(in.Labels, HasOpenPRLabel) || !c.SkipIssuesWithOpenPR() {
return ""
}
_, linked, err := c.OpenPRLinkingIssue(ctx, in.Repo, in.Number)
if err != nil {
return ""
}
if linked {
store.ResetOpenPRLabelClear(key)
return ""
}
rec, _ := store.Get(key)
remove, yieldNow := openPRLabelClearAllowed(rec)
if yieldNow && store.MarkOpenPRLabelClearYielded(key) && logger != nil {
logger.Info("issue stage labels: "+HasOpenPRLabel+" came back after the hive removed it and no open PR links the issue; leaving it on this issue", "repo", in.Repo, "issue", in.Number, "label", HasOpenPRLabel)
}
if !remove {
return ""
}
return HasOpenPRLabel
}

// IssueStageFor classifies one enumerated issue: it resolves the hive's
// label families into stageengine.Facts (issueFactsFrom) and asks the
// engine (stageengine.DeriveIssue) for the stage. covered reports whether
Expand Down Expand Up @@ -614,6 +661,7 @@ func SyncIssueStageLabelsWith(ctx context.Context, client *Client, result *Actio
var want stagelabels.Desired
var tr stagelabels.Transition
var triageYielded bool
var staleOpenPR string
if stage == stagelabels.None {
store.ForgetStage(key)
} else {
Expand Down Expand Up @@ -660,6 +708,11 @@ func SyncIssueStageLabelsWith(ctx context.Context, client *Client, result *Actio
want.Clear = []string{triageAwaitingLabel}
}
}
// A `has-open-pr` whose linking PR is gone comes off in the same
// write; Decision.Clear carries it through StaleOpenPRLabel.
if staleOpenPR = client.settleOpenPRLabelClear(ctx, store, key, in, logger); staleOpenPR != "" {
want.Clear = append(want.Clear, staleOpenPR)
}
}
if stage == stagelabels.PRInProgress || stage == stagelabels.CoveredByPR {
var edited, commented bool
Expand Down Expand Up @@ -709,6 +762,7 @@ func SyncIssueStageLabelsWith(ctx context.Context, client *Client, result *Actio
facts.ObservedAt = now
facts.Issue.Stalled = want.Stalled
facts.Issue.TriageClearYielded = triageYielded
facts.Issue.StaleOpenPRLabel = staleOpenPR
pending = append(pending, issueStagePending{in: in, key: key, want: want, tr: tr, covered: covered, reason: reason, facts: facts})
}
// The write: one ReconcileBatch for the pass. The reconciler re-reads
Expand Down
165 changes: 165 additions & 0 deletions src/pkg/github/issue_stage_labels_open_pr_clear_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package github

import (
"bytes"
"context"
"log/slog"
"slices"
"strings"
"testing"
"time"

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

// projectbluefin/bluefin-bling#82 and projectbluefin/common#1656: the
// open-PR guard put `has-open-pr` on an issue it refused to dispatch, the
// linking PR then closed or merged, and the label stayed for good next to
// stage/010 or stage/045, still saying an open PR links the issue. The
// issue sweep now takes it off in the stage write once its own open-PR
// listing shows no PR links the issue.
func TestSyncIssueStageLabels_HasOpenPRClearedOnlyOnEvidence(t *testing.T) {
const n = 82
issue := func() *ActionableResult {
result := &ActionableResult{}
result.Issues = IssueResultFromItems([]Issue{{
Repo: "acme/widgets", Number: n, Author: "alice", AuthorIsHuman: true,
Labels: []string{"kind/bug", HasOpenPRLabel, stagelabels.Actionable.Label()},
}})
return result
}
openPRRemovals := func(fake *issueStageServer) int {
fake.mu.Lock()
defer fake.mu.Unlock()
count := 0
for _, l := range fake.removed[n] {
if strings.EqualFold(l, HasOpenPRLabel) {
count++
}
}
return count
}
linking := []map[string]any{openPRFixture(128, "Fixes #82", "mendezr", stageNow().Add(-24*time.Hour))}

t.Run("no PR links the issue: cleared, silently", func(t *testing.T) {
fake := newIssueStageServer(t)
c := issueStageTestClient(t, fake.srv, true)
store := stagelabels.NewStore("", stageNow)
syncSeeded(t, fake, c, issue(), store, stageNow())
if got := openPRRemovals(fake); got != 1 {
t.Fatalf("%s removals = %d, want 1: removed=%v", HasOpenPRLabel, got, fake.removed[n])
}
fake.mu.Lock()
defer fake.mu.Unlock()
if slices.Contains(fake.removed[n], "kind/bug") || len(fake.added[n]) != 0 {
t.Fatalf("only the stale label may change: added=%v removed=%v", fake.added[n], fake.removed[n])
}
if fake.comments[n] != 0 {
t.Fatalf("the label is silent: %d comments posted", fake.comments[n])
}
if rec, _ := store.Get(stagelabels.Key("acme/widgets", n)); rec.OpenPRLabelClearedAt.IsZero() {
t.Fatalf("removal must be booked on the record: %+v", rec)
}
})

t.Run("an open PR still links it: kept", func(t *testing.T) {
fake := newIssueStageServer(t)
fake.openPRs = linking
c := issueStageTestClient(t, fake.srv, true)
syncSeeded(t, fake, c, issue(), stagelabels.NewStore("", stageNow), stageNow())
if got := openPRRemovals(fake); got != 0 {
t.Fatalf("label removed while PR #128 still links the issue: removed=%v", fake.removed[n])
}
})

t.Run("listing fails: kept", func(t *testing.T) {
fake := newIssueStageServer(t)
fake.openPRsFail = true
c := issueStageTestClient(t, fake.srv, true)
syncSeeded(t, fake, c, issue(), stagelabels.NewStore("", stageNow), stageNow())
if got := openPRRemovals(fake); got != 0 {
t.Fatalf("a failed listing must never remove the label: removed=%v", fake.removed[n])
}
})

t.Run("guard off: kept, no listing", func(t *testing.T) {
fake := newIssueStageServer(t)
c := issueStageTestClient(t, fake.srv, true)
c.SetSkipIssuesWithOpenPR(false)
syncSeeded(t, fake, c, issue(), stagelabels.NewStore("", stageNow), stageNow())
if got := openPRRemovals(fake); got != 0 {
t.Fatalf("scanner.skip_issues_with_open_pr: false must leave the label: removed=%v", fake.removed[n])
}
fake.mu.Lock()
defer fake.mu.Unlock()
if fake.pullsCalls != 0 {
t.Fatalf("open-PR listings = %d, want 0 with the guard off", fake.pullsCalls)
}
})

t.Run("re-added with no PR: removed once, then yielded", func(t *testing.T) {
fake := newIssueStageServer(t)
c := issueStageTestClient(t, fake.srv, true)
store := stagelabels.NewStore("", stageNow)
var logBuf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&logBuf, nil))
pass := func() {
t.Helper()
result := issue()
fake.seed(result)
ResetRateLimitPacingForTest()
resetRESTAccountingForTest(t, stageNow())
c.InvalidateOpenPRLinks("")
SyncIssueStageLabels(context.Background(), c, result, store, stageNow(), logger)
}
key := stagelabels.Key("acme/widgets", n)
pass()
pass() // another writer put it back: yield
pass() // still yielded: no removal, no second log
if got := openPRRemovals(fake); got != 1 {
t.Fatalf("%s removals = %d over three passes, want exactly 1: removed=%v", HasOpenPRLabel, got, fake.removed[n])
}
if rec, _ := store.Get(key); !rec.OpenPRLabelClearYielded {
t.Fatalf("label back with no PR must book the yield: %+v", rec)
}
if got := strings.Count(logBuf.String(), "came back after the hive removed it"); got != 1 {
t.Fatalf("yield logged %d times, want once:\n%s", got, logBuf.String())
}

// A new PR links the issue (the guard re-adds the label for it):
// the label is accurate again, so the once-only memory starts over
// and the label comes off once more after that PR closes.
fake.mu.Lock()
fake.openPRs = linking
fake.mu.Unlock()
pass()
if rec, _ := store.Get(key); rec.OpenPRLabelClearYielded || !rec.OpenPRLabelClearedAt.IsZero() {
t.Fatalf("a linking PR beside the label must reset the once-only state: %+v", rec)
}
fake.mu.Lock()
fake.openPRs = nil
fake.mu.Unlock()
pass()
if got := openPRRemovals(fake); got != 2 {
t.Fatalf("after the new PR closed the label must come off once more: %d removals, removed=%v", got, fake.removed[n])
}
})
}

// The once-only rule on its own, mirroring triageClearAllowed.
func TestOpenPRLabelClearAllowed(t *testing.T) {
cases := []struct {
name string
rec stagelabels.Record
remove, yieldN bool
}{
{"never removed", stagelabels.Record{}, true, false},
{"removed once and back", stagelabels.Record{OpenPRLabelClearedAt: stageNow()}, false, true},
{"already yielded", stagelabels.Record{OpenPRLabelClearedAt: stageNow(), OpenPRLabelClearYielded: true}, false, false},
}
for _, tc := range cases {
if remove, yieldNow := openPRLabelClearAllowed(tc.rec); remove != tc.remove || yieldNow != tc.yieldN {
t.Errorf("%s: remove=%v yieldNow=%v, want %v/%v", tc.name, remove, yieldNow, tc.remove, tc.yieldN)
}
}
}
17 changes: 17 additions & 0 deletions src/pkg/github/issue_stage_labels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ type issueStageServer struct {
// counts them in prLookups (guarded by mu).
prRateLimited bool
prLookups int
// openPRs is what GET /repos/acme/widgets/pulls (the open-PR guard's
// listing) answers; openPRsFail makes it answer 502. pullsCalls counts
// the listings.
openPRs []map[string]any
openPRsFail bool
pullsCalls int
}

func newIssueStageServer(t *testing.T) *issueStageServer {
Expand Down Expand Up @@ -158,6 +164,17 @@ func newIssueStageServer(t *testing.T) *issueStageServer {
_ = json.NewDecoder(r.Body).Decode(&body)
s.prPatches[pr] = body.Body
_ = json.NewEncoder(w).Encode(map[string]any{"number": pr, "body": body.Body})
case r.Method == http.MethodGet && rest == "pulls":
s.pullsCalls++
if s.openPRsFail {
w.WriteHeader(http.StatusBadGateway)
return
}
out := s.openPRs
if out == nil {
out = []map[string]any{}
}
_ = json.NewEncoder(w).Encode(out)
case r.Method == http.MethodGet && rest == "issues":
// List-by-label used by the legacy decision-label retirement:
// answer from truth so carriers block definition deletion.
Expand Down
6 changes: 4 additions & 2 deletions src/pkg/github/open_pr_links.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ import (
const (
// HasOpenPRLabel marks an issue the guard refused to dispatch because an
// open pull request already links it with a closing keyword. It is a
// signal for the tracker, not a park: the label comes off with nothing
// — the stage engine re-derives the issue's stage from the PR itself.
// signal for the tracker, not a park: nothing has to remove it for the
// issue to move on — the stage engine re-derives the issue's stage from
// the PR itself — and the issue stage-label sweep takes it off once no
// open PR links the issue any more (settleOpenPRLabelClear).
HasOpenPRLabel = "has-open-pr"
hasOpenPRLabelColor = "0e8a16"
hasOpenPRLabelDescription = "An open PR already links this issue with Fixes/Closes/Resolves; the hive will not dispatch it again"
Expand Down
15 changes: 14 additions & 1 deletion src/pkg/stageengine/derive_issue.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func deriveIssue(f Facts) Decision {
// label as found and the next sweep re-judges it from the restarted
// clock.
Stalled: f.Issue.Stalled && stage != stagelabels.None,
Clear: append(issueTriageClear(f, stage), issueParkClear(f, stage)...),
Clear: append(append(issueTriageClear(f, stage), issueParkClear(f, stage)...), issueOpenPRLabelClear(f, stage)...),
}
}

Expand All @@ -135,6 +135,19 @@ func issueParkClear(f Facts, stage stagelabels.Stage) []string {
return []string{label}
}

// issueOpenPRLabelClear names `has-open-pr` once the issue sweep found no
// open PR linking the issue (IssueFacts.StaleOpenPRLabel). The open-PR
// guard adds the label when it refuses a dispatch, and its description says
// an open PR links the issue; once that PR merged or closed the claim is
// false, so the writer takes it off in the same write as the stage.
func issueOpenPRLabelClear(f Facts, stage stagelabels.Stage) []string {
label := strings.TrimSpace(f.Issue.StaleOpenPRLabel)
if label == "" || stage == stagelabels.None {
return nil
}
return []string{label}
}

// issueTriageClear names the reporter-trust awaiting label the issue still
// wears once its stage has settled triage (020 claimed and later), so the
// writer removes it in the same label write as the stage. 015 is a tracking
Expand Down
48 changes: 48 additions & 0 deletions src/pkg/stageengine/derive_issue_open_pr_clear_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package stageengine

import (
"slices"
"testing"

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

// The issue sweep marks `has-open-pr` stale (IssueFacts.StaleOpenPRLabel)
// once its open-PR listing shows no PR links the issue; the deriver then
// asks the writer to clear it in the same write as the stage, next to any
// other clear. Without the mark, or on a closed issue, nothing is added.
func TestDeriveIssueClearsStaleOpenPRLabel(t *testing.T) {
const label = "has-open-pr"
cases := []struct {
name string
mut func(f *Facts)
clear []string
}{
{"marked stale: cleared", func(f *Facts) {
f.Labels = append(f.Labels, label)
f.Issue.StaleOpenPRLabel = label
}, []string{label}},
{"worn but not marked: kept", func(f *Facts) { f.Labels = append(f.Labels, label) }, nil},
{"beside a stale needs-triage: both cleared", func(f *Facts) {
f.Labels = append(f.Labels, label, "needs-triage")
f.Issue.Bucket = BucketInProgress
f.Issue.TriageAwaitingLabel = "needs-triage"
f.Issue.StaleOpenPRLabel = label
}, []string{"needs-triage", label}},
{"closed issue: nothing extra", func(f *Facts) {
f.Open = false
f.Issue.StaleOpenPRLabel = label
}, nil},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
d := DeriveIssue(derivedIssueFacts(tc.mut))
if !slices.Equal(d.Clear, tc.clear) {
t.Fatalf("Clear = %v, want %v (stage %s)", d.Clear, tc.clear, d.Stage)
}
if d.Stage == stagelabels.None && len(d.Clear) != 0 {
t.Fatalf("a None stage must not clear: %v", d.Clear)
}
})
}
}
Loading
Loading