Skip to content

Commit 1d10be8

Browse files
committed
feat: adapt apply scan window
1 parent a397ae0 commit 1d10be8

7 files changed

Lines changed: 321 additions & 8 deletions

File tree

‎.github/workflows/sweep.yml‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2263,7 +2263,10 @@ jobs:
22632263
progress_every="10"
22642264
checkpoint_size="${{ github.event_name == 'workflow_dispatch' && github.event.inputs.apply_checkpoint_size || '5' }}"
22652265
comment_sync_processed_limit=1000
2266-
close_processed_limit=300
2266+
base_close_processed_limit=300
2267+
max_close_processed_limit=900
2268+
close_processed_limit="$base_close_processed_limit"
2269+
adaptive_apply_scan_reason="base_window"
22672270
sync_batch_size="${{ github.event_name == 'workflow_dispatch' && github.event.inputs.apply_limit || '25' }}"
22682271
item_numbers="${{ github.event_name == 'repository_dispatch' && github.event.client_payload.item_number || github.event.inputs.apply_item_numbers || '' }}"
22692272
sync_open_pr_batch="${{ github.event_name == 'schedule' && github.event.schedule == '6,21,36,51 * * * *' && 'true' || 'false' }}"
@@ -2311,6 +2314,17 @@ jobs:
23112314
echo "Capping apply checkpoint size at 5 to keep each GitHub App token within its lifetime."
23122315
checkpoint_size=5
23132316
fi
2317+
if [ "$sync_comments_only" != "true" ] && [ -z "$item_numbers" ]; then
2318+
mkdir -p .artifacts
2319+
adaptive_batch_env=".artifacts/apply-adaptive-batch.env"
2320+
pnpm run --silent workflow -- adaptive-apply-batch-size \
2321+
--status-path "results/sweep-status/${target_slug}.json" \
2322+
--base-size "$base_close_processed_limit" \
2323+
--max-size "$max_close_processed_limit" > "$adaptive_batch_env"
2324+
cat "$adaptive_batch_env"
2325+
close_processed_limit="$(awk -F= '$1 == "close_processed_limit" { print $2 }' "$adaptive_batch_env")"
2326+
adaptive_apply_scan_reason="$(awk -F= '$1 == "adaptive_apply_scan_reason" { print $2 }' "$adaptive_batch_env")"
2327+
fi
23142328
mkdir -p .artifacts/apply-reports
23152329
publish_changes() {
23162330
message="$1"
@@ -2430,7 +2444,7 @@ jobs:
24302444
if [ "$proposed_count" -lt "$limit" ]; then
24312445
limit="$proposed_count"
24322446
fi
2433-
echo "Auto-selected $proposed_count proposed close candidate(s) from apply cursor window: $item_numbers; apply-ready count: ${apply_ready_count:-unknown}"
2447+
echo "Auto-selected $proposed_count proposed close candidate(s) from $close_processed_limit-record apply cursor window ($adaptive_apply_scan_reason): $item_numbers; apply-ready count: ${apply_ready_count:-unknown}"
24342448
fi
24352449
fi
24362450
item_numbers_arg=()
@@ -2466,7 +2480,7 @@ jobs:
24662480
pnpm run status -- \
24672481
--target-repo "$TARGET_REPO" \
24682482
--state "Apply in progress" \
2469-
--detail "Starting apply/comment-sync run for up to $limit fresh $apply_kind closes. Close reasons: $apply_close_reasons. Existing Codex automated review comments are updated in place when closing or when comment-only sync is stale by ${comment_sync_min_age_days} day(s); checkpoints commit every $checkpoint_size fresh closes; close delay is ${close_delay_ms}ms; sync-comments-only=$sync_comments_only; item numbers=${item_numbers:-all}." \
2483+
--detail "Starting apply/comment-sync run for up to $limit fresh $apply_kind closes. Close reasons: $apply_close_reasons. Scan window: $close_processed_limit records ($adaptive_apply_scan_reason). Existing Codex automated review comments are updated in place when closing or when comment-only sync is stale by ${comment_sync_min_age_days} day(s); checkpoints commit every $checkpoint_size fresh closes; close delay is ${close_delay_ms}ms; sync-comments-only=$sync_comments_only; item numbers=${item_numbers:-all}." \
24702484
--run-url "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
24712485
if ! publish_changes "chore: mark sweep apply in progress" records results/sweep-status; then
24722486
echo "Best-effort apply start status update failed"
@@ -2659,6 +2673,8 @@ jobs:
26592673
echo "APPLY_SYNC_OPEN_PR_BATCH=$sync_open_pr_batch"
26602674
echo "APPLY_AUTO_SELECTED_BATCH=$auto_selected_apply_batch"
26612675
echo "APPLY_COMMENT_SYNC_MIN_AGE_DAYS=$comment_sync_min_age_days"
2676+
echo "APPLY_CLOSE_PROCESSED_LIMIT=$close_processed_limit"
2677+
echo "APPLY_ADAPTIVE_SCAN_REASON=$adaptive_apply_scan_reason"
26622678
} >> "$GITHUB_ENV"
26632679
26642680
- name: Commit apply results

