Skip to content

Fix/scheduler duplicate candidate stranding - #1046

Merged
steipete merged 4 commits into
openclaw:mainfrom
dwin-gharibi:fix/scheduler-duplicate-candidate-stranding
Aug 6, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
dwin-gharibi:fix/scheduler-duplicate-candidate-stranding

Conversation

@dwin-gharibi

@dwin-gharibi dwin-gharibi commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1045.

What Problem This Solves

Fixes an issue where a sweep would review fewer items than it had capacity for,
with no error and no telemetry signal, whenever the same item appeared twice in
the due list.

Duplicates are a normal GitHub pagination artifact: GET /issues is sorted by
updated, so an item touched between two page reads shifts pages and is returned
on both. selectDueCandidates already dedupes by repo#number — the dedup was
never the problem. The problem was that hitting a duplicate ended selection
entirely, stranding every candidate queued behind it while capacity sat free.

Through the real plan CLI with three distinct due PRs and #1 listed on four
pages, the pre-fix sweep selected [1] where the fix selects [1, 2, 3] —
dueBacklog reported 6 in both cases.

The stranded items stay due, so the effect is delay and wasted capacity rather
than permanent starvation — but it compounds against the weekly-coverage SLO,
which is the outer freshness deadline for canonical records.

Reachability, precisely. A stall needs a whole weighted pass to consume
nothing but duplicates, so the threshold is per bucket. Derived by driving the
real dueCandidate() logic against a pre-fix build:

bucket weight page entries for one item needed to strand
hot_pull_request, activity, recent_issue 2 4
daily_pull_request 3 6
hot_issue 4 8
weekly_issue 1 unreachable

weekly_issue cannot reach it: "due" and "weekly-coverage-due" share the same
6-day threshold there, so such an item is always claimed by the coverage preselect
lane, which takes candidates in a plain loop. The candidate must also be
coverage-tracked and reviewed inside the window between its cadence (1 day) and
the 6-day coverage deadline; untracked items are recovered by the final loop.

I originally wrote that a single duplicate was enough. That was wrong — it came
from a hand-built weekly_issue candidate the real planner never emits in a
due-but-not-coverage-due state. The defect and the fix are unchanged; the
severity is narrower than I first stated, and this section is the correction.

Why This Change Was Made

take() collapses three outcomes into "nothing happened": capacity reached,
bucket empty, and duplicate skipped. The weighted drain's no-progress guard then
read a pass that consumed only duplicates as "all buckets are drained" and broke
out of the loop.

The fix changes what the loop measures — candidates drained instead of
candidates selected — in the final drain loop and in takeWeighted, which has
the same shape. Two lines per loop.

Deliberately minimal. It does not:

  • deduplicate the due list up front (that would change which entry wins when two
    copies carry different review/bucket fields — a larger behavioral change
    than this defect calls for);
  • change bucket weights, ordering, comparators, or the dedup key;
  • change behavior at all for a due list with no duplicates.

A duplicate still consumes one weighted slot in its pass; only the premature
break is removed. Termination is unchanged in kind: each pass either drains at
least one candidate or breaks, and due is finite.

User Impact

Sweeps fill their configured batch size when the GitHub listing returns an item
twice, instead of silently truncating. Operators see the review throughput the
capacity settings imply; no configuration change is needed.

No data-contract, workflow, or schema change. No migration.

OpenClaw Bay: not affected. This changes how many candidates a sweep selects,
not any status, lifecycle, or telemetry shape Bay renders. dueBacklog,
capacityReason, and planSelectionTelemetry keep their existing meanings — the
selected count simply stops being wrong. No Bay update or Bay proof is needed.

Release note: fix: stop duplicate due candidates from truncating the review batch.
No CHANGELOG.md edit is included — happy to add one if this repo's release policy
wants it.

Evidence

Diff

 src/scheduler-policy.ts       |  19 +++++--
 test/scheduler-policy.test.ts | 129 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 144 insertions(+), 4 deletions(-)

Plus a new proof package under docs/proof/scheduler-duplicate-candidate-stranding/.

