Skip to content

Commit 9725dab

Browse files
authored
Fix/scheduler duplicate candidate stranding (#1046)
* fix(src/scheduler-policy.ts): fixing the problem of scheduler duplicate-candidate stranding * test(test/scheduler-policy.test.ts): adding some edge case tests for fixed problem * docs(docs/proof/scheduler-duplicate-candidate-stranding): adding the bug proofs for clawsweeper * docs(docs/proof/scheduler-duplicate-candidate-stranding): fixing up the problems of proofing clawsweeper
1 parent 86d9741 commit 9725dab

4 files changed

Lines changed: 436 additions & 4 deletions

File tree

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
# Scheduler duplicate-candidate stranding proof contract
2+
3+
## Claim
4+
5+
`selectDueCandidates` fills the review batch up to capacity from the candidates
6+
it is given, even when the same item appears more than once in the due list.
7+
Before this change, a run of duplicates could end selection early and strand
8+
every remaining candidate while capacity was still free.
9+
10+
## Exercised surface
11+
12+
`run-proof.sh` drives the real `plan` CLI end to end — **no application function
13+
is substituted**:
14+
15+
```
16+
node dist/clawsweeper.js plan
17+
-> createReviewPlanningSelection().selectCandidates()
18+
-> fetchOpenItemPage() -> ghJsonLines() -> spawnSync -> `gh` subprocess
19+
-> JSON-lines parse -> item mapping
20+
-> dueCandidate() -> bucket / priority / due derivation
21+
-> selectDueCandidates()
22+
```
23+
24+
Only the `gh` **binary** is replaced, standing in for GitHub's server.
25+
ClawSweeper's own transport — subprocess spawn, argument construction,
26+
JSON-lines parsing, pagination loop — runs unchanged. The `selectedKeys` dedup
27+
set inside `selectDueCandidates` exists precisely because duplicate page entries
28+
are expected.
29+
30+
## Controlled scenario and fixture
31+
32+
Three distinct open PRs, `--batch_size 10` (far above the due count, so capacity
33+
is never the limiting factor), `--max_pages 5`. The stub `gh` returns `#1` on four
34+
consecutive pages, reproducing the `updated`-sorted pagination race in which an
35+
item touched mid-scan is listed again on later pages:
36+
37+
```
38+
page 1: [#1, #2] page 2: [#1, #3] page 3: [#1] page 4: [#1] page 5+: []
39+
```
40+
41+
Four entries are needed because these land in `hot_pull_request`, whose weight is
42+
2 — a stall requires one whole weighted pass to consume nothing but duplicates.
43+
See **Reachability** below for the per-bucket thresholds.
44+
45+
### Two details that are load bearing
46+
47+
Both of these silently turn the proof vacuous — it passes on a pre-fix build and
48+
demonstrates nothing. Do not "simplify" either one away.
49+
50+
1. **Clock.** `selectCandidates()` calls `selectDueCandidates()` **without** a `now`
51+
argument, so the scheduler uses the real `Date.now()`. Candidates must be recent
52+
enough to stay *out* of the weekly-coverage preselect lane (which needs 6 days).
53+
An earlier version used a fixed past timestamp; every candidate then qualified as
54+
weekly-coverage-due and was taken by the plain
55+
`for (const candidate of weeklyCoverageDue) take(candidate)` loop, which never
56+
reaches the weighted drain.
57+
58+
2. **Prior reports.** Items with no existing report are *coverage-untracked* and go
59+
through `takeWeighted`, whose cohort is a separate copy of the bucket lists — the
60+
final loop then recovers the survivors and nothing is stranded. The fixture
61+
therefore writes a prior report per item so the candidates are coverage-tracked
62+
and the final weighted drain owns selection.
63+
64+
## Expected observation
65+
66+
`shards[0].itemNumbers` from the real `plan` CLI, same fixture and invocation:
67+
68+
| build | selected | dueBacklog |
69+
|---|---|---|
70+
| pre-fix | `[1]` — `#2` and `#3` stranded | 6 |
71+
| post-fix | `[1, 2, 3]` | 6 |
72+
73+
The proof also asserts the selection stays deduplicated, so the fix cannot be
74+
satisfied by simply letting the duplicate through.
75+
76+
## Artifact and command
77+
78+
Supported-environment run (Node 24, Crabbox `local-container`). `run-proof.sh`
79+
drives the **real `plan` CLI** with only the `gh` binary stubbed:
80+
81+
```bash
82+
crabbox run \
83+
--provider local-container \
84+
--local-container-image node:24 \
85+
--no-hydrate \
86+
--timing-json \
87+
--artifact-glob '.artifacts/scheduler-duplicate-proof/**' \
88+
--script docs/proof/scheduler-duplicate-candidate-stranding/run-proof.sh
89+
```
90+
91+
It installs the pinned pnpm into a user-writable prefix (the lease runs as the
92+
unprivileged `crabbox` user, so `corepack enable` cannot symlink into
93+
`/usr/local/bin`), builds, runs the planner fixture, and runs the focused suite.
94+
95+
Host-only quick check of the selection logic (injects `fetchOpenItemPage` rather
96+
than the `gh` binary, so it does **not** exercise the transport):
97+
98+
```bash
99+
pnpm run build
100+
node docs/proof/scheduler-duplicate-candidate-stranding/run-proof.mjs # exit 0 = PASS
101+
```
102+
103+
## Provenance
104+
105+
- provider: Crabbox `local-container` (Docker/OrbStack)
106+
- crabbox: `0.15.0`
107+
- image: `node:24` @ `sha256:934240a162082fd8b8a2f90cd5114446443f1eba1c5378f6687167ca405e6584`
108+
- container node: `v24.19.0` (satisfies `engines.node >= 24`)
109+
- lease: `cbx_7c89c5c91f66` (`brave-lobster`)
110+
- run: `run_71734de37d18`
111+
- artifact: `.crabbox/runs/run_71734de37d18/run_71734de37d18-artifacts.tgz`
112+
(`plan.json`, `summary.json`, `focused-tests.txt`, `install.log`, `build.log`)
113+
- result: exit `0`; selected `[1,2,3]`, `dueBacklog` 6, deduped; focused suite `24/24`
114+
- privacy: synthetic `contributor` login and public-shaped item numbers only. The
115+
stub `gh` makes no network call; the proof performs no queue, GitHub, or
116+
production mutation, and no credential is present in the lease.
117+
118+
## Reachability
119+
120+
A stall needs a whole weighted pass to consume nothing but duplicates, so the
121+
threshold is per bucket. Derived by driving the real `dueCandidate()` logic
122+
against a pre-fix build:
123+
124+
| bucket | weight | page entries for one item needed to strand |
125+
|---|---:|---:|
126+
| `hot_pull_request`, `activity`, `recent_issue` | 2 | 4 |
127+
| `daily_pull_request` | 3 | 6 |
128+
| `hot_issue` | 4 | 8 |
129+
| `weekly_issue` | 1 | unreachable |
130+
131+
`weekly_issue` is unreachable because "due" and "weekly-coverage-due" share the
132+
same 6-day threshold there, so the coverage preselect lane always claims it.
133+
134+
Focused tests:
135+
136+
```bash
137+
node --test test/scheduler-policy.test.ts
138+
```
139+
140+
Red/green was verified by swapping only the compiled `dist/scheduler-policy.js`
141+
for a pre-fix build of the same file and re-running the focused suite with the new
142+
tests present: 4 fail pre-fix, 24/24 pass post-fix, with all 20 pre-existing
143+
assertions unchanged in both directions.
144+
145+
## Limits
146+
147+
Covers the batch-selection path only. The duplicate is injected at the `gh`
148+
**binary** boundary rather than produced by a real pagination race, since that race
149+
is timing dependent and not reproducible on demand — so GitHub's own server
150+
behavior is modeled, not exercised. No live GitHub, Worker, or queue is contacted,
151+
and the proof performs no mutation. The lease is a local Docker container, not a
152+
cloud host, so it proves the Linux/Node 24 runtime but not cross-host isolation.
153+
154+
The fix changes only the loop's termination signal (candidates drained instead of
155+
candidates selected). It does not deduplicate the `due` list up front, does not
156+
change bucket weights, ordering, or the dedup key, and does not change behavior at
157+
all for a due list with no duplicates. A duplicate still consumes one weighted
158+
slot in its pass; only the premature `break` is removed.
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
#!/usr/bin/env node
2+
/**
3+
* Real-behavior proof for the scheduler duplicate-candidate stranding fix.
4+
*
5+
* Drives the SHIPPED planner path, not just the pure comparator:
6+
*
7+
* createReviewPlanningSelection(...).selectCandidates()
8+
* -> src/clawsweeper-review-planning-selection.ts:90-111
9+
* -> selectDueCandidates() (src/scheduler-policy.ts)
10+
*
11+
* The only injected behavior is `fetchOpenItemPage`, which reproduces the real
12+
* GitHub artifact that triggers this: the paginated issue listing is sorted by
13+
* `updated`, so an item touched mid-pagination shifts pages and is returned
14+
* twice. Everything downstream is the real planner.
15+
*
16+
* Pre-fix the planner silently returns a truncated batch; post-fix it returns
17+
* every distinct due item.
18+
*
19+
* Usage: node docs/proof/scheduler-duplicate-candidate-stranding/run-proof.mjs
20+
*/
21+
import fs from "node:fs";
22+
import path from "node:path";
23+
import { fileURLToPath } from "node:url";
24+
25+
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
26+
const distPlanner = path.join(repoRoot, "dist", "clawsweeper-review-planning-selection.js");
27+
28+
if (!fs.existsSync(distPlanner)) {
29+
console.error(`missing build artifact: ${distPlanner}\nrun: pnpm run build`);
30+
process.exit(2);
31+
}
32+
33+
const { createReviewPlanningSelection } = await import(`file://${distPlanner}`);
34+
35+
// selectCandidates() calls selectDueCandidates() without a `now` argument, so the
36+
// scheduler uses the real Date.now(). Anchor to it: a candidate reviewed an hour
37+
// ago is NOT weekly-coverage-due (that lane needs 6 days), so selection falls
38+
// through to the weighted drain loop this proof is about. Using a fixed past
39+
// timestamp instead would route everything through the coverage preselect lane,
40+
// which takes candidates in a plain loop and never exercises the defect.
41+
const REVIEWED_AT = Date.now() - 60 * 60 * 1000;
42+
const REPO = "openclaw/openclaw";
43+
44+
const makeItem = (number) => ({
45+
repo: REPO,
46+
number,
47+
kind: "issue",
48+
title: `Item ${number}`,
49+
url: `https://github.com/${REPO}/issues/${number}`,
50+
createdAt: "2020-01-01T00:00:00Z",
51+
updatedAt: "2020-01-01T00:00:00Z",
52+
author: "contributor",
53+
authorAssociation: "NONE",
54+
labels: [],
55+
});
56+
57+
/**
58+
* Two pages of open issues. #1 is touched between the two reads, so GitHub's
59+
* `updated`-sorted listing shifts it onto page 2 as well - it is returned twice.
60+
*/
61+
const pagesWithDuplicate = [
62+
[makeItem(1), makeItem(2)],
63+
[makeItem(1), makeItem(3)],
64+
];
65+
66+
/** Same distinct items, no pagination race. */
67+
const pagesWithoutDuplicate = [
68+
[makeItem(1), makeItem(2)],
69+
[makeItem(3)],
70+
];
71+
72+
const buildPlanner = (pages) =>
73+
createReviewPlanningSelection({
74+
maxPlanShardCount: 8,
75+
targetRepo: () => REPO,
76+
shouldPlanItem: () => true,
77+
buildExistingReviewIndex: () => new Map(),
78+
fetchOpenItemPage: (page) => pages[page - 1] ?? [],
79+
fetchHotIntakeItems: () => ({ items: [], pagesScanned: 0 }),
80+
fetchItem: () => ({ item: null, state: "open" }),
81+
shouldSkipScheduledHotIntakeExactReview: () => false,
82+
reviewBackfillCandidate: () => null,
83+
// Every item is due, in the weight-1 weekly_issue bucket, already reviewed
84+
// recently enough that the weekly-coverage preselect lane does not claim it.
85+
dueCandidate: (item) => ({
86+
item,
87+
review: { reviewStatus: "complete", reviewedAt: new Date(REVIEWED_AT).toISOString() },
88+
priority: 6,
89+
reviewedAt: REVIEWED_AT,
90+
nextDueAt: 0,
91+
bucket: "weekly_issue",
92+
coverageTracked: true,
93+
}),
94+
});
95+
96+
const run = (pages) =>
97+
buildPlanner(pages)
98+
.selectCandidates({
99+
batchSize: 10, // capacity far above the 3 distinct due items
100+
maxPages: pages.length,
101+
shardIndex: 0,
102+
shardCount: 1,
103+
itemsDir: path.join(repoRoot, "does-not-exist"),
104+
})
105+
.candidates.map((item) => item.number);
106+
107+
const control = run(pagesWithoutDuplicate);
108+
const subject = run(pagesWithDuplicate);
109+
110+
const expected = [1, 2, 3];
111+
const sameSet = (left, right) =>
112+
left.length === right.length && [...left].sort().every((value, i) => value === [...right].sort()[i]);
113+
114+
console.log("== planner selectCandidates(), batchSize 10, 3 distinct due items ==\n");
115+
console.log(` control (no pagination race) -> [${control.join(", ")}]`);
116+
console.log(` subject (#1 returned twice) -> [${subject.join(", ")}]`);
117+
console.log(` expected -> [${expected.join(", ")}]\n`);
118+
119+
const controlOk = sameSet(control, expected);
120+
const subjectOk = sameSet(subject, expected);
121+
const noDuplicates = new Set(subject).size === subject.length;
122+
123+
console.log(` control selects every due item : ${controlOk ? "yes" : "NO"}`);
124+
console.log(` subject selects every due item : ${subjectOk ? "yes" : "NO <- stranded"}`);
125+
console.log(` subject is still deduplicated : ${noDuplicates ? "yes" : "NO <- duplicate leaked"}\n`);
126+
127+
const passed = controlOk && subjectOk && noDuplicates;
128+
console.log(`RESULT: ${passed ? "PASS" : "FAIL"}`);
129+
console.log(
130+
passed
131+
? " A duplicated page entry no longer costs the batch its remaining candidates."
132+
: " The pagination duplicate truncated the batch (pre-fix behavior).",
133+
);
134+
process.exit(passed ? 0 : 1);