‎docs/scheduler.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,15 @@ continuation with a fresh GitHub App token after any checkpoint that closes at
459459
least one item. A saturated scan that closes nothing stops without chaining so
460460
the same records cannot create an unbounded runner loop.
461461

462+
Untargeted cursor-based close apply starts with a 300-record scan window. If
463+
the previous cursor window was a full close-mode scan, closed nothing, skipped
464+
at least 80% of processed records, and did not hit a live-fetch, runtime-budget,
465+
or missing-cursor failure, the next automatic window expands to inspect more
466+
records, capped at 900. This changes only the deterministic scan window:
467+
`apply_limit`, checkpoint size, close gates, live-state checks, and maintainer
468+
policy gates stay unchanged. The workflow logs and sweep status detail include
469+
the selected scan window and reason.
470+
462471
## Continuation and Recovery
463472

464473
When a normal or hot review run fills its planned capacity, the publish job

‎src/clawsweeper.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -760,6 +760,7 @@ interface WorkflowStatusSummary {
760760
detail: string;
761761
runUrl: string | undefined;
762762
applyHealth: Record<string, unknown> | undefined;
763+
lastCloseApplyHealth: Record<string, unknown> | undefined;
763764
plannedCount: number | undefined;
764765
plannedCapacity: number | undefined;
765766
plannedShards: number | undefined;
@@ -1923,10 +1924,14 @@ function writeSweepStatus(options: {
19231924
}): void {
19241925
const profile = options.profile ?? targetProfile();
19251926
const updatedAt = new Date().toISOString();
1927+
const previousStatus = readSweepStatusSummary(profile);
19261928
const applyHealth =
1927-
options.applyHealth === undefined
1928-
? readSweepStatusSummary(profile)?.applyHealth
1929-
: options.applyHealth;
1929+
options.applyHealth === undefined ? previousStatus?.applyHealth : options.applyHealth;
1930+
const previousCloseApplyHealth =
1931+
previousStatus?.lastCloseApplyHealth ??
1932+
(previousStatus?.applyHealth?.mode === "close" ? previousStatus.applyHealth : undefined);
1933+
const lastCloseApplyHealth =
1934+
applyHealth && applyHealth.mode === "close" ? applyHealth : previousCloseApplyHealth;
19301935
const payload = {
19311936
schema_version: 1,
19321937
slug: profile.slug,
@@ -1949,6 +1954,7 @@ function writeSweepStatus(options: {
19491954
bot_owned_proof_decisions_requested: options.botOwnedProofDecisionsRequested ?? null,
19501955
bot_owned_proof_dispatches: options.botOwnedProofDispatches ?? null,
19511956
apply_health: applyHealth ?? null,
1957+
last_close_apply_health: lastCloseApplyHealth ?? null,
19521958
updated_at: updatedAt,
19531959
};
19541960
const outputPath = sweepStatusPath(profile);
@@ -8294,6 +8300,7 @@ function readSweepStatusSummary(profile = targetProfile()): WorkflowStatusSummar
82948300
detail: stringOrUndefined(parsed.detail) ?? "No workflow status has been published yet.",
82958301
runUrl: stringOrUndefined(parsed.run_url),
82968302
applyHealth: recordOrUndefined(parsed.apply_health),
8303+
lastCloseApplyHealth: recordOrUndefined(parsed.last_close_apply_health),
82978304
plannedCount: numberOrUndefined(parsed.planned_count),
82988305
plannedCapacity: numberOrUndefined(parsed.planned_capacity),
82998306
plannedShards: numberOrUndefined(parsed.planned_shards),
@@ -8388,6 +8395,7 @@ function workflowStatusSummary(block: string): WorkflowStatusSummary {
83888395
detail,
83898396
runUrl,
83908397
applyHealth: undefined,
8398+
lastCloseApplyHealth: undefined,
83918399
plannedCount: numberOrUndefined(planMatch?.[1]),
83928400
plannedShards: numberOrUndefined(planMatch?.[2]),
83938401
plannedCapacity: numberOrUndefined(planMatch?.[3]),

‎src/repair/workflow-utils.ts‎

Lines changed: 135 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,25 @@ type ApplyCycleSummary = {
102102
scheduled_interval_minutes: number | null;
103103
label: string;
104104
};
105+
106+
type AdaptiveApplyBatchSizeOptions = {
107+
statusPath: string;
108+
baseSize: number;
109+
maxSize: number;
110+
};
111+
112+
type AdaptiveApplyBatchSize = {
113+
closeProcessedLimit: number;
114+
baseCloseProcessedLimit: number;
115+
maxCloseProcessedLimit: number;
116+
adaptive: boolean;
117+
reason: string;
118+
previousProcessed: number | null;
119+
previousProcessedLimit: number | null;
120+
previousClosed: number | null;
121+
previousSkipped: number | null;
122+
};
123+
105124
const args = parseArgs(process.argv.slice(2));
106125

107126
function runCli(): void {
@@ -158,6 +177,25 @@ function runCli(): void {
158177
)}\n`,
159178
);
160179
break;
180+
case "adaptive-apply-batch-size": {
181+
const result = adaptiveApplyBatchSize({
182+
statusPath: requiredString("status-path"),
183+
baseSize: numberArg("base-size", 300),
184+
maxSize: numberArg("max-size", 900),
185+
});
186+
printOutput({
187+
close_processed_limit: String(result.closeProcessedLimit),
188+
base_close_processed_limit: String(result.baseCloseProcessedLimit),
189+
max_close_processed_limit: String(result.maxCloseProcessedLimit),
190+
adaptive_apply_scan: result.adaptive ? "true" : "false",
191+
adaptive_apply_scan_reason: result.reason,
192+
previous_apply_processed: optionalNumberOutput(result.previousProcessed),
193+
previous_apply_processed_limit: optionalNumberOutput(result.previousProcessedLimit),
194+
previous_apply_closed: optionalNumberOutput(result.previousClosed),
195+
previous_apply_skipped: optionalNumberOutput(result.previousSkipped),
196+
});
197+
break;
198+
}
161199
case "count-command-actions":
162200
console.log(
163201
countCommandActions(
@@ -308,6 +346,89 @@ function defaultCapacityReason(
308346
return "under capacity: due backlog below planned capacity";
309347
}
310348

349+
export function adaptiveApplyBatchSize(
350+
options: AdaptiveApplyBatchSizeOptions,
351+
): AdaptiveApplyBatchSize {
352+
const baseSize = positiveInteger(options.baseSize, "baseSize");
353+
const maxSize = Math.max(baseSize, positiveInteger(options.maxSize, "maxSize"));
354+
const base: AdaptiveApplyBatchSize = {
355+
closeProcessedLimit: baseSize,
356+
baseCloseProcessedLimit: baseSize,
357+
maxCloseProcessedLimit: maxSize,
358+
adaptive: false,
359+
reason: "base_window",
360+
previousProcessed: null,
361+
previousProcessedLimit: null,
362+
previousClosed: null,
363+
previousSkipped: null,
364+
};
365+
const status = readJsonObjectIfPresent(options.statusPath);
366+
if (!status) return base;
367+
const health = closeApplyHealthFromStatus(status);
368+
if (!health) return base;
369+
const previousProcessed = nonNegativeIntegerOrNull(health.processed);
370+
const previousProcessedLimit = nonNegativeIntegerOrNull(health.processed_limit);
371+
const previousClosed = nonNegativeIntegerOrNull(health.closed);
372+
const previousSkipped = nonNegativeIntegerOrNull(health.skipped);
373+
const withPrevious = {
374+
...base,
375+
previousProcessed,
376+
previousProcessedLimit,
377+
previousClosed,
378+
previousSkipped,
379+
};
380+
if (health.cursor_required !== true) return withPrevious;
381+
if (
382+
previousProcessed === null ||
383+
previousProcessedLimit === null ||
384+
previousClosed === null ||
385+
previousSkipped === null
386+
) {
387+
return withPrevious;
388+
}
389+
390+
const fullWindow = previousProcessedLimit > 0 && previousProcessed >= previousProcessedLimit;
391+
const zeroClose = previousClosed === 0;
392+
const skipHeavy = previousProcessed > 0 && previousSkipped / previousProcessed >= 0.8;
393+
const attentionReasons = new Set(stringArray(health.attention_reasons));
394+
const unsafeAttention = [
395+
"cursor_required_but_missing_after_full_window",
396+
"skipped_live_fetch_failed",
397+
"skipped_runtime_budget",
398+
].some((reason) => attentionReasons.has(reason));
399+
if (!fullWindow || !zeroClose || !skipHeavy || unsafeAttention) return withPrevious;
400+
401+
const grown = Math.min(maxSize, Math.max(baseSize, previousProcessedLimit * 2));
402+
if (grown <= baseSize) return withPrevious;
403+
return {
404+
...withPrevious,
405+
closeProcessedLimit: grown,
406+
adaptive: true,
407+
reason: "previous_full_zero_close_skip_window",
408+
};
409+
}
410+
411+
function closeApplyHealthFromStatus(status: LooseRecord): LooseRecord | null {
412+
const current = recordOrNull(status.apply_health);
413+
if (current?.mode === "close") return current;
414+
const preserved = recordOrNull(status.last_close_apply_health);
415+
return preserved?.mode === "close" ? preserved : null;
416+
}
417+
418+
function optionalNumberOutput(value: number | null): string {
419+
return value === null ? "" : String(value);
420+
}
421+
422+
function positiveInteger(value: number, name: string): number {
423+
if (!Number.isInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
424+
return value;
425+
}
426+
427+
function nonNegativeIntegerOrNull(value: JsonValue | undefined): number | null {
428+
const parsed = Number(value);
429+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
430+
}
431+
311432
export function plannedItemNumberCsv(plan: LooseRecord): string {
312433
const candidates: JsonValue[] = Array.isArray(plan.candidates) ? plan.candidates : [];
313434
return candidates
@@ -1359,6 +1480,19 @@ function readJsonObject(filePath: string): LooseRecord {
13591480
return parsed;
13601481
}
13611482

1483+
function readJsonObjectIfPresent(filePath: string): LooseRecord | null {
1484+
if (!filePath || !fs.existsSync(filePath)) return null;
1485+
try {
1486+
return readJsonObject(filePath);
1487+
} catch {
1488+
return null;
1489+
}
1490+
}
1491+
1492+
function recordOrNull(value: JsonValue | undefined): LooseRecord | null {
1493+
return isJsonObject(value) ? value : null;
1494+
}
1495+
13621496
function printOutput(values: Record<string, string>): void {
13631497
for (const [key, value] of Object.entries(values)) console.log(`${key}=${value}`);
13641498
}
@@ -1416,7 +1550,7 @@ function positiveNumber(value: string, fallback: number): number {
14161550
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
14171551
}
14181552

1419-
function stringArray(value: JsonValue): string[] {
1553+
function stringArray(value: JsonValue | undefined): string[] {
14201554
return Array.isArray(value)
14211555
? value.filter((entry): entry is string => typeof entry === "string")
14221556
: [];

‎test/clawsweeper.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1996,6 +1996,9 @@ test("sweep status writer preserves non-apply health and clears stale apply upda
19961996
/state\.startsWith\("Apply "\)\s+\?\s+null\s+:\s+readSweepStatusSummary\(profile\)\?\.applyHealth/,
19971997
);
19981998
assert.match(source, /apply_health: applyHealth \?\? null/);
1999+
assert.match(source, /last_close_apply_health: lastCloseApplyHealth \?\? null/);
2000+
assert.match(source, /previousStatus\?\.lastCloseApplyHealth/);
2001+
assert.match(source, /previousStatus\?\.applyHealth\?\.mode === "close"/);
19992002
});
20002003

20012004
test("review parser strips environment access caveats from risks", () => {

0 commit comments

Comments
 (0)