watchpr: start the conflict window at the arm
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful

The window ran from the first non-mergeable poll even while the rule was
disarmed, so the poll that armed it confirmed a run it played no part in.
Measure from the later of the run's start and the arm; re-arming stays a
no-op so a base moving under every poll still confirms.
This commit is contained in:
2026-09-26 22:14:25 +10:00
parent 7ffa123e3d
commit 5928233a97
6 changed files with 218 additions and 41 deletions
+31 -10
View File
@@ -5,11 +5,11 @@
// agent's own pushes and comments) are ignored, and so is any condition that was
// already true at the baseline -- which watchpr prints on stderr (as a JSON
// record under --json), so a run started against a conflicted or CI-red PR says
// so. One case is never reported at all: a conflict introduced by the push
// immediately before the watch started, on a PR whose head and base then never
// move, stays silent for the whole run, because nothing in Gitea's payload
// separates it from a merge check still in flight. The baseline line is the
// only notice of it.
// so. A conflict introduced by the push immediately before the watch started is
// not reported while the commits stay put, because nothing in Gitea's payload
// separates it from a merge check still in flight; the baseline line is the only
// notice of it. A later move of the head or base arms the rule without alerting,
// and restarts the two-minute window from itself.
//
// watchpr owner/repo#12 owner/repo:15
// watchpr --once --json owner/repo#12
@@ -73,7 +73,7 @@ func newRootCmd() *cobra.Command {
}
refs = append(refs, ref)
}
c := clientFor()
c := clientFor(jsonMode)
if once {
return runOnce(c, refs, jsonMode)
}
@@ -99,15 +99,33 @@ func newRootCmd() *cobra.Command {
// clientFor builds the Gitea client. Watching public repos works anonymously,
// so an unavailable token is a warning, not a failure; a poll that is actually
// rejected re-mints then.
func clientFor() *agent.GiteaClient {
func clientFor(jsonMode bool) *agent.GiteaClient {
token, err := agent.GiteaToken()
if err != nil {
fmt.Fprintf(os.Stderr, "warning: no Gitea token (%v); polling anonymously\n", err)
warn(os.Stderr, jsonMode, "no Gitea token (%v); polling anonymously", err)
token = ""
}
return agent.NewGiteaClient(token)
}
// warnRecord is the --json form of a warning. Under --json stderr carries
// nothing but NDJSON records, so a caller parsing it line by line never has to
// guess which shape a line is.
type warnRecord struct {
Warning string `json:"warning"`
}
// warn writes a non-fatal notice to stderr in whichever form the caller asked
// for.
func warn(w io.Writer, jsonMode bool, format string, args ...any) {
msg := fmt.Sprintf(format, args...)
if jsonMode {
_ = json.NewEncoder(w).Encode(warnRecord{Warning: msg})
return
}
_, _ = fmt.Fprintf(w, "warning: %s\n", msg)
}
// runOnce fetches and prints the current state of each PR, then exits 0.
func runOnce(c *agent.GiteaClient, refs []agent.PRRef, jsonMode bool) error {
login := agent.AgentLogin()
@@ -140,7 +158,7 @@ func runWatch(c *agent.GiteaClient, refs []agent.PRRef, interval time.Duration,
emitBaselines(os.Stderr, states, interval, jsonMode)
}
onError := func(ref agent.PRRef, err error) {
fmt.Fprintf(os.Stderr, "warning: polling %s: %v\n", ref.String(), err)
warn(os.Stderr, jsonMode, "polling %s: %v", ref.String(), err)
}
res, err := agent.Watch(c, refs, login, ticker.C, onBaseline, onError)
@@ -233,8 +251,11 @@ func baselineLine(st agent.PRState) string {
func suppressedAtBaseline(st agent.PRState) string {
var conds []string
if st.Mergeable == agent.MergeNo {
switch st.Mergeable {
case agent.MergeNo:
conds = append(conds, "already non-mergeable (a real conflict, or Gitea still recomputing)")
case agent.MergeUnknown:
conds = append(conds, "mergeability unknown (the conflict rule is disarmed until Gitea answers or the commits move)")
}
if st.CIStatus == "failure" || st.CIStatus == "error" {
conds = append(conds, "CI already "+st.CIStatus)
+53
View File
@@ -256,3 +256,56 @@ func TestBaselineIsEmittedInJSONMode(t *testing.T) {
t.Errorf("clean baseline = %q, want no suppression field", buf.String())
}
}
// Under --json stderr is the baseline and warning channel, so it has to be one
// shape: a caller parsing it line by line must never meet a bare `warning:`
// line between two NDJSON records.
func TestJSONModeStderrIsAllRecords(t *testing.T) {
st := agent.PRState{
Ref: agent.PRRef{Owner: "unkin", Repo: "repo", Number: 7},
State: "open",
Mergeable: agent.MergeNo,
}
var buf bytes.Buffer
warn(&buf, true, "no Gitea token (%v); polling anonymously", errors.New("vault refused"))
emitBaselines(&buf, []agent.PRState{st}, 30*time.Second, true)
warn(&buf, true, "polling %s: %v", st.Ref.String(), errors.New("HTTP 502"))
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(lines) != 3 {
t.Fatalf("stderr = %q, want 3 records", buf.String())
}
for _, line := range lines {
var rec map[string]any
if err := json.Unmarshal([]byte(line), &rec); err != nil {
t.Errorf("stderr line %q is not a JSON record: %v", line, err)
}
}
var first warnRecord
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil || !strings.Contains(first.Warning, "vault refused") {
t.Errorf("first record = %q, want the token warning", lines[0])
}
buf.Reset()
warn(&buf, false, "polling %s: %v", st.Ref.String(), errors.New("HTTP 502"))
if got := buf.String(); !strings.HasPrefix(got, "warning: ") {
t.Errorf("plain-mode warning = %q, want the warning: prefix", got)
}
}
// An unknown mergeability disarms the conflict rule exactly as a non-mergeable
// baseline does, so the baseline has to name it too.
func TestBaselineNamesAnUnknownMergeability(t *testing.T) {
st := agent.PRState{
Ref: agent.PRRef{Owner: "unkin", Repo: "repo", Number: 7},
State: "open",
Mergeable: agent.MergeUnknown,
CIStatus: "success",
}
if got := suppressedAtBaseline(st); !strings.Contains(got, "mergeability unknown") {
t.Errorf("suppressed = %q, want it to name the unknown mergeability", got)
}
if got := baselineLine(st); !strings.Contains(got, "not alerting") {
t.Errorf("baselineLine = %q, want the suppression note", got)
}
}