Skip to content

Commit f68acbe

Browse files
authored
fix(klaud): harden validation and recovery, speed up planning and wakes / fix(klaud):加固验证与恢复,加速规划与唤醒 (#4633)
* fix(klaud): harden validation and recovery, speed up planning and wakes / fix(klaud):加固验证与恢复,加速规划与唤醒 * fix(klaud): measure starvation per attempt and keep deferred resumes and curve holds / fix(klaud):按尝试计算排队饥饿并保留延迟恢复与曲线暂缓
1 parent 055e66e commit f68acbe

18 files changed

Lines changed: 2869 additions & 405 deletions

‎.github/klaud-candidate-prompt.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,8 @@ Keep targeted work draft with no sweep labels. Dispatch ONLY updated-image e2e-t
123123
from main, with ref=exact measured SHA, fail-fast=true, klaud-run=true,
124124
test-name=$KLAUD_TEST_NAME, and
125125
`generate-cli-command="test-config --config-files FILE --config-keys KEY... --scenario-type agentic-coding --smoke"`,
126-
listing every family key after `--config-keys`.
126+
listing every family key after `--config-keys`. Add agentx-fast=true only to this `--smoke`
127+
dispatch (20-minute profile). Never pass it to a sweep without `--smoke` or to the final sweep.
127128
Autosweeps cover only the family's AgentX (agentic-coding) points; never run fixed-seq-len points.
128129
Smoke retains minimum-concurrency throughput and canonical representative eval concurrency;
129130
it is startup evidence, not a full curve. When candidate.json has `smoke-covers-full: true`, the
@@ -202,7 +203,11 @@ appear once. Use exact 8k/1k lengths, unambiguous point labels, `110 (+10%)`, la
202203
↑/↓ headers and `97% (+0.50 pp)` evals with sample counts. Omit Result/Coverage/Finding,
203204
legends, boilerplate, limitations and redundant milestones. Briefly note failures and N/A
204205
reasons; preserve sources and uncertainty. Report observations on material changes or after
205-
30 minutes waiting. Improvement is best effort; there is no regression rejection gate.
206+
30 minutes waiting. Improvement is best effort, but final-sweep validation (never smoke) blocks
207+
validated when a matched point's output tok/s/GPU falls over 30% below baseline or has no
208+
baseline throughput, any point's request errors exceed 5%, or an eval falls below half its
209+
baseline score or below 50% for gsm8k and the Kimi/MiniMax tool-call suites;
210+
repair within budget, else finish failed with the affected points.
206211

207212
On terminal resolve/baseline evidence, stop investigating. Finalize attempts; the final
208213
attempt's Next states why you stopped, because finish shows it as the closing reason. Write
@@ -219,9 +224,8 @@ can be established). Select the first actual blocker, not a guessed cause. A fai
219224
baseline work belongs in `resolve`, and a failed updated-image run belongs in `targeted` or
220225
`final-sweep`. Do not put free text, raw responses, private telemetry or transcripts in the
221226
code. The fixed code appears in sanitized diagnostics and the completion report.
222-
After finish returns a verified `validated` outcome, check for an existing exact `/use
223-
<verified-final-run-id>` comment, then post it once on this PR. Never post `/use` for any
224-
other outcome or any run except the verified final sweep.
227+
For a verified `validated` outcome, finish itself posts `/use <verified-final-run-id>` once on
228+
this PR. Never post `/use` yourself.
225229
Otherwise finish reports the failure/deferral, cancels owned work, confirms every job
226230
terminal, removes sweep labels, drafts/closes the PR, deletes the candidate branch and releases
227231
the family claim so a later wave may retry it. Pending cleanup means wait and retry finish.

‎.github/workflows/klaud-candidate.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ jobs:
141141
}]}],
142142
"PostToolUse": [{"hooks": [{
143143
"type": "command",
144-
"command": "cd \"$GITHUB_WORKSPACE\" && uv run --project \"$INFERENCEX_TOOLING_PROJECT\" --locked python -P -m infx.klaud check-deadline"
144+
"command": "s=\"${KLAUD_SESSION_STARTED:-}\"; [ -n \"$s\" ] || exit 0; e=$(($(date +%s) - s)); [ \"$e\" -ge 18000 ] || exit 0; m=$(((19800 - e) / 60)); [ \"$m\" -ge 0 ] || m=0; printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PostToolUse\",\"additionalContext\":\"About %s minutes remain in this session. Publish attempt reports for owned runs now, then run park, or finish if the outcome is terminal, and end with StructuredOutput.\"}}\\n' \"$m\""
145145
}]}]
146146
}
147147
}
@@ -163,7 +163,7 @@ jobs:
163163
KLAUD_EXECUTION: ${{ steps.claude.outputs.execution_file }}
164164
run: |
165165
execution="${KLAUD_EXECUTION:-$RUNNER_TEMP/claude-execution-output.json}"
166-
used=false
166+
used=true
167167
if [[ -f "$execution" ]]; then
168168
used=$(jq 'any(.[]?; .type == "assistant" and any(.message.content[]?; .type == "tool_use"))' "$execution")
169169
fi

