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
25 changes: 22 additions & 3 deletions bin/contributor-relay.js
Original file line number Diff line number Diff line change
Expand Up @@ -5007,12 +5007,25 @@ function escapeRegExp(s) {
return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// fixPRRunningWhere says where this relay is already running fix-pr task
// taskId, or null. One fix-pr task runs in exactly one place: a second
// task_assign with the same task_id (a hub that delivered it twice) must not
// start it again as the primary task or in a parallel session.
function fixPRRunningWhere(taskId) {
if (!taskId) return null;
if (currentTask && currentTask.task_id === taskId) return 'as the primary task';
if (parallelFixes.has(taskId)) return 'in a parallel fix session';
if (preemptingFix && preemptingFix.task_id === taskId) return 'as the fix preempting the primary task';
if (deferredFixes.some(d => d.task.task_id === taskId)) return 'deferred until the current task ends';
return null;
}

// handleFixPRInterrupt decides spawn / preempt / defer for a fix-pr task that
// arrived while currentTask is running.
function handleFixPRInterrupt(msg, hub) {
if (parallelFixes.has(msg.task_id) || deferredFixes.some(d => d.task.task_id === msg.task_id)
|| (preemptingFix && preemptingFix.task_id === msg.task_id)) {
console.log(`Ignoring duplicate fix-pr ${sanitizeHubText(msg.task_id)} — already handling it`);
const where = fixPRRunningWhere(msg.task_id);
if (where) {
console.log(`Ignoring duplicate fix-pr ${sanitizeHubText(msg.task_id)} — already running it ${where}`);
return;
}
noteTaskAttemptStart(hub, msg);
Expand Down Expand Up @@ -10016,6 +10029,10 @@ function handleMessage(data, hub) {
handleFixPRInterrupt(msg, hub);
break;
}
if (msg.kind === FIX_PR_KIND && fixPRRunningWhere(msg.task_id)) {
console.log(`Ignoring duplicate fix-pr ${sanitizeHubText(msg.task_id)} — already running it ${fixPRRunningWhere(msg.task_id)}`);
break;
}
if (currentTask) {
console.log(`Rejecting task ${taskDisplay(msg)} from ${hub.url} — already working on ${taskDisplay(currentTask)}`);
sendTo(hub, { type: 'task_failed', seq: nextSeq(), task_id: msg.task_id, reason: 'Already has active task' });
Expand Down Expand Up @@ -10108,6 +10125,7 @@ function handleMessage(data, hub) {
writeRelayStatus();
activeHubIndex = hubs.indexOf(hub);
console.log(`Task assigned: ${sanitizeHubText(msg.kind)} ${sanitizeHubText(taskDisplay(msg))} — ${sanitizeHubText(msg.title)} (from ${hub.url})`);
if (msg.kind === FIX_PR_KIND) console.log(`fix-pr ${fixPRLabel(msg)}: running as the primary task (no task was running)`);
if (msg.github_token) {
injectGhToken(msg.github_token);
tokenExpiresAt = msg.token_expires_at ? new Date(msg.token_expires_at).getTime() : null;
Expand Down Expand Up @@ -10871,6 +10889,7 @@ if (process.env.HIVE_RELAY_TEST_MODE === '1') {
FIX_PR_DONE_MARKER,
FIX_PR_FAILED_MARKER,
fixPRState,
fixPRRunningWhere,
scanPaneForFixMarkers,
relaySupportsParallelFixes,
blockingPromptKey,
Expand Down
52 changes: 52 additions & 0 deletions bin/contributor-relay.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15600,6 +15600,58 @@ test('#12436 headless primary: a preempt fix is deferred and runs before the nex
} finally { console.log = log; teardown(relay); }
});

// hivecommons/hive#17385 (2026-11-09): the hub delivered one boundary fix-pr
// task twice. The relay started the first copy as its primary task and the
// second in a parallel fix session, so the same fix ran in two places.
test('#17385 a fix-pr task_id delivered twice runs once, as the primary task', () => {
const relay = loadRelay({ backend: 'claude', env: { HIVE_MAX_PARALLEL_FIXES: '1', HIVE_CONTRIBUTOR_QUOTA_GUARD: 'off' }, execFileResult: { defer: true } });
const log = console.log;
const lines = [];
console.log = (...a) => lines.push(a.join(' '));
try {
const hub = relay.getHubs()[0];
const sent = [];
hub.ws = { readyState: 1, send: p => sent.push(JSON.parse(p)) };
relay.setCurrentTask(null);
const boundary = FIX_PR_TASK('fix-danathar-1', { priority: 'queued', mode: 'boundary' });
relay.handleMessage(JSON.stringify(boundary), hub);
assert.strictEqual(relay.getCurrentTask() && relay.getCurrentTask().task_id, 'fix-danathar-1', 'the first copy becomes the primary task');
const spawnsBefore = relay.__execFileCalls.length;
relay.handleMessage(JSON.stringify(boundary), hub);
assert.deepStrictEqual(relay.fixPRState().parallel, [], 'the second copy must not start a parallel fix session');
assert.strictEqual(relay.__execFileCalls.length, spawnsBefore, 'no parallel child spawned for the duplicate');
assert.strictEqual(relay.getCurrentTask().task_id, 'fix-danathar-1');
assert.strictEqual(sent.filter(m => m.type === 'task_accepted' && m.task_id === 'fix-danathar-1').length, 1, `accepted once: ${JSON.stringify(sent)}`);
assert.ok(!sent.some(m => m.type === 'task_failed' && m.task_id === 'fix-danathar-1'), 'the duplicate is ignored, not failed back');
assert.ok(lines.some(l => /running as the primary task/.test(l)), `log names the path taken: ${lines.join('\n')}`);
assert.ok(lines.some(l => /Ignoring duplicate fix-pr fix-danathar-1 — already running it as the primary task/.test(l)), lines.join('\n'));
} finally { console.log = log; teardown(relay); }
});

test('#17385 a fix-pr task_id already in a parallel session is not also started as the primary task', () => {
const relay = loadRelay({ backend: 'claude', env: { HIVE_MAX_PARALLEL_FIXES: '1', HIVE_CONTRIBUTOR_QUOTA_GUARD: 'off' }, execFileResult: { defer: true } });
const log = console.log;
const lines = [];
console.log = (...a) => lines.push(a.join(' '));
try {
const hub = relay.getHubs()[0];
const sent = [];
hub.ws = { readyState: 1, send: p => sent.push(JSON.parse(p)) };
relay.setCurrentTask({ task_id: 't-primary', task_gen: 1, kind: 'issue', repo: 'foo/bar', number: 1, title: 'primary' });
relay.handleMessage(JSON.stringify(FIX_PR_TASK('fix-r')), hub);
assert.deepStrictEqual(relay.fixPRState().parallel, ['fix-r']);
// The primary ends while the fix still runs; the same task arrives again.
relay.setCurrentTask(null);
relay.handleMessage(JSON.stringify(FIX_PR_TASK('fix-r')), hub);
assert.strictEqual(relay.getCurrentTask(), null, 'the duplicate must not become the primary task');
assert.deepStrictEqual(relay.fixPRState().parallel, ['fix-r']);
assert.strictEqual(sent.filter(m => m.type === 'task_accepted' && m.task_id === 'fix-r').length, 1, JSON.stringify(sent));
assert.ok(lines.some(l => /Ignoring duplicate fix-pr fix-r — already running it in a parallel fix session/.test(l)), lines.join('\n'));
assert.strictEqual(relay.fixPRRunningWhere('fix-r'), 'in a parallel fix session');
assert.strictEqual(relay.fixPRRunningWhere('other'), null);
} finally { console.log = log; teardown(relay); }
});

(async () => {
for (const [name, fn] of only ? tests.filter(([n]) => n.includes(only)) : tests) {
try {
Expand Down
1 change: 1 addition & 0 deletions changelog.d/fixed-contribute-no-rework-for-merged-pr.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- A contributor's relay is no longer sent to rework a PR that has already merged or closed, and one `fix-pr` task now runs once. On hivecommons/hive#17385 a stage-072 nudge queued a fix at 12:32Z, the PR merged at 13:13:58Z, and at about 14:25Z the hub still handed the relay `fix-pr hive#17385`, which the relay then ran twice: about 4.5 minutes lost, nothing pushed. Each link in that chain is fixed. The fix queue took the nudge's display name (`hive` on a hive whose repos are listed without the org), so the "left stage 072" resolve, which looks up `owner/name`, never found the entry, and the relay got a repo it could not match to its authorized list; queued fixes are now keyed and sent as `owner/name`. Right before a queued fix is handed out, the hub now checks the PR is still open (from the state cache when it holds the repo, else one PR read tagged `hive:contribute_fix_dispatch`); a merged or closed PR leaves the queue with a `fix queue: dropped a PR that is no longer open` log line, and if the state cannot be read the fix waits for the next tick while the relay takes ordinary work. A fix handed out at a task boundary was pushed to the relay twice (once by the dispatcher, once by the `ready` handler); it is now sent once, and the relay ignores a second `task_assign` for a `fix-pr` task it is already running (as its primary task, in a parallel session, preempting, or deferred) and logs where it runs. Progress reports from a boundary fix running as the relay's primary task are no longer answered with `task_revoke: no active lease for this task`, which killed the fix mid-run.
3 changes: 3 additions & 0 deletions src/docs/contributor-relay.md
Original file line number Diff line number Diff line change
Expand Up @@ -1757,9 +1757,12 @@ Set `HIVE_MAX_PARALLEL_FIXES=0` in `~/.config/hive/contributor.env` and restart
- `mode=preempt`, interactive pane: `task_accepted`, then the pane receives an `INTERRUPT (hive fix-pr, preempt mode)` prompt telling the agent to park the current issue (commit/stash WIP; the claim stays alive), fix the PR, print exactly `HIVE_FIX_PR_DONE <task_id>` (or `HIVE_FIX_PR_FAILED <task_id> <reason>`), then resume. The progress tick reads the marker off the pane and reports `task_complete`/`task_failed` for the fix's `task_id`. Only one fix preempts at a time; more are queued locally.
- `mode=preempt`, headless primary: there is no pane to interrupt, so the fix is deferred (`task_accepted` immediately) and runs before the relay's next `ready` — "fix what you broke before taking new work" holds on the client too.
- With no task running, a `fix-pr` is just the next task.
- One `fix-pr` task runs in one place. A second `task_assign` with a `task_id` the relay is already running — as its primary task, in a parallel session, as the preempting fix, or deferred — is ignored, and the log says where it is already running.

The hub records the mode it used in the nudge comment's marker (`mode=spawn|preempt|queued|comment`) and exposes queue depth / in-flight as `fix_queue` on the contributor profile API.

**Only open PRs are dispatched.** Right before a queued fix is handed out, the hub checks that its PR is still open: from the state cache when it holds the repo (free while the cached copy is inside its freshness bound, otherwise one re-read), else with one PR read tagged `hive:contribute_fix_dispatch`. A PR that has merged or closed leaves the queue with a `fix queue: dropped a PR that is no longer open` log line, and no relay is sent to rework it. When the state cannot be read, the fix is not dispatched that tick: it stays queued and the next one asks again, and a relay asking for its next task gets ordinary work meanwhile instead of waiting idle. Queued fixes carry the repo as `owner/name` even on a hive that lists its repos without the org, so the fix task's `repo` and the PR leaving stage 072 both match the queued entry.

**When the relay fails the task.** `task_failed` for a fix's `task_id` does not settle it as done: its PRs go back in the hub's queue (same place by age) and are not interrupted back in for 5 minutes, though the relay's next `ready` serves them at once. After three failed dispatches a PR leaves the fix queue and the stage engine's re-nudge / adoption path takes over. A dispatch the relay fails within one second of the nudge is not reported as delivered: the nudge comment reads `mode=queued`, says the relay could not take the task (quoting the relay's `message`/`reason`), and the stage log carries `relay_failed=true` (hivecommons/hive#14668).

#### What the operator sees (Operations → Connected contributor agents)
Expand Down
4 changes: 4 additions & 0 deletions src/pkg/dashboard/api_repo_item_takeover_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dashboard

import (
"context"
"encoding/json"
"net/http"
"slices"
Expand Down Expand Up @@ -236,6 +237,9 @@ func TestRepoItemReroutePickupLapseFallsBackToAdoptNow(t *testing.T) {
srv, store := takeoverServer(t, mock)
hub := srv.contributeHub
hub.fixDispatched = func(_ *ContributorConnection, _ WSMessage) {}
// org/other#1 is a fixture the GitHub mock does not serve: report it
// open so the dispatch check keeps it.
hub.fixPRStateHook = func(context.Context, string, int) (fixPRState, string, error) { return fixPRStateOpen, "", nil }
// bee2 is online but already holds a task: the reroute queues behind it.
c := fixConn(hub, "bee2", fixCaps(capFixPRInterrupt), time.Now())
c.mu.Lock()
Expand Down
2 changes: 1 addition & 1 deletion src/pkg/dashboard/contribute_coverage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@ func TestRoleCoverage_FixTaskDispatchEndsNoWorkRun(t *testing.T) {
relay.mu.Unlock()
hub.sendFixTask(relay, "alice", &fixqueue.Dispatch{ID: "fix-1", Mode: fixqueue.ModeBoundary, Items: []fixqueue.Item{
{Repo: "myorg/repo1", Number: 7, URL: "https://github.com/myorg/repo1/pull/7", Title: "red PR"},
}})
}}, true)
if got := coverageAt(hub, relay, later); !reflect.DeepEqual(got, scannerAlice) {
t.Fatalf("relay working a fix task: RoleCoverage = %+v, want %+v", got, scannerAlice)
}
Expand Down
Loading
Loading