Focused tests

node --test test/scheduler-policy.test.ts → 24/24 pass (20 pre-existing + 4 new).

New tests:

  • duplicate due candidates do not strand the rest of the batch — contract-level,
    plus assertions that duplicates are still deduped and capacity is still respected.
  • a run of duplicates larger than the bucket weight still drains — eight entries
    in the weight-4 hot_issue bucket, spanning two full passes with no new
    selection in the second.
  • duplicates across separate buckets do not stall the weighted drain — duplicates
    in two buckets simultaneously.
  • pagination duplicates do not strand candidates the real planner produces —
    builds its candidate the way dueCandidate() does, asserting the derived bucket
    and due-ness first, so the regression guard is pinned to a shape production
    actually emits rather than a hand-built one.

Red/green

Swapped only the compiled dist/scheduler-policy.js for a pre-fix build of the
same file, and re-ran with the new tests present:

build result
pre-fix 4 fail, 20 pass — exactly the 4 new tests
post-fix 24 pass, 0 fail

All 20 pre-existing assertions were unchanged in both directions.

Real Behavior Proof

Claim. selectDueCandidates fills the batch to capacity from the candidates it
is given, even when an item appears twice.

Exercised surface. The real plan CLI, end to end — no application function
is substituted
:

node dist/clawsweeper.js plan
  -> createReviewPlanningSelection().selectCandidates()
  -> fetchOpenItemPage()  -> ghJsonLines() -> spawnSync -> `gh` subprocess
                          -> JSON-lines parse -> item mapping
  -> dueCandidate()       -> bucket / priority / due derivation
  -> selectDueCandidates()

Only the gh binary is replaced, standing in for GitHub's server. ClawSweeper's
own transport — subprocess spawn, argument construction, JSON-lines parsing,
pagination loop — runs unchanged. This addresses the previous review's finding that
the artifact "substitutes fetchOpenItemPage, so it does not exercise a real
transport client".

Scenario / fixture. Three distinct open PRs, --batch_size 10 (far above the due
count, so capacity is never the limiting factor), --max_pages 5. The stub gh
returns #1 on four consecutive pages, reproducing the updated-sorted pagination
race in which an item touched mid-scan is listed again on later pages:

