Skip to content

Commit b81ec96

Browse files
steipeteag-linden
andauthored
fix: recover interrupted command dispatches (#407)
Preserve durable command claims across router interruptions, recover keyed Actions receipts, verify actual worker execution before suppressing retries, and retain the keyed workflow_dispatch fallback. Co-authored-by: Alex <[email protected]>
1 parent a52b852 commit b81ec96

13 files changed

Lines changed: 1202 additions & 39 deletions

‎.github/workflows/assist.yml‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name: ClawSweeper assist
22

3-
run-name: ${{ format('Assist {0}#{1}', github.event.client_payload.target_repo || 'openclaw/openclaw', github.event.client_payload.item_number || '?') }}
3+
run-name: ${{ github.event.client_payload.dispatch_key && format('Assist {0}#{1} [{2}]', github.event.client_payload.target_repo || 'openclaw/openclaw', github.event.client_payload.item_number || '?', github.event.client_payload.dispatch_key) || format('Assist {0}#{1}', github.event.client_payload.target_repo || 'openclaw/openclaw', github.event.client_payload.item_number || '?') }}
44

55
on:
66
repository_dispatch:
@@ -47,6 +47,7 @@ on:
4747
type: string
4848

4949
permissions:
50+
actions: read
5051
contents: read
5152
issues: write
5253
pull-requests: read
@@ -61,7 +62,42 @@ concurrency:
6162
cancel-in-progress: false
6263

6364
jobs:
65+
receipt:
66+
name: Deduplicate command dispatch receipt
67+
runs-on: ubuntu-latest
68+
outputs:
69+
proceed: ${{ steps.receipt.outputs.proceed }}
70+
steps:
71+
- uses: actions/checkout@v5
72+
with:
73+
sparse-checkout: scripts/dispatch-receipt-owner.sh
74+
sparse-checkout-cone-mode: false
75+
76+
- id: receipt
77+
env:
78+
DISPATCH_KEY: ${{ github.event.client_payload.dispatch_key || '' }}
79+
ITEM_NUMBER: ${{ github.event.client_payload.item_number || '?' }}
80+
TARGET_REPO: ${{ github.event.client_payload.target_repo || 'openclaw/openclaw' }}
81+
GH_TOKEN: ${{ github.token }}
82+
run: |
83+
set -euo pipefail
84+
if [ -z "$DISPATCH_KEY" ]; then
85+
echo "proceed=true" >> "$GITHUB_OUTPUT"
86+
exit 0
87+
fi
88+
expected_title="Assist ${TARGET_REPO}#${ITEM_NUMBER} [${DISPATCH_KEY}]"
89+
owner="$(bash scripts/dispatch-receipt-owner.sh \
90+
assist.yml "$expected_title" "$GITHUB_RUN_ID" assist)"
91+
if [ "$owner" = "owner" ]; then
92+
echo "proceed=false" >> "$GITHUB_OUTPUT"
93+
echo "An older active or successfully executed command dispatch already exists; skipping duplicate assist."
94+
exit 0
95+
fi
96+
echo "proceed=true" >> "$GITHUB_OUTPUT"
97+
6498
capacity:
99+
needs: receipt
100+
if: ${{ needs.receipt.outputs.proceed == 'true' }}
65101
runs-on: ubuntu-latest
66102
outputs:
67103
proceed: ${{ steps.limit.outputs.proceed }}

‎.github/workflows/repair-cluster-worker.yml‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name: repair cluster worker
22

3-
run-name: ${{ contains(inputs.job, '/inbox/issue-') && format('issue implementation {0}', inputs.job) || contains(inputs.job, '/inbox/automerge-') && format('automerge repair {0}', inputs.job) || format('repair cluster {0}', inputs.job) }}
3+
run-name: ${{ inputs.dispatch_key && format('{0} [{1}]', contains(inputs.job, '/inbox/issue-') && format('issue implementation {0}', inputs.job) || contains(inputs.job, '/inbox/automerge-') && format('automerge repair {0}', inputs.job) || format('repair cluster {0}', inputs.job), inputs.dispatch_key) || contains(inputs.job, '/inbox/issue-') && format('issue implementation {0}', inputs.job) || contains(inputs.job, '/inbox/automerge-') && format('automerge repair {0}', inputs.job) || format('repair cluster {0}', inputs.job) }}
44

55
on:
66
workflow_dispatch:
@@ -9,6 +9,11 @@ on:
99
description: "Job markdown path, for example jobs/openclaw/inbox/cluster-001.md"
1010
required: true
1111
type: string
12+
dispatch_key:
13+
description: "Optional command-router idempotency key"
14+
required: false
15+
default: ""
16+
type: string
1217
mode:
1318
description: "Worker mode"
1419
required: true
@@ -67,8 +72,50 @@ concurrency:
6772
cancel-in-progress: false
6873

