Skip to content

Commit fe62ca8

Browse files
committed
fix(label-hygiene): isolate a refused label so the sweep finishes (#1418)
The first failed DELETE escaped main() and ended the run on its first item, so the other 18 were never touched. Each removal now stands on its own: a 404 is a skip ("already gone"), any other refusal - including the 422 the live #1356/#1359 runs answered while the label stayed on the item - is recorded with the response body, the sweep still cleans everything behind it, and the run exits non-zero at the end naming what failed. The read-back stays the criterion. Rebased onto 5daf756 after the previous tip 324458e was judged FAIL.
1 parent 5daf756 commit fe62ca8

3 files changed

Lines changed: 133 additions & 6 deletions

File tree

‎.github/scripts/label-hygiene.mjs‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,23 @@ export function plan(pages) {
3939

4040
const realGh = (...a) => execFileSync('gh', a, { encoding: 'utf8', maxBuffer: 16 << 20 })
4141

42+
// What a refused DELETE says, in the order the log needs it: the status line `gh` writes to stderr,
43+
// then the JSON body it writes to stdout (#1418). A bare status line cannot tell a refused request
44+
// apart from a race, so the body is kept with the item that hit it.
45+
const describe = (error) => {
46+
const status = String(error?.stderr ?? '')
47+
.split('\n').map(line => line.trim()).filter(Boolean).pop()
48+
?.replace(/^gh:\s*/, '')
49+
const body = String(error?.stdout ?? '').trim().replace(/\s+/g, ' ')
50+
const line = status ?? String(error?.message ?? error)
51+
return body ? `${line} — ${body}` : line
52+
}
53+
54+
// A 404 is the one benign answer: the label was already gone before this call. A 422 is a refusal —
55+
// the live #1356/#1359 runs show the label still on the item afterwards — so it must not be read as
56+
// "already gone"; it goes to `failed` like any other write failure.
57+
const alreadyGone = (error) => /\(HTTP 404\)|Label does not exist/.test(String(error?.stderr ?? error?.message ?? error))
58+
4259
// `gh` and `env` are injectable so the whole run can be driven without the network, the way
4360
// merge-gate.mjs is tested.
4461
export function main({ gh = realGh, env = process.env, repo: repoOption, apply: applyOption } = {}) {
@@ -54,23 +71,45 @@ export function main({ gh = realGh, env = process.env, repo: repoOption, apply:
5471
const items = plan(pages)
5572
const labels = items.reduce((n, item) => n + item.stale.length, 0)
5673
console.log(`label-hygiene: before: ${items.length} item(s) / ${labels} label(s) not open`)
74+
// Each removal stands on its own: one refused label is reported and the items behind it are still
75+
// cleaned (#1418). Before this, the first throw escaped main() and the run processed only 1 item.
76+
const skipped = []
77+
const failed = []
5778
for (const item of items) {
5879
for (const name of item.stale) console.log(`#${item.number} ${item.title} -${name}`)
5980
if (!apply) continue
60-
for (const name of item.stale) gh('api', '-X', 'DELETE', `repos/${repo}/issues/${item.number}/labels/${encodeURIComponent(name)}`)
81+
for (const name of item.stale) {
82+
try {
83+
gh('api', '-X', 'DELETE', `repos/${repo}/issues/${item.number}/labels/${encodeURIComponent(name)}`)
84+
} catch (error) {
85+
if (alreadyGone(error)) {
86+
skipped.push({ number: item.number, name })
87+
console.log(`label-hygiene: skip #${item.number} ${name}: already gone`)
88+
continue
89+
}
90+
const reason = describe(error)
91+
failed.push({ number: item.number, name, reason })
92+
console.log(`label-hygiene: FAILED #${item.number} ${name}: ${reason}`)
93+
}
94+
}
6195
}
6296
if (!apply) {
6397
console.log('label-hygiene: dry run; add --apply to remove these labels')
64-
return { ok: items.length === 0 || !apply, items, applied: false }
98+
return { ok: items.length === 0 || !apply, items, skipped, failed, applied: false }
6599
}
100+
// Print the collected failures before the read-back, so the line survives the normal case where the
101+
// refused label is still on the item and the read-back answers first.
102+
if (failed.length) console.log(`label-hygiene: FAILED: ${failed.map(f => `#${f.number} (${f.name}: ${f.reason})`).join(', ')}`)
66103
// Read back rather than assume: the run reports its own result so the cleanup is verified, not trusted.
67104
const after = plan(STALE_LABELS.flatMap(name => list(`repos/${repo}/issues?state=closed&labels=${encodeURIComponent(name)}&per_page=100`)))
68105
console.log(`label-hygiene: after: ${after.length} item(s)`)
69106
if (after.length) {
70107
console.log(`label-hygiene: STILL STALE: ${after.map(item => `#${item.number} (${item.stale.join(', ')})`).join(', ')}`)
71-
return { ok: false, items, after, applied: true }
108+
return { ok: false, items, after, skipped, failed, applied: true }
72109
}
73-
return { ok: true, items, after, applied: true }
110+
// A write that was refused keeps the run red even if another actor cleared the label meanwhile: this
111+
// sweep did not do the work it set out to do, and the log names it. A 404 is skipped, not a failure.
112+
return { ok: failed.length === 0, items, after, skipped, failed, applied: true }
74113
}
75114

76115
if (process.argv[1] === fileURLToPath(import.meta.url)) {

‎.github/scripts/label-hygiene.test.mjs‎

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ const issue = (number, state, labels, title = `Item ${number}`) =>
1111

1212
// A fake API over a page store: `GET repos/x/y/issues?state=closed&labels=<name>` filters like GitHub
1313
// (state and one label), and a DELETE removes that label from the item. Every call is recorded.
14-
const fakeGh = (items) => {
14+
// `failures` maps `<number>/<label>` to a refusal: `stderr` is the status line `gh` writes, `stdout`
15+
// the JSON body it writes, and `remove: false` keeps the label on the item like a real refusal does.
16+
const fakeGh = (items, failures = {}) => {
1517
const store = items.map(item => ({ ...item, labels: item.labels }))
1618
const calls = []
1719
const gh = (...args) => {
@@ -21,7 +23,14 @@ const fakeGh = (items) => {
2123
const m = /\/issues\/(\d+)\/labels\/(.+)$/.exec(path)
2224
const item = store.find(i => String(i.number) === m[1])
2325
const name = decodeURIComponent(m[2])
24-
item.labels = item.labels.filter(l => l.name !== name)
26+
const failure = failures[`${m[1]}/${name}`]
27+
if (failure?.remove !== false) item.labels = item.labels.filter(l => l.name !== name)
28+
if (failure) {
29+
const error = new Error(failure.stderr)
30+
error.stderr = failure.stderr
31+
error.stdout = failure.stdout ?? ''
32+
throw error
33+
}
2534
return ''
2635
}
2736
const url = new URL('https://api.github.com/' + path)
@@ -41,6 +50,15 @@ const fakeGh = (items) => {
4150

4251
const run = (gh, apply) => main({ gh, env: { GH_REPO: 'ThinkFlowLab/FlyBot' }, repo: 'ThinkFlowLab/FlyBot', apply })
4352

53+
// Capture what the run prints: the failure line and the refusal's response body are the evidence, so
54+
// the tests pin them the way the live log reads.
55+
const capture = (fn) => {
56+
const lines = []
57+
const log = console.log
58+
console.log = (...args) => lines.push(args.join(' '))
59+
try { return { result: fn(), lines } } finally { console.log = log }
60+
}
61+
4462
test('#738: a dry run prints what it would do and removes nothing', () => {
4563
const gh = fakeGh([issue(602, 'closed', ['agent-working', 'bug', 'risk:T1'])])
4664
const r = run(gh, false)
@@ -131,3 +149,72 @@ test('#1401: closing an item is a trigger, and the daily sweep stays', () => {
131149
assert.match(wf, /^ {2}cancel-in-progress: false$/m, 'a close must not cancel the sweep it needs')
132150
assert.match(wf, /run: node \.github\/scripts\/label-hygiene\.mjs --apply$/m, 'the close event runs the same --apply as the sweep')
133151
})
152+
153+
test('#1418: a 422 is a refusal, not "already gone": the sweep continues and the read-back keeps the run red', () => {
154+
// The live shape from #1418: the label is still on the item after a 422 (job 122128075345, #1359).
155+
const gh = fakeGh([
156+
issue(1356, 'closed', ['agent-working']),
157+
issue(1359, 'closed', ['agent-pr']),
158+
issue(1400, 'closed', ['agent-working', 'bug']),
159+
], {
160+
'1356/agent-working': {
161+
remove: false,
162+
stderr: 'gh: Validation Failed (HTTP 422)',
163+
stdout: '{"message":"Validation Failed","errors":[{"resource":"Issue","field":"labels","code":"unprocessable"}]}',
164+
},
165+
})
166+
const { result: r, lines } = capture(() => run(gh, true))
167+
assert.equal(gh.deletes().length, 3, 'the first refusal must not abandon the items behind it')
168+
assert.deepEqual(gh.store.find(i => i.number === 1356).labels.map(l => l.name), ['agent-working'], 'a 422 leaves its label on the item')
169+
assert.deepEqual(gh.store.filter(i => i.number !== 1356).map(i => i.labels.map(l => l.name)), [[], ['bug']], 'the other items are still cleaned')
170+
assert.deepEqual(r.skipped, [], 'a 422 is never reported as already gone')
171+
assert.deepEqual(r.failed.map(f => [f.number, f.name]), [[1356, 'agent-working']])
172+
assert.equal(r.ok, false, 'the label is still stale at the read-back')
173+
const text = lines.join('\n')
174+
assert.match(text, /label-hygiene: FAILED #1356 agent-working: Validation Failed \(HTTP 422\)/)
175+
assert.match(text, /"message":"Validation Failed"/, 'the response body is printed, not only the status line')
176+
assert.doesNotMatch(text, /label-hygiene: skip #1356/)
177+
assert.match(text, /label-hygiene: FAILED: #1356 \(agent-working:/, 'the failed summary is printed before the read-back')
178+
assert.match(text, /STILL STALE: #1356 \(agent-working\)/)
179+
})
180+
181+
test('#1418: a 404 means the label is already gone: one skip line and a clean board is green', () => {
182+
const gh = fakeGh([
183+
issue(1356, 'closed', ['agent-working']),
184+
issue(1359, 'closed', ['agent-pr']),
185+
], {
186+
'1356/agent-working': {
187+
stderr: 'gh: Not Found (HTTP 404)',
188+
stdout: '{"message":"Not Found","documentation_url":"https://docs.github.com/rest"}',
189+
},
190+
})
191+
const { result: r, lines } = capture(() => run(gh, true))
192+
assert.equal(gh.deletes().length, 2)
193+
assert.deepEqual(r.skipped.map(s => [s.number, s.name]), [[1356, 'agent-working']])
194+
assert.deepEqual(r.failed, [])
195+
assert.equal(r.ok, true, 'a label that was gone before the call does not fail the sweep')
196+
const text = lines.join('\n')
197+
assert.match(text, /label-hygiene: skip #1356 agent-working: already gone/)
198+
assert.doesNotMatch(text, /STILL STALE/)
199+
})
200+
201+
test('#1418: an unexpected write failure is collected, the rest is cleaned, and the run names it and exits non-zero', () => {
202+
const gh = fakeGh([1354, 1356, 1358].map(n => issue(n, 'closed', ['agent-working', 'bug'])), {
203+
'1356/agent-working': {
204+
remove: false,
205+
stderr: 'gh: Server Error (HTTP 500)',
206+
stdout: '{"message":"Server Error"}',
207+
},
208+
})
209+
const { result: r, lines } = capture(() => run(gh, true))
210+
assert.equal(gh.deletes().length, 3)
211+
assert.deepEqual(r.failed.map(f => [f.number, f.name]), [[1356, 'agent-working']])
212+
assert.deepEqual(r.skipped, [])
213+
assert.equal(r.ok, false)
214+
assert.deepEqual(r.after.map(i => i.number), [1356], 'the label that really failed stays on the board')
215+
assert.deepEqual(gh.store.filter(i => i.number !== 1356).map(i => i.labels.map(l => l.name)), [['bug'], ['bug']])
216+
const text = lines.join('\n')
217+
assert.match(text, /FAILED #1356 agent-working: Server Error \(HTTP 500\)/)
218+
assert.match(text, /label-hygiene: FAILED: #1356 \(agent-working:/)
219+
assert.match(text, /STILL STALE: #1356 \(agent-working\)/)
220+
})
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The label-hygiene sweep no longer stops at the first label it cannot remove. A `404` on one DELETE means that label was already gone and is skipped; any other refusal — including the `422` that the live `#1356`/`#1359` runs returned, with the label still on the item — is collected together with the response body the request answered, the items behind it are still cleaned, and the run exits non-zero at the end naming what failed. The read-back after the sweep stays the criterion. ([#1418](https://github.com/ThinkFlowLab/FlyBot/issues/1418))

0 commit comments

Comments
 (0)