page 1: [#1, #2]   page 2: [#1, #3]   page 3: [#1]   page 4: [#1]   page 5+: []

A prior report exists for each PR in the items dir, making them coverage-tracked —
the state in which the weighted drain, not the coverage preselect lane, owns
selection.

Command and environment. Executed in the supported environment — Node 24 in a
Docker-backed Crabbox local-container lease, on the current head:

crabbox run \
  --provider local-container \
  --local-container-image node:24 \
  --no-hydrate \
  --timing-json \
  --artifact-glob '.artifacts/scheduler-duplicate-proof/**' \
  --script docs/proof/scheduler-duplicate-candidate-stranding/run-proof.sh
field value
provider Crabbox local-container (Docker/OrbStack)
crabbox 0.15.0
image node:24 @ sha256:934240a162082fd8b8a2f90cd5114446443f1eba1c5378f6687167ca405e6584
container node v24.19.0 (satisfies engines.node >= 24)
lease cbx_7c89c5c91f66 (brave-lobster)
run run_71734de37d18
artifact .crabbox/runs/run_71734de37d18/run_71734de37d18-artifacts.tgz
exit 0

Observed result. In-container, on the current head:

selected   : [1,2,3]
expected   : [1,2,3]
dueBacklog : 6        (6 page entries for 3 distinct PRs)
deduped    : true
RESULT: PASS

focused suite: 24/24 pass

summary.json from the artifact tarball:

{ "selected": [1,2,3], "expected": [1,2,3], "dueBacklog": 6,
  "scannedPages": 5, "duplicateFreeSelection": true, "pass": true }

Against a pre-fix build of dist/scheduler-policy.js, the identical fixture and
CLI invocation yields shards[0].itemNumbers = [1] — #2 and #3 stranded with
dueBacklog still 6.

The proof also asserts the selection stays deduplicated, so the fix cannot be
satisfied by simply letting the duplicate through.

Two traps worth recording, both documented in the proof README so the next
person does not silently reintroduce a vacuous proof:

  1. selectCandidates() calls selectDueCandidates() without a now argument, so
    the scheduler uses the real Date.now(). An earlier fixture used a fixed past
    reviewedAt; every candidate then qualified as weekly-coverage-due and was taken
    by the plain for (const candidate of weeklyCoverageDue) take(candidate) lane,
    which never reaches the weighted drain — so it passed on a pre-fix build and
    proved nothing.
  2. Items with no prior report take the untracked lane, where survivors are
    recovered by the final loop and nothing is stranded. The fixture therefore writes
    a prior report per item; without that, the proof is also vacuous.

Artifact / trace. docs/proof/scheduler-duplicate-candidate-stranding/ contains
run-proof.sh (the Crabbox entry point), run-proof.mjs (host-only quick check),
and the contract README. The lease artifact tarball holds plan.json,
summary.json, focused-tests.txt, install.log, and build.log.

Limits. Covers batch selection only. The duplicate is injected at the gh
binary boundary rather than produced by a real pagination race, since that race
is timing dependent and not reproducible on demand — so GitHub's own server
behavior is modeled, not exercised. No live GitHub, Worker, or queue is contacted,
and the proof performs no mutation. The lease is a local Docker container, not a
cloud host, so it proves the Linux/Node 24 runtime but not cross-host isolation.

Privacy. The fixture uses only openclaw/openclaw public-shaped item numbers
and a synthetic contributor login. No credential is present in the lease; the
stub gh makes no network call.

Repository test suite status

The proof and focused suite now run on Node 24 inside the Crabbox
local-container lease
recorded above (24/24 focused tests in-container). The
notes below concern only the full suite run on the macOS host.

engines.node is >=24; the newest Node available on the macOS host is v23.7.0,
and AGENTS.md warns about test misbehavior below Node 24.

run tree distinct failing tests
clean main fix stashed, rebuilt 20
run 1 this branch 22
run 2 this branch 21

Two runs of the identical branch disagree with each other — comm -3 over
run 1 and run 2 shows three tests flipping. That is direct evidence of flakiness
rather than a regression.

The two tests that appeared only on the fix branch in run 1
(comment webhook settles duplicate fast ack comments after dispatch,
webhook signature verification uses sha256 body hmac) both passed in run 2,
and both pass 25/25, three runs in a row, in isolation on both the clean tree
and this branch. A module-graph walk from dist/repair/comment-webhook.js confirms
scheduler-policy is not reachable from that code at all.

No scheduler test failed in any run, on either tree.

Green on this branch:

check environment result
Crabbox local-container proof Node 24 container PASS, exit 0
test/scheduler-policy.test.ts Node 24 container 24/24
pnpm run build:all macOS host clean
pnpm run format:check macOS host clean, 636 files
pnpm run lint macOS host clean (all four projects)

Please confirm pnpm run check on Node 24+ in CI before merging. The changed
surface is proven on Node 24, but I have not produced a green full-suite run and
am not claiming one.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal priority bug or improvement with limited blast radius. labels Aug 6, 2026
@clawsweeper

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 6, 2026, 10:27 AM ET / 14:27 UTC.

ClawSweeper review

What this changes

The PR changes weighted scheduler draining so duplicate due candidates do not stop a review batch before remaining distinct candidates are selected.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 3 items remain

Keep this PR open: current main has the duplicate-drain defect and the code repair is sound, but merge should wait for required supported-environment behavior proof.

Priority: P2
Reviewed head: 8b868b0dfcc71dbcd0ba6035e82a05f70013a67f

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation and focused coverage are strong, but merge-ready real behavior proof is still missing.
Proof confidence 🦐 gold shrimp (3/6) Needs real behavior proof before merge: The runnable artifact exercises compiled planner code but replaces the page-fetch boundary, and it lacks the required current-head Docker-backed Crabbox local-container provenance. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The runnable artifact exercises compiled planner code but replaces the page-fetch boundary, and it lacks the required current-head Docker-backed Crabbox local-container provenance. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current-main defect: The two weighted loops stop when selected count does not grow; shifting an already-selected duplicate leaves that count unchanged even though later candidates remain queued.
Narrow repair: The branch counts shifted candidates in both weighted loops, preserving the existing deduplication key, bucket order, and capacity check.
Focused regression coverage: Three new cases cover a weight-one duplicate, a duplicate run beyond bucket weight, and duplicates across buckets.
Findings None None.
Security None None.

How this fits together

Review planning fetches open GitHub items into due candidates, then the scheduler selects a bounded batch across priority buckets. That batch feeds the Codex review workflow and its throughput telemetry.

flowchart LR
  A[Open GitHub item pages] --> B[Review planning]
  B --> C[Due candidates]
  C --> D[Weighted scheduler]
  D --> E[Deduplicate and drain]
  E --> F[Review batch]
  F --> G[Codex review workflow]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The runnable artifact exercises compiled planner code but replaces the page-fetch boundary, and it lacks the required current-head Docker-backed Crabbox local-container provenance. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The submitted proof remains mock-only and was recorded outside the repository-required Node 24 Docker-backed Crabbox environment, so the production scheduling path lacks merge-ready runtime evidence.
  • Complete next step (P2) - This active paired fix PR needs contributor-owned supported-environment proof, not an automated replacement or repair job.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Scheduler coverage 15 production lines changed, 77 test lines added, 223 proof-documentation lines added The patch covers both weighted draining loops and adds duplicate scenarios plus a planner-path proof artifact.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #1045
Summary: This PR is the concrete candidate fix for the open duplicate-candidate scheduler issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Retain the narrow drained-candidate repair and attach a current-head Node 24 Crabbox local-container trace that demonstrates the post-fix planner result with an injected pagination duplicate.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Retain the narrow drained-candidate repair and attach a current-head Node 24 Crabbox local-container trace that demonstrates the post-fix planner result with an injected pagination duplicate.

Do we have a high-confidence way to reproduce the issue?

Yes: current-main source exposes the premature no-progress break when a duplicate is shifted, and the submitted fixture places that duplicate ahead of distinct due candidates.

Is this the best way to solve the issue?

Yes: measuring drained queue entries preserves existing deduplication and weighted ordering while removing the premature termination condition.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against daf339e6d1d3.

Labels

Label changes:

  • add P2: Duplicate pagination entries can silently reduce scheduled review throughput, but the demonstrated effect is delayed work rather than data loss or an outage.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The runnable artifact exercises compiled planner code but replaces the page-fetch boundary, and it lacks the required current-head Docker-backed Crabbox local-container provenance. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P2: Duplicate pagination entries can silently reduce scheduled review throughput, but the demonstrated effect is delayed work rather than data loss or an outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The runnable artifact exercises compiled planner code but replaces the page-fetch boundary, and it lacks the required current-head Docker-backed Crabbox local-container provenance. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • Martin Cleary: Available local history attributes two scheduler-policy commits to Martin Cleary, including recent duplicate-intake work. (role: recent scheduler contributor; confidence: medium; commits: 559a7969d173, 6ad7b5448970; files: src/scheduler-policy.ts)
  • PollyBot13: Recent scheduler history includes the review scheduling change b83f298. (role: recent scheduler contributor; confidence: medium; commits: b83f2983da6b; files: src/scheduler-policy.ts)
  • Peter Steinberger: Blame attributes the page-fetch to due-candidate planning path to the focused review-planning refactor. (role: review-planning refactor author; confidence: high; commits: 0036015e1dd0; files: src/clawsweeper-review-planning-selection.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Run the planner proof on the current head in Crabbox local-container and add redacted provider, image, lease, artifact, and output details to the PR body.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@dwin-gharibi

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@steipete
steipete merged commit 9725dab into openclaw:main Aug 6, 2026
8 of 11 checks passed
ostehost pushed a commit to ostehost/clawsweeper that referenced this pull request Aug 7, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Duplicate due candidates end batch selection early and strand due items

2 participants