6974
jobs:
75+
receipt:
76+
name: Deduplicate command dispatch receipt
77+
runs-on: ubuntu-latest
78+
permissions:
79+
actions: read
80+
contents: read
81+
outputs:
82+
proceed: ${{ steps.receipt.outputs.proceed }}
83+
steps:
84+
- uses: actions/checkout@v5
85+
with:
86+
sparse-checkout: scripts/dispatch-receipt-owner.sh
87+
sparse-checkout-cone-mode: false
88+
89+
- id: receipt
90+
env:
91+
DISPATCH_KEY: ${{ inputs.dispatch_key }}
92+
JOB_PATH: ${{ inputs.job }}
93+
GH_TOKEN: ${{ github.token }}
94+
run: |
95+
set -euo pipefail
96+
if [ -z "$DISPATCH_KEY" ]; then
97+
echo "proceed=true" >> "$GITHUB_OUTPUT"
98+
exit 0
99+
fi
100+
case "$JOB_PATH" in
101+
*/inbox/issue-*) title="issue implementation $JOB_PATH" ;;
102+
*/inbox/automerge-*) title="automerge repair $JOB_PATH" ;;
103+
*) title="repair cluster $JOB_PATH" ;;
104+
esac
105+
expected_title="${title} [${DISPATCH_KEY}]"
106+
owner="$(bash scripts/dispatch-receipt-owner.sh \
107+
repair-cluster-worker.yml "$expected_title" "$GITHUB_RUN_ID" "Plan and review cluster")"
108+
if [ "$owner" = "owner" ]; then
109+
echo "proceed=false" >> "$GITHUB_OUTPUT"
110+
echo "An older active or successfully executed command dispatch already exists; skipping duplicate repair."
111+
exit 0
112+
fi
113+
echo "proceed=true" >> "$GITHUB_OUTPUT"
114+
70115
cluster:
71116
name: Plan and review cluster
117+
needs: receipt
118+
if: ${{ needs.receipt.outputs.proceed == 'true' }}
72119
runs-on: ${{ inputs.runner }}
73120
timeout-minutes: 90
74121
outputs:

