From 794f1dab1e9fc2515b2ca68d4de268fe344e2aac Mon Sep 17 00:00:00 2001 From: Danathar <6772335+Danathar@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:20:36 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20issue=20stage=20labels:=20take?= =?UTF-8?q?=20has-open-pr=20off=20once=20no=20open=20PR=20links=20the=20is?= =?UTF-8?q?sue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The open-PR guard added has-open-pr when it refused a dispatch and nothing removed it, so after the linking PR merged or closed the issue kept claiming an open PR links it (projectbluefin/bluefin-bling#82, projectbluefin/common#1656). The issue stage-label sweep now asks the guard's own listing (OpenPRLinkingIssue) for issues wearing the label and clears it through Decision.Clear in the stage write, only on a successful listing with no linking PR. Once per linking PR: a re-add with still no PR is yielded, and a linking PR seen again resets it. Signed-off-by: Danathar <6772335+Danathar@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 --- ...fixed-has-open-pr-cleared-when-unlinked.md | 1 + .../sweeps-and-operations.md | 9 +- src/docs/running-at-level-6.md | 2 +- src/pkg/github/issue_stage_labels.go | 54 ++++++ .../issue_stage_labels_open_pr_clear_test.go | 165 ++++++++++++++++++ src/pkg/github/issue_stage_labels_test.go | 17 ++ src/pkg/github/open_pr_links.go | 6 +- src/pkg/stageengine/derive_issue.go | 15 +- .../derive_issue_open_pr_clear_test.go | 48 +++++ src/pkg/stageengine/facts.go | 7 + src/pkg/stageengine/reconciler.go | 17 ++ .../stagelabels/open_pr_label_clear_test.go | 45 +++++ src/pkg/stagelabels/store.go | 56 ++++++ 13 files changed, 437 insertions(+), 5 deletions(-) create mode 100644 changelog.d/fixed-has-open-pr-cleared-when-unlinked.md create mode 100644 src/pkg/github/issue_stage_labels_open_pr_clear_test.go create mode 100644 src/pkg/stageengine/derive_issue_open_pr_clear_test.go create mode 100644 src/pkg/stagelabels/open_pr_label_clear_test.go diff --git a/changelog.d/fixed-has-open-pr-cleared-when-unlinked.md b/changelog.d/fixed-has-open-pr-cleared-when-unlinked.md new file mode 100644 index 0000000000..5786f110b3 --- /dev/null +++ b/changelog.d/fixed-has-open-pr-cleared-when-unlinked.md @@ -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. diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index 2feda4ff1d..b91cbc9515 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -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 diff --git a/src/docs/running-at-level-6.md b/src/docs/running-at-level-6.md index a1825be9e3..f74a76ee54 100644 --- a/src/docs/running-at-level-6.md +++ b/src/docs/running-at-level-6.md @@ -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 `` 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:`, 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. | diff --git a/src/pkg/github/issue_stage_labels.go b/src/pkg/github/issue_stage_labels.go index a1ab0aa0ea..00b8b2e350 100644 --- a/src/pkg/github/issue_stage_labels.go +++ b/src/pkg/github/issue_stage_labels.go @@ -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 @@ -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 { @@ -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 @@ -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 diff --git a/src/pkg/github/issue_stage_labels_open_pr_clear_test.go b/src/pkg/github/issue_stage_labels_open_pr_clear_test.go new file mode 100644 index 0000000000..34722626a9 --- /dev/null +++ b/src/pkg/github/issue_stage_labels_open_pr_clear_test.go @@ -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) + } + } +} diff --git a/src/pkg/github/issue_stage_labels_test.go b/src/pkg/github/issue_stage_labels_test.go index cc6235867c..b7bb4d83a1 100644 --- a/src/pkg/github/issue_stage_labels_test.go +++ b/src/pkg/github/issue_stage_labels_test.go @@ -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 { @@ -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. diff --git a/src/pkg/github/open_pr_links.go b/src/pkg/github/open_pr_links.go index 7e77215931..726ee68f73 100644 --- a/src/pkg/github/open_pr_links.go +++ b/src/pkg/github/open_pr_links.go @@ -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" diff --git a/src/pkg/stageengine/derive_issue.go b/src/pkg/stageengine/derive_issue.go index da3e64f5dd..b2ae6f8491 100644 --- a/src/pkg/stageengine/derive_issue.go +++ b/src/pkg/stageengine/derive_issue.go @@ -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)...), } } @@ -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 diff --git a/src/pkg/stageengine/derive_issue_open_pr_clear_test.go b/src/pkg/stageengine/derive_issue_open_pr_clear_test.go new file mode 100644 index 0000000000..e66b558921 --- /dev/null +++ b/src/pkg/stageengine/derive_issue_open_pr_clear_test.go @@ -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) + } + }) + } +} diff --git a/src/pkg/stageengine/facts.go b/src/pkg/stageengine/facts.go index ec3434aba9..811c5a9125 100644 --- a/src/pkg/stageengine/facts.go +++ b/src/pkg/stageengine/facts.go @@ -214,6 +214,13 @@ type IssueFacts struct { // writer owns it on this issue, so the deriver no longer asks for it // to be cleared (hivecommons/hive#18387). TriageClearYielded bool + // StaleOpenPRLabel is the `has-open-pr` label the issue wears when the + // issue sweep found, on a successful open-PR listing, that no open PR + // links the issue any more; "" otherwise. The deriver asks the writer + // to clear it in the same label write as the stage. Only the sweep sets + // it: the evidence is its listing, so an out-of-cycle fact keeps the + // label as found. + StaleOpenPRLabel string } // ClaimFact is the live claim on an issue. diff --git a/src/pkg/stageengine/reconciler.go b/src/pkg/stageengine/reconciler.go index 76bda36012..89951b2646 100644 --- a/src/pkg/stageengine/reconciler.go +++ b/src/pkg/stageengine/reconciler.go @@ -213,6 +213,7 @@ func (r *reconciler) Reconcile(ctx context.Context, f Facts) (Transition, error) } } noteTriageCleared(r.opts.Store, key, f, out.Removed) + noteOpenPRLabelCleared(r.opts.Store, key, f, out.Removed) if err == nil { // The gate's refusal is a fact about the record: readers that // compare the record with the item's labels must know the labels @@ -249,6 +250,22 @@ func noteTriageCleared(store *stagelabels.Store, key string, f Facts, removed [] } } +// noteOpenPRLabelCleared records on the issue's record that this write +// took a stale `has-open-pr` off, so a later read that finds it back with +// still no linking PR makes the hive yield it on that issue. +func noteOpenPRLabelCleared(store *stagelabels.Store, key string, f Facts, removed []string) { + if store == nil || f.Issue == nil || f.Ref.Kind != stagelabels.IssueItem { + return + } + label := strings.TrimSpace(f.Issue.StaleOpenPRLabel) + if label == "" { + return + } + if slices.ContainsFunc(removed, func(l string) bool { return strings.EqualFold(l, label) }) { + store.NoteOpenPRLabelCleared(key, f.ObservedAt) + } +} + // noteCoveringPR keeps the issue record's memory of its covering PR in // step with the stage just observed: the named PR while the issue is at // 040-covered-by-pr, nothing at any other stage. A 040 whose PR the facts diff --git a/src/pkg/stagelabels/open_pr_label_clear_test.go b/src/pkg/stagelabels/open_pr_label_clear_test.go new file mode 100644 index 0000000000..bd6aaa1555 --- /dev/null +++ b/src/pkg/stagelabels/open_pr_label_clear_test.go @@ -0,0 +1,45 @@ +package stagelabels + +import ( + "path/filepath" + "testing" + "time" +) + +// The hive's one removal of a stale `has-open-pr` and its yield persist +// with the record; a linking PR seen beside the label again resets both so +// the label can come off once more when that PR goes. +func TestStoreOpenPRLabelClearPersistsAndResets(t *testing.T) { + now := time.Date(2026, 11, 17, 19, 22, 0, 0, time.UTC) + clock := func() time.Time { return now } + path := filepath.Join(t.TempDir(), StateFile) + s := NewStore(path, clock) + const key = "projectbluefin/bluefin-bling#82" + s.NoteOpenPRLabelCleared(key, now) + if _, ok := s.Get(key); ok { + t.Fatal("NoteOpenPRLabelCleared must not invent a record") + } + if s.MarkOpenPRLabelClearYielded(key) { + t.Fatal("no record yet: nothing to mark") + } + s.Observe(key, Actionable, "PR #128 closed") + s.NoteOpenPRLabelCleared(key, now) + if !s.MarkOpenPRLabelClearYielded(key) || s.MarkOpenPRLabelClearYielded(key) { + t.Fatal("the yield must report set exactly once") + } + if err := s.Save(); err != nil { + t.Fatal(err) + } + reloaded := NewStore(path, clock) + if err := reloaded.Load(); err != nil { + t.Fatal(err) + } + rec, ok := reloaded.Get(key) + if !ok || !rec.OpenPRLabelClearedAt.Equal(now) || !rec.OpenPRLabelClearYielded { + t.Fatalf("reloaded record %+v: want the removal time and the yield", rec) + } + reloaded.ResetOpenPRLabelClear(key) + if rec, _ := reloaded.Get(key); !rec.OpenPRLabelClearedAt.IsZero() || rec.OpenPRLabelClearYielded { + t.Fatalf("reset left %+v", rec) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index 04d41be075..1d59ff2f74 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -277,6 +277,16 @@ type Record struct { // a reset on a read that finds the label briefly absent would restart // the remove / re-add loop. TriageClearYielded bool `json:"triage_clear_yielded,omitempty"` + // OpenPRLabelClearedAt is when the hive's stage write last took + // `has-open-pr` off this issue because no open PR links it any more. + // Zero when the hive never removed it, or since a linking PR was seen + // beside the label again (ResetOpenPRLabelClear). + OpenPRLabelClearedAt time.Time `json:"open_pr_label_cleared_at,omitempty"` + // OpenPRLabelClearYielded is set once `has-open-pr` was seen back on + // the issue, with no open PR linking it, after the hive removed it: + // another writer owns it there, so the hive leaves it until a linking + // PR is seen beside it again. + OpenPRLabelClearYielded bool `json:"open_pr_label_clear_yielded,omitempty"` // AdoptedHeadAt is when AdoptedHead last moved under a live in-place // adoption: the adoption itself, then each hive push. Zero only on // records written before it existed (hivecommons/hive#13040); the @@ -1488,6 +1498,52 @@ func (s *Store) MarkTriageClearYielded(key string) bool { return true } +// NoteOpenPRLabelCleared records that the hive's stage write took +// `has-open-pr` off key at now. A missing record is left missing. +func (s *Store) NoteOpenPRLabelCleared(key string, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || r.OpenPRLabelClearedAt.Equal(now) { + return + } + r.OpenPRLabelClearedAt = now + s.items[key] = r + s.dirty = true +} + +// MarkOpenPRLabelClearYielded records that `has-open-pr` came back on key +// after the hive removed it while no open PR linked the issue. It reports +// whether this call set the mark, so the caller logs the yield once. +func (s *Store) MarkOpenPRLabelClearYielded(key string) bool { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || r.OpenPRLabelClearYielded { + return false + } + r.OpenPRLabelClearYielded = true + s.items[key] = r + s.dirty = true + return true +} + +// ResetOpenPRLabelClear forgets the one removal and any yield on key: a +// linking PR was seen beside `has-open-pr`, so the label is accurate again +// and may come off once more when that PR goes. +func (s *Store) ResetOpenPRLabelClear(key string) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || (r.OpenPRLabelClearedAt.IsZero() && !r.OpenPRLabelClearYielded) { + return + } + r.OpenPRLabelClearedAt = time.Time{} + r.OpenPRLabelClearYielded = false + s.items[key] = r + s.dirty = true +} + // MarkNudged records that nudge number n for head was posted at now. A new // head restarts the count and the adoption grace; online says whether the // author's relay was reachable (first nudge decides the grace kind).