‎src/scheduler-policy.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,11 @@ export function selectDueCandidates<
322322
for (const candidate of candidates) cohort.get(candidate.bucket)?.push(candidate);
323323
for (const bucketCandidates of cohort.values()) bucketCandidates.sort(compare);
324324
while (selected.length < capacity) {
325-
const before = selected.length;
325+
// Stop on candidates drained, not candidates selected. take() silently
326+
// drops an already-selected duplicate, so a pass that consumed only
327+
// duplicates is not evidence that the buckets are empty; measuring
328+
// selection here would strand every candidate queued behind them.
329+
let drained = 0;
326330
for (const [bucket, weight] of SCHEDULER_BUCKET_WEIGHTS) {
327331
const bucketCandidates = cohort.get(bucket);
328332
if (!bucketCandidates?.length) continue;
@@ -332,9 +336,10 @@ export function selectDueCandidates<
332336
index += 1
333337
) {
334338
take(bucketCandidates.shift());
339+
drained += 1;
335340
}
336341
}
337-
if (selected.length === before) break;
342+
if (drained === 0) break;
338343
}
339344
};
340345

@@ -388,15 +393,21 @@ export function selectDueCandidates<
388393
}
389394

390395
while (selected.length < capacity) {
391-
const before = selected.length;
396+
// Stop on candidates drained, not candidates selected. GitHub's paginated
397+
// issue listing is sorted by `updated`, so an item touched mid-pagination
398+
// can appear on two pages; take() drops that duplicate silently. Measuring
399+
// selection here would read "hit a duplicate" as "buckets are drained" and
400+
// abandon every remaining candidate while capacity is still free.
401+
let drained = 0;
392402
for (const [bucket, weight] of SCHEDULER_BUCKET_WEIGHTS) {
393403
const candidates = buckets.get(bucket);
394404
if (!candidates?.length) continue;
395405
for (let i = 0; i < weight && candidates.length && selected.length < capacity; i += 1) {
396406
take(candidates.shift());
407+
drained += 1;
397408
}
398409
}
399-
if (selected.length === before) break;
410+
if (drained === 0) break;
400411
}
401412

402413
return selected;

0 commit comments

Comments
 (0)