‎.github/workflows/sweep.yml‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,12 @@ run-name: >-
1616
(github.event_name == 'repository_dispatch' &&
1717
github.event.action == 'clawsweeper_target_sweep') &&
1818
format('Review target repo {0}', github.event.client_payload.target_repo || 'openclaw/openclaw') ||
19+
(github.event_name == 'repository_dispatch' && github.event.client_payload.dispatch_key != '') &&
20+
format('Review event item {0}#{1} [{2}]', github.event.client_payload.target_repo || 'openclaw/openclaw', github.event.client_payload.item_number || '?', github.event.client_payload.dispatch_key) ||
1921
github.event_name == 'repository_dispatch' &&
2022
format('Review event item {0}#{1}', github.event.client_payload.target_repo || 'openclaw/openclaw', github.event.client_payload.item_number || '?') ||
23+
(github.event_name == 'workflow_dispatch' && startsWith(github.event.inputs.item_numbers, 'router-')) &&
24+
format('Review event item {0}#{1} [{2}]', github.event.inputs.target_repo || 'openclaw/openclaw', github.event.inputs.item_number || '?', github.event.inputs.item_numbers) ||
2125
((github.event_name == 'workflow_dispatch' &&
2226
github.event.inputs.apply_existing == 'true' &&
2327
github.event.inputs.apply_sync_comments_only == 'true') ||
@@ -229,9 +233,12 @@ jobs:
229233
const payload = JSON.parse(process.env.CLIENT_PAYLOAD || "{}");
230234
const itemKind = payload.item_kind === "pull_request" ? "pull_request" : "issue";
231235
const sourceEvent = payload.source_event === "pull_request" ? "pull_request" : "issues";
236+
const dispatchKey = String(payload.dispatch_key || "").trim();
232237
process.stdout.write(
233238
JSON.stringify({
234-
delivery_id: `legacy:${process.env.GITHUB_RUN_ID}:${process.env.GITHUB_RUN_ATTEMPT}`,
239+
delivery_id: dispatchKey
240+
? `router:${dispatchKey}`
241+
: `legacy:${process.env.GITHUB_RUN_ID}:${process.env.GITHUB_RUN_ATTEMPT}`,
235242
decision: {
236243
targetRepo: payload.target_repo || "openclaw/openclaw",
237244
targetBranch: payload.target_branch || "main",
@@ -1157,7 +1164,9 @@ jobs:
11571164
BATCH_SIZE: ${{ steps.mode.outputs.batch_size }}
11581165
HOT_INTAKE: ${{ steps.mode.outputs.hot_intake }}
11591166
ITEM_NUMBER: ${{ github.event.inputs.item_number || '' }}
1160-
ITEM_NUMBERS: ${{ github.event.inputs.item_numbers || github.event.client_payload.item_number || '' }}
1167+
# A router fallback carries its receipt key in item_numbers because GitHub caps this
1168+
# workflow at 25 inputs; item_number remains the exact review target in that case.
1169+
ITEM_NUMBERS: ${{ (github.event.inputs.item_number != '' && startsWith(github.event.inputs.item_numbers, 'router-') && github.event.inputs.item_number) || github.event.inputs.item_numbers || github.event.client_payload.item_number || '' }}
11611170
MAX_PAGES: ${{ steps.mode.outputs.max_pages }}
11621171
MIN_ACTIVE_SHARDS: ${{ steps.mode.outputs.min_active_shards }}
11631172
MIN_BACKFILL_REVIEW_AGE_MINUTES: ${{ steps.mode.outputs.min_backfill_review_age_minutes }}

‎scripts/dispatch-receipt-owner.sh‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
4+
workflow="${1:?workflow file is required}"
5+
expected_title="${2:?expected run title is required}"
6+
current_run_id="${3:?current run id is required}"
7+
required_job_name="${4:?required worker job name is required}"
8+
9+
runs_json="$(gh api --method GET \
10+
"repos/${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is required}/actions/workflows/${workflow}/runs?per_page=100")"
11+
12+
active_owner_id="$(
13+
jq -r --arg title "$expected_title" --arg current "$current_run_id" '
14+
first(
15+
.workflow_runs[]
16+
| select(.display_title == $title and .id < ($current | tonumber))
17+
| select(.status == "queued" or .status == "in_progress" or .status == "waiting" or .status == "pending" or .status == "requested")
18+
| .id
19+
) // empty
20+
' <<<"$runs_json"
21+
)"
22+
if [ -n "$active_owner_id" ]; then
23+
printf 'owner\n'
24+
exit 0
25+
fi
26+
27+
successful_run_ids="$(
28+
jq -r --arg title "$expected_title" --arg current "$current_run_id" '
29+
.workflow_runs[]
30+
| select(.display_title == $title and .id < ($current | tonumber) and .conclusion == "success")
31+
| .id
32+
' <<<"$runs_json"
33+
)"
34+
while IFS= read -r run_id; do
35+
if [ -z "$run_id" ]; then
36+
continue
37+
fi
38+
jobs_json="$(gh api --method GET \
39+
"repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/jobs?per_page=100")"
40+
if jq -e --arg required "$required_job_name" \
41+
'any(.jobs[]; .name == $required and .conclusion == "success")' \
42+
<<<"$jobs_json" >/dev/null; then
43+
printf 'owner\n'
44+
exit 0
45+
fi
46+
done <<<"$successful_run_ids"
47+
48+
printf 'none\n'

‎src/repair/comment-router-utils.ts‎

Lines changed: 85 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,33 @@ const DEFAULT_IGNORED_CHECKS = [
1313
];
1414
const TRANSIENT_CANCELLED_CHECKS = new Set(["real behavior proof"]);
1515

16+
export function dispatchClaimLookupKeys(entry: LooseRecord) {
17+
const keys: string[] = [];
18+
const commentId = String(entry.comment_id ?? "").trim();
19+
const commentUpdatedAt = String(entry.comment_updated_at ?? "").trim();
20+
if (commentId && commentUpdatedAt) keys.push(`comment:${commentId}:${commentUpdatedAt}`);
21+
const idempotencyKey = String(entry.idempotency_key ?? "").trim();
22+
if (idempotencyKey) keys.push(`idempotency:${idempotencyKey}`);
23+
return keys;
24+
}
25+
26+
export function dispatchReceiptKeyMaterial(entry: LooseRecord, claim: LooseRecord | null) {
27+
const idempotencyKey = String(entry.idempotency_key ?? entry.comment_version_key ?? "unknown");
28+
if (entry.automation_source !== "repair_loop_label_sweep") return idempotencyKey;
29+
const attempt = String(
30+
claim?.processed_at ?? entry.processed_at ?? entry.comment_updated_at ?? "unknown-attempt",
31+
);
32+
return `${idempotencyKey}:${attempt}`;
33+
}
34+
35+
export function hasSuccessfulDispatchExecutionJob(jobs: LooseRecord[], requiredJobName: string) {
36+
return jobs.some(
37+
(job) =>
38+
String(job.name ?? "") === requiredJobName &&
39+
String(job.conclusion ?? "").toLowerCase() === "success",
40+
);
41+
}
42+
1643
export function summarizeChecks(checks: LooseRecord[]) {
1744
const ignored = ignoredCheckNames();
1845
const latestChecks = latestCheckRuns(checks);
@@ -115,6 +142,49 @@ export function shouldSuppressProcessedCommentVersion(entry: LooseRecord) {
115142
return true;
116143
}
117144

145+
export function dispatchClaimDecision({
146+
claim,
147+
runs,
148+
expectedTitle,
149+
nowMs = Date.now(),
150+
graceMs = 300_000,
151+
}: {
152+
claim: LooseRecord | null;
153+
runs: LooseRecord[];
154+
expectedTitle: string;
155+
nowMs?: number;
156+
graceMs?: number;
157+
}) {
158+
if (!claim) return { action: "dispatch", run: null };
159+
const normalizedGraceMs = Number.isFinite(graceMs) ? Math.max(0, graceMs) : 300_000;
160+
const claimedAtMs = Date.parse(String(claim.processed_at ?? ""));
161+
const matchingRuns = runs.filter((run) => {
162+
if (String(run.display_title ?? run.displayTitle ?? "") !== expectedTitle) return false;
163+
const createdAtMs = Date.parse(String(run.created_at ?? run.createdAt ?? ""));
164+
return (
165+
Number.isFinite(claimedAtMs) &&
166+
Number.isFinite(createdAtMs) &&
167+
createdAtMs >= claimedAtMs - 5_000
168+
);
169+
});
170+
const successfulRun = matchingRuns.find(
171+
(run) =>
172+
String(run.conclusion ?? "").toLowerCase() === "success" &&
173+
run.dispatch_execution_verified !== false,
174+
);
175+
if (successfulRun) return { action: "recover", run: successfulRun };
176+
const activeRun = matchingRuns.find((run) =>
177+
["queued", "in_progress", "waiting", "pending", "requested"].includes(
178+
String(run.status ?? "").toLowerCase(),
179+
),
180+
);
181+
if (activeRun) return { action: "wait", run: null };
182+
if (Number.isFinite(claimedAtMs) && nowMs - claimedAtMs >= normalizedGraceMs) {
183+
return { action: "dispatch", run: null };
184+
}
185+
return { action: "wait", run: null };
186+
}
187+
118188
export function sortCommentsForRouting(comments: LooseRecord[]) {
119189
return [...comments].sort((left: LooseRecord, right: LooseRecord) => {
120190
const leftTime = commentRoutingTime(left);
@@ -244,7 +314,9 @@ export function readLedger(file: JsonValue) {
244314

245315
export function appendLedger(current: LooseRecord, entries: LooseRecord[]) {
246316
const compact = entries
247-
.filter((entry: JsonValue) => ["executed", "skipped", "waiting"].includes(entry.status))
317+
.filter((entry: JsonValue) =>
318+
["claimed", "executed", "skipped", "waiting"].includes(entry.status),
319+
)
248320
.filter((entry: JsonValue) => !isNoopSkip(entry))
249321
.map((entry: JsonValue) => {
250322
const actions = compactLedgerActions(entry.actions);
@@ -271,7 +343,7 @@ export function appendLedger(current: LooseRecord, entries: LooseRecord[]) {
271343
expected_head_sha: entry.expected_head_sha ?? null,
272344
finding_id: entry.finding_id ?? null,
273345
status: entry.status,
274-
processed_at: new Date().toISOString(),
346+
processed_at: entry.processed_at ?? new Date().toISOString(),
275347
target: entry.target
276348
? {
277349
kind: entry.target.kind,
@@ -313,10 +385,20 @@ function isNoopSkip(entry: LooseRecord) {
313385
}
314386

315387
function stableLedgerEntry(entry: LooseRecord) {
316-
return JSON.stringify({ ...entry, processed_at: null });
388+
return JSON.stringify({
389+
...entry,
390+
processed_at: entry.status === "claimed" ? entry.processed_at : null,
391+
});
317392
}
318393

319394
function ledgerEntryKey(entry: LooseRecord) {
395+
if (
396+
!entry.comment_version_key &&
397+
entry.automation_source === "repair_loop_label_sweep" &&
398+
entry.idempotency_key
399+
) {
400+
return `idempotency:${entry.idempotency_key}`;
401+
}
320402
return (
321403
entry.comment_version_key ??
322404
`${entry.comment_id ?? "unknown"}:${entry.comment_updated_at ?? "unknown"}`

0 commit comments

Comments
 (0)