‎.github/workflows/klaud-plan.yml‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@ name: Klaud Cold auto-sweep
22
run-name: >-
33
${{ inputs.resume-parent && format('Klaud Cold resume {0} {1} session {2}',
44
inputs.resume-parent, inputs.resume-candidate, inputs.resume-session)
5-
|| (github.event.schedule == '30 * * * *' || inputs.wake) && 'Klaud Cold wake'
5+
|| (github.event.schedule == '47 * * * *' || inputs.wake) && 'Klaud Cold wake'
66
|| 'Klaud Cold auto-sweep' }}
77
8-
# Wakes, dispatched by klaud-wake.yml when a Klaud-owned run ends or scheduled hourly as a
9-
# backstop, share one group: one runs and one waits, so a burst collapses into a single recovery
10-
# pass. Every other run is its own group, so the 4-hourly auto-sweep's recover can overlap a wake
11-
# pass. Recovery leases keep two passes off the same candidate.
8+
# Wakes, dispatched by klaud-wake.yml when a Klaud-owned run ends or a delayed rerun is due, or
9+
# scheduled hourly as a backstop, collapse bursts: a wake for one candidate shares that
10+
# candidate's group and full passes share another, where one runs, one waits and a newer waiting
11+
# pass replaces an older one. Passes of one group cover the same candidates, so a replaced wake
12+
# loses none. Every other run is its own group, so the 4-hourly auto-sweep's recover can overlap
13+
# a wake pass. Recovery leases keep two passes off the same candidate.
1214
concurrency:
13-
group: ${{ (inputs.wake || github.event.schedule == '30 * * * *') && 'klaud-wake' || github.run_id }}
15+
group: >-
16+
${{ (inputs.wake || github.event.schedule == '47 * * * *')
17+
&& format('klaud-wake-{0}', inputs.wake && inputs.wake-candidate || 'all') || github.run_id }}
1418
cancel-in-progress: false
1519

1620
on: # zizmor: ignore[concurrency-limits]
@@ -32,9 +36,13 @@ on: # zizmor: ignore[concurrency-limits]
3236
description: Recovery-only pass, dispatched when a Klaud-owned run ends
3337
type: boolean
3438
default: false
39+
wake-candidate:
40+
description: Candidate the wake reconciles alone; empty for every candidate
41+
type: string
42+
default: ''
3543
schedule:
36-
- cron: '0 */4 * * *'
37-
- cron: '30 * * * *'
44+
- cron: '17 */4 * * *'
45+
- cron: '47 * * * *'
3846

3947
permissions:
4048
contents: read
@@ -97,16 +105,21 @@ jobs:
97105
env:
98106
GH_TOKEN: ${{ secrets.AGENT_PAT }} # zizmor: ignore[secrets-outside-env]
99107
KLAUD_STATUS_TOKEN: ${{ github.token }}
108+
WAKE_CANDIDATE: ${{ inputs.wake && inputs.wake-candidate || '' }}
100109
run: |
101-
uv run --project "$INFERENCEX_PYTHON_PROJECT" --locked python -m infx.klaud recover --max-sessions "$MAX_CANDIDATES_PER_RUN"
110+
uv run --project "$INFERENCEX_PYTHON_PROJECT" --locked python -m infx.klaud recover --max-sessions "$MAX_CANDIDATES_PER_RUN" ${WAKE_CANDIDATE:+--candidate "$WAKE_CANDIDATE"}
102111
if [[ -f "$RUNNER_TEMP/klaud-recovery.json" ]]; then
103112
echo "blocked-families=$(jq -c . "$RUNNER_TEMP/klaud-recovery.json")" >> "$GITHUB_OUTPUT"
104113
fi
105114
106115
review:
107116
name: Review candidate overlap
108117
needs: recover
109-
if: github.event.schedule != '30 * * * *' && !inputs.wake && needs.recover.outputs.deferred != 'true'
118+
# A job-level if cannot read env, so 5 is MAX_CANDIDATES_PER_RUN. With no free slot the wave
119+
# skips review and selection.
120+
if: >-
121+
github.event.schedule != '47 * * * *' && !inputs.wake && needs.recover.outputs.deferred != 'true'
122+
&& fromJSON(needs.recover.outputs.active-sessions || '0') < 5
110123
runs-on: ubuntu-latest
111124
permissions:
112125
contents: read
@@ -147,11 +160,15 @@ jobs:
147160
env:
148161
GH_TOKEN: ${{ github.token }}
149162
KLAUD_DASHBOARD_API_KEY: ${{ secrets.DASH_API_KEY }} # zizmor: ignore[secrets-outside-env]
163+
KLAUD_REQUEUE_TOKEN: ${{ secrets.AGENT_PAT }} # zizmor: ignore[secrets-outside-env]
164+
KLAUD_ACTIVE_SESSIONS: ${{ needs.recover.outputs.active-sessions }}
150165
run: >-
151166
uv run --project "$INFERENCEX_PYTHON_PROJECT" --locked python -m infx.klaud plan
152167
--directory "$RUNNER_TEMP/klaud"
153168
--review-batch-size "$REVIEW_BATCH_SIZE"
154169
--cooldown-hours "$CANDIDATE_COOLDOWN_HOURS"
170+
--max-candidates-per-run "$MAX_CANDIDATES_PER_RUN"
171+
--active-sessions "${KLAUD_ACTIVE_SESSIONS:-0}"
155172
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
156173
with:
157174
name: klaud-review-input

‎.github/workflows/klaud-wake.yml‎

Lines changed: 86 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,46 @@
11
name: Klaud Cold wake on run end
2-
run-name: Klaud Cold wake on run end - ${{ github.event.workflow_run.display_title }}
2+
run-name: >-
3+
${{ github.event_name == 'workflow_dispatch'
4+
&& format('Klaud Cold wake at {0} - {1}', inputs.not-before, inputs.candidate)
5+
|| format('Klaud Cold wake on run end - {0}', github.event.workflow_run.display_title) }}
36
47
# A parked Klaud session resumes only after recovery sees its owned runs end. Rather than wait
5-
# for the hourly :30 wake, start a recovery-only planner pass as soon as a Klaud-owned
6-
# targeted run (e2e Test - klaud-*) or PR sweep (klaud/auto-* branch) completes, unless another
7-
# run of that candidate is still active and will wake recovery when it ends. No checkout and no
8-
# event data reaches a shell: the event gates the job and the pinned script reads it as data.
8+
# for the hourly :47 wake, start a recovery-only planner pass for the candidate as soon as a
9+
# Klaud-owned targeted run (e2e Test - klaud-*) or PR sweep (klaud/auto-* branch) completes,
10+
# unless its session's agent is still running and sees the end itself, or another of its runs is still
11+
# active and will wake recovery when it ends. Recovery dispatches this workflow for a rerun it
12+
# holds until a set time (a parked infrastructure rerun, or a preempted run's grace period); that
13+
# run sleeps until then and wakes recovery for the candidate. No checkout and no event data
14+
# reaches a shell: the event gates the job and the pinned script reads it as data.
915
on: # zizmor: ignore[concurrency-limits]
1016
workflow_run: # zizmor: ignore[dangerous-triggers] runs no code from the triggering run
1117
workflows: [End-to-End Tests, Run Sweep]
1218
types: [completed]
19+
workflow_dispatch:
20+
inputs:
21+
candidate:
22+
description: Candidate whose recovery wakes at not-before
23+
type: string
24+
required: true
25+
not-before:
26+
description: When to wake recovery, an ISO 8601 time at most 4 hours ahead
27+
type: string
28+
required: true
1329

1430
permissions: {}
1531

1632
jobs:
1733
wake:
1834
name: Wake Klaud recovery
1935
if: >-
20-
github.event.workflow_run.head_repository.full_name == github.repository
36+
github.event_name == 'workflow_run'
37+
&& github.event.workflow_run.head_repository.full_name == github.repository
2138
&& github.event.workflow_run.conclusion != 'skipped'
2239
&& (startsWith(github.event.workflow_run.display_title, 'e2e Test - klaud-')
2340
|| startsWith(github.event.workflow_run.head_branch, 'klaud/auto-'))
2441
runs-on: ubuntu-latest
2542
permissions:
26-
actions: write # Read the candidate's runs and dispatch the planner's recovery-only wake.
43+
actions: write # Read the candidate's runs and jobs and dispatch the planner's recovery-only wake.
2744
steps:
2845
- name: Dispatch a recovery-only planner pass
2946
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
@@ -35,20 +52,23 @@ jobs:
3552
new RegExp(`^klaud/auto-(${id})$`).exec(ended.head_branch ?? '')
3653
?? new RegExp(`^e2e Test - klaud-\\d+-(${id})$`).exec(ended.display_title)
3754
)?.[1];
55+
const inputs = { wake: 'true' };
3856
if (candidate) {
3957
const branch = `klaud/auto-${candidate}`;
4058
const title = new RegExp(`^e2e Test - klaud-\\d+-${candidate}$`);
59+
const statuses = ['requested', 'waiting', 'pending', 'queued', 'in_progress'];
4160
const runs = (workflow, filters) => github.paginate(
4261
github.rest.actions.listWorkflowRuns,
4362
{ ...context.repo, workflow_id: workflow, per_page: 100, ...filters },
4463
);
45-
const [targeted, sweeps] = await Promise.all([
46-
Promise.all(['requested', 'waiting', 'pending', 'queued', 'in_progress'].map(
64+
const [targeted, sweeps, plans] = await Promise.all([
65+
Promise.all(statuses.map(
4766
(status) => runs('e2e-tests.yml', {
4867
actor: 'Klaud-Cold', event: 'workflow_dispatch', status,
4968
}),
5069
)),
5170
runs('run-sweep.yml', { branch }),
71+
Promise.all(statuses.map((status) => runs('klaud-plan.yml', { status }))),
5272
]);
5373
const active = [
5474
...targeted.flat().filter((run) => title.test(run.display_title)),
@@ -58,7 +78,63 @@ jobs:
5878
core.info(`Run ${active.id} of candidate ${candidate} is still active; its end wakes recovery.`);
5979
return;
6080
}
81+
const jobs = await Promise.all(plans.flat().map((run) => github.paginate(
82+
github.rest.actions.listJobsForWorkflowRun,
83+
{ ...context.repo, run_id: run.id, per_page: 100 },
84+
)));
85+
const running = jobs.flat().filter(
86+
(job) => job.name.startsWith(`Run candidate ${candidate}`) && job.status !== 'completed',
87+
);
88+
const agent = running.find((job) => !(job.steps ?? []).some(
89+
(step) => step.name === 'Let Klaud Cold own the candidate PR' && step.status === 'completed',
90+
));
91+
if (agent) {
92+
core.info(`Session job ${agent.id} of candidate ${candidate} is still running its agent; it sees the run end.`);
93+
return;
94+
}
95+
// Recovery skips a session whose job still runs, so let its cleanup steps finish first (up to 10 minutes).
96+
for (const job of running) {
97+
for (let poll = 0; poll < 40; poll += 1) {
98+
await new Promise((resolve) => setTimeout(resolve, 15000));
99+
const { data } = await github.rest.actions.getJobForWorkflowRun({ ...context.repo, job_id: job.id });
100+
if (data.status === 'completed') break;
101+
}
102+
}
103+
inputs['wake-candidate'] = candidate;
104+
}
105+
await github.rest.actions.createWorkflowDispatch({
106+
...context.repo, workflow_id: 'klaud-plan.yml', ref: 'main', inputs,
107+
});
108+
109+
due:
110+
name: Wake Klaud recovery when a rerun is due
111+
if: >-
112+
github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main'
113+
&& github.actor == 'Klaud-Cold'
114+
runs-on: ubuntu-latest
115+
timeout-minutes: 250
116+
# Every pass that holds the same rerun asks for the same wake; keep only the newest.
117+
concurrency:
118+
group: klaud-due-wake-${{ inputs.candidate }}-${{ inputs.not-before }}
119+
cancel-in-progress: true
120+
permissions:
121+
actions: write # Dispatch the planner's recovery-only wake.
122+
steps:
123+
- name: Dispatch a recovery-only planner pass at not-before
124+
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
125+
env:
126+
CANDIDATE: ${{ inputs.candidate }}
127+
NOT_BEFORE: ${{ inputs.not-before }}
128+
with:
129+
script: |
130+
const { CANDIDATE: candidate, NOT_BEFORE: notBefore } = process.env;
131+
const wait = Date.parse(notBefore) - Date.now();
132+
if (!/^[0-9a-f]{16}-[0-9a-f]{16}$/.test(candidate) || !(wait <= 4 * 60 * 60 * 1000)) {
133+
core.setFailed(`No wake for candidate ${candidate} at ${notBefore}: invalid or over 4 hours ahead.`);
134+
return;
61135
}
136+
await new Promise((resolve) => setTimeout(resolve, Math.max(wait, 0)));
62137
await github.rest.actions.createWorkflowDispatch({
63-
...context.repo, workflow_id: 'klaud-plan.yml', ref: 'main', inputs: { wake: 'true' },
138+
...context.repo, workflow_id: 'klaud-plan.yml', ref: 'main',
139+
inputs: { wake: 'true', 'wake-candidate': candidate },
64140
});

0 commit comments

Comments
 (0)