Skip to content

Reconcile open bot PRs on demand with backoff and batched GraphQL reads - #1397

Merged
zhaozhaozz merged 1 commit into
agent-CI-Infra:mainfrom
zhaozhaozz:feat/issue-1396-on-demand-bot-pr-reconcile
Nov 26, 2026
Merged

zhaozhaozz merged 1 commit into
agent-CI-Infra:mainfrom
zhaozhaozz:feat/issue-1396-on-demand-bot-pr-reconcile

Conversation

@zhaozhaozz

Copy link
Copy Markdown
Collaborator

Fixes #1396

Problem

BotPrWakeScanner ran reconcileOpenBotPullRequestsForRepo every 60 s for every repository with open bot PRs and read the 25 newest of them over REST each time (GET /pulls/<n> each, GET ref per base branch, check runs and suites whenever a 10-minute in-memory cache expired), whether or not anything had changed. On the openJiuwen-ai installation (sciencediscovery 41 open bot PRs, DigitalMate 17) that loop alone was about 3,300 core requests an hour against a 5,000 quota, and the 16 older sciencediscovery PRs were never reconciled.

Change

Per-PR schedule (bot_pr_states.reconcile_at, reconcile_due_at, reconcile_interval_ms, reconcile_fingerprint, reconcile_env):

  • A PR is read 5 minutes after a change, then twice as long each time nothing changed: 5 → 10 → 20 → 40 → 80 → 160 → 240 minutes, capped at 4 hours (BOT_PR_RECONCILE_MIN_MS / BOT_PR_RECONCILE_MAX_MS).
  • One PR is never read more often than every 5 minutes.
  • The interval starts over when a read finds a change: state/draft/merged, mergeability, head or base OID, the base branch tip, updated_at, or the head commit's check suites.
  • It also starts over on a webhook about the PR (markBotPrsForReconcile, called from botPrWakeEvents): PR events, reviews and comments; check_run / check_suite / workflow_run / status on its head commit or branch; a push to its head or base branch; another PR merged into its base. Such a PR becomes due at max(now, reconcile_at + 5 min).
  • A change to the project's local settings makes every PR due again once its 5 minutes are up. These settings are policy, roles, stored installation permissions and the project computer: the patrol environment fingerprint without live permissions.
  • The 6-hour patrol (feat(dispatch): 为未合入 bot PR 增加内部定期巡检与复核机制(抑制无效冲突空烧,不外发通知) #1316) is unchanged. A PR is also due when its patrol interval has passed and it has not been read since.
  • All open bot PRs are candidates (the LIMIT 25 is gone). The scanner still ticks every minute, but a repository with no due PR does not connect and sends nothing.

Batched reads: all due PRs of a repository go into one GraphQL query per 50 PRs (pN: pullRequest(number: N) aliases), with these fields: state isDraft mergeable updatedAt headRefName headRefOid baseRefName baseRefOid baseRef{target{oid}} commits(last:1){…checkSuites(first:100){totalCount nodes{databaseId status conclusion}}}.

  • If the snapshot digest matches the last read and the patrol is not due, no REST request is made for that PR.
  • Otherwise the existing REST flow runs unchanged for that PR (GET /pulls/<n>, conflict handling, mergeability recheck, patrol). The base tip comes from the query, so there is no GET ref.
  • Check runs and suites are read over REST only when the query shows a completed suite on the head that did not pass and whose state changed since the last read. The query sees startup_failure suites without check runs, so those are still detected.
  • A REST read that fails after a reported change is not recorded, so the next pass reads it again.
  • A PR GitHub reports as NOT_FOUND yields a partial answer and is backed off like an unchanged PR.

GraphQL rate-limit window: blockedUntil / refused now take the resource. request() uses graphql for POST /graphql and core otherwise, and the x-ratelimit-resource: graphql headers are recorded in github_rate_limits as before.

  • A used-up core window no longer blocks queries, and the reverse.
  • graphql() maps a RATE_LIMITED answer (HTTP 200) to github_rate_limited / retry_wait instead of github_graphql_failed.
  • In the reconcile, a used-up GraphQL window stops the pass with no REST fallback and records nothing, so the PRs stay due.
  • Any other GraphQL failure falls back to the REST read for each due PR, and that schedule also backs off.

Webhook-driven rechecks (schedulePendingSuiteRecheck, which passes onlyPrNumbers) are not scheduled; they still read their PRs over REST right away.

Why GraphQL rather than REST conditional requests

I checked the query against real GitHub (agent-test-zone/bot-demo). 50 aliased PRs with their check suites cost 1 point. A missing number answers null plus a NOT_FOUND error for that alias only. CheckConclusionState includes STARTUP_FAILURE, and baseRef.target.oid gives the base tip in the same query.

With If-None-Match, a 304 does not count, but each poll would still be one request per PR, plus separate check-runs and check-suites requests (each needing its own ETag) and a ref read. GraphQL covers all of that in one request and moves the polling load to the separate graphql window.

Requests per hour, before and after (fake GitHub)

Scenario: 41 open bot PRs (sciencediscovery's count) on one App installation, nothing changes, 6-hour patrol on, scanner ticking every minute for 8 simulated hours. The counts are installation-token REST requests, not the App's own JWT requests (installation lookup, token minting). The same scenario was run against origin/main (65724a6) and this branch.

hour before: REST (of which GET /pulls/<n>) after: REST / GraphQL queries / GET /pulls/<n>
1 (cold start, first patrol) 2,005 (1,500) 172 / 4 / 41
2 1,980 (1,500) 2 / 1 / 0
3 1,980 (1,500) 2 / 1 / 0
4 1,980 (1,500) 0 / 0 / 0
5 1,980 (1,500) 0 / 0 / 0
6 1,980 (1,500) 2 / 1 / 0
7 (6-hour patrol) 2,005 (1,500) 166 / 1 / 41
8 1,980 (1,500) 0 / 0 / 0
8 h total ≈ 15,890, only 25 of 41 PRs ever read 344 REST + 8 GraphQL points, all 41 PRs

The "after" column is printed by the last test in test/st/src/review/bot-pr-reconcile-schedule.test.mjs, which also bounds it. Once PRs change, each changed PR costs one GET /pulls/<n>, plus check runs and suites when a suite that did not pass appears, plus comments for an unrecorded conflict, at most once per 5 minutes.

Behaviour changes worth noting

  • An environment, permission or capability change used to wake a blocked PR's patrol within a minute. It now wakes it at the PR's next allowed read, at most 5 minutes after the previous one. In bot-pr-patrol.test.mjs, four 2-minute clock steps became 5-minute steps for this reason.
  • The in-memory settledReconcileChecks cache is gone; the persisted snapshot digest replaces it.

Tests

  • New test/st/src/review/bot-pr-reconcile-schedule.test.mjs (weight added to test-set-weights.json), on a fake App installation:
    • 30 open PRs (more than the old cap) are read in one query. Ten hours of minute ticks read at minutes 5, 15, 35, 75, 155, 315 and 555 (gaps of 5 to 240 minutes) with no REST PR read, and no request at all in between. The graphql window is recorded.
    • A new head (with a runless startup_failure suite that still wakes the Manager) resets only that PR. Reads are triggered by a comment webhook, by a check_suite on the head (held back by the 5-minute floor), by another PR merged into main (all PRs), and by a local policy change.
    • A used-up GraphQL window stops the pass without REST reads, records nothing and is not sent into again, while core stays unblocked. A 502 from GraphQL falls back to REST, and that schedule still backs off.
    • The per-hour request count above.
  • github-rate-limits.test.mjs: a RATE_LIMITED GraphQL answer stops as github_rate_limited, the next query is not sent, and REST still is.
  • bot-pr-wake and bot-pr-patrol fixtures answer the batched query through the new test/fixtures/bot-pr-graphql.mjs, so their scanner scenarios (startup_failure detection, conflicts, patrol, suppression) now run through the GraphQL path.

Verification

Head 98fb2576, on origin/main 65724a65, Node 22.

  • npm ci → exit 0; (cd runner && npm ci) → exit 0.
  • npm run check → exit 0 (tsc, runtime syntax checks of 853 files).
  • npm test → exit 1. 350 of 352 sets passed; the two failures are unrelated to this change and pass on their own:
    • runner-transport: listen EADDRINUSE on a 119-byte socket path under this deep worktree's .tmp/tests-*/… (over the 108-byte sun_path limit). TMPDIR=$PWD/.tmp/s node --test test/ut/manager/runner-transport.test.mjs → exit 0, 4/4.
    • codex-harness: a timing assertion ("stopped promptly after interrupt_requested") under the parallel load. node test/framework/test-sets.mjs test/st/src/harness/codex-harness.test.mjs → exit 0, 68/68.
  • The related sets run together (bot-pr-reconcile-schedule, bot-pr-wake, bot-pr-patrol, continuous-pr-task, github-rate-limits) → exit 0, 28/28.
  • GraphQL query shape and cost checked read-only against real GitHub (agent-test-zone/bot-demo): 50 aliased PRs with check suites, cost: 1, x-ratelimit-resource: graphql, missing numbers answer null and NOT_FOUND for that alias only.

…ed GraphQL reads

The fallback reconcile read the 25 newest open bot PRs of every repository
over REST every minute, whether or not anything changed. On a busy
installation that alone used most of the hourly core quota, and older PRs
were never read.

Each open bot PR now has its own schedule in bot_pr_states: it is read
5 minutes after a change, then twice as long each time nothing changed, up
to 4 hours, and never more often than every 5 minutes. A change it finds,
a webhook about the PR, its head commit or its base branch, or a change to
the project's local settings makes it due again. Every open bot PR is
covered, and a tick with no PR due makes no GitHub request.

The due PRs of a repository are read with one GraphQL query per 50 PRs
(state, draft, mergeability, head, base and base tip, updated_at, head
check suites, including startup_failure suites without check runs). Only
PRs whose snapshot changed, or whose patrol is due, are read over REST as
before; check runs and suites are read only when a completed suite that did
not pass appears. When GraphQL fails for another reason than its rate
limit, the due PRs are read over REST.

GraphQL queries now count against their own window: a used-up core window
no longer stops queries, a used-up GraphQL window no longer stops REST
requests, and a RATE_LIMITED answer stops as github_rate_limited.

Fixes agent-CI-Infra#1396
@zhaozhaozz
zhaozhaozz added this pull request to the merge queue Nov 26, 2026
@zhaozhaozz

Copy link
Copy Markdown
Collaborator Author

Reviewed head 98fb2576685fbb8b80d12fc1aefc8c58c8dc9d23.

Checked the per-PR reconcile schedule (#1396): 5 min floor, 5→10→20→40→80→160→240 min backoff, 4 h cap, reset on change/webhook/local-env change, all open bot PRs covered, no connect while nothing is due; the batched GraphQL read (50 aliases per query), REST details only for changed PRs (and check runs/suites only for a changed completed non-passing suite), the REST fallback when GraphQL fails for other reasons, and the separate graphql rate-limit window in src/github/client.ts/rate-limits.ts. CI is green: unit (both shards), e2e, the four image builds and CodeQL. Docs match the behaviour.

No blocking issues. Enqueued for merge with expectedHeadOid=98fb2576685fbb8b80d12fc1aefc8c58c8dc9d23.

@agent-ci-infra-bot agent-ci-infra-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit: 98fb257
Coverage: PR #1397; 12 changed file(s)

Comment thread src/review/bot-pr-wake.ts
Comment on lines +3311 to +3313
} catch {
// Isolate per-PR patrol errors so one malformed row or transient failure never stalls scanning other PRs.
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

F1(suggestion)逐 PR try 里的异常不会被记为「未读到」,会把该 PR 的下一次读取推迟到翻倍后的间隔(最长 4 小时)

同一段代码已在别处定下「读不到就下轮重读」的约定:第 2992 行 REST 详情读取失败时 seen = null,第 3316 行落库为 'unreadable',saveBotPrReconcile 判定摘要变化后把间隔复位到 5 分钟。但这里的 catch 没有做同样的事——此时 seen 仍是前面 GraphQL 快照算出的摘要,finally 落库后判定为「没变化」,间隔按 prior * 2 翻倍(封顶 4 小时)。

叠加 botPrReconcileDue(第 2847 行 if (patrolDueAt <= nowMs && last < patrolDueAt) return true;)会因为本次已写入 reconcile_at = now 而不再命中巡检兜底分支,结果是:一次瞬时失败(例如 SQLITE_BUSY、recordEvent 事务异常、巡检路径中除 guardRequest 之外的意外抛错)会让该 PR 的巡检、冲突与失败检查在最长 4 小时内不再重试。改动前这类异常由每分钟一轮的扫描自然重试(last_patrol_at 未推进,下一 tick 仍判定巡检到期)。在当前改动下只有该 PR 恰好又收到 Webhook 时才会在 5 分钟后重读,而没有 Webhook 的安静 PR 正是巡检要覆盖的场景。

建议在 catch 中把本次读取标记为未读到,与上面两处语义对齐(一行改动,不影响其它 PR):

} catch {
  // Isolate per-PR patrol errors ...; the read is recorded as unread so it is retried in 5 minutes.
  seen = null;
}

@agent-ci-infra-bot

Copy link
Copy Markdown
Contributor

检视结论(head 98fb2576,base main@65724a65)

12 个文件 +907/−364。整体设计与 #1396 的问题陈述一致:去掉 LIMIT 25 的全量候选、按 PR 独立回溯(5 分钟下限 → 翻倍 → 4 小时封顶)、Webhook 复位、graphql/core 双窗口分离、GraphQL 批量读取 + 只在有变化时补 REST 详情,文档(docs/design/dispatch-and-tasks.md、docs/features/github-automation.md、docs/features/deployment-and-operations.md)与实现一致。

在本任务工作区实际执行的验证

  • npm run check:TypeScript + 853 个运行时 JS 文件语法检查通过。
  • node --test test/st/src/review/*.test.mjs:95/95 通过(含 bot-pr-reconcile-schedule 的调度/Webhook 复位/graphql 窗口用尽停止与 REST 回退,以及 bot-pr-wake、bot-pr-patrol)。
  • node --test test/st/src/github/*.test.mjs:52/52 通过(含新增的「GraphQL 独立窗口」用例:200 + RATE_LIMITED 映射为 github_rate_limited,blockedUntil(...,'graphql') 生效而 core 不受影响)。
  • 逐段核对的重点:botPrReconcileDue / saveBotPrReconcile(含 Webhook 在读取期间获胜的 CASE WHEN ... IS NOT ? 写法)、readBotPrSnapshots 的 NOT_FOUND 局部错误容忍与其它错误整体回退、markBotPrsForReconcile 的压平 SQL 参数顺序(numbers/shas×2/heads/bases)、pN 别名与 RECONCILE_BATCH 分片、prFilter(Webhook 定向复查)不参与调度、以及 test/fixtures/bot-pr-graphql.mjs 对 REST 形态状态的忠实映射。

发现

编号 严重度 结论 位置
F1 suggestion open src/review/bot-pr-wake.ts:3311

F1 不阻断合入(不影响正确性主线,只在瞬时异常时把重试推迟),其余未发现逻辑/并发/资源/安全/API 破坏类缺陷。第 3316 行 finally 用的 store.db.isOpen 是正确的(文中其它 store.db.open 判断属于改动前既有写法,本 PR 未新增)。

未独立复核:PR 描述中「50 个别名 PR 连同 check suites 实测 1 点 GraphQL 额度」来自作者在真实 GitHub 的实测;仓库内假 GitHub 不模拟 rateLimit.cost,我无法在本地复现该数值,仅确认窗口分离逻辑本身正确。

Reviewed commit: 98fb257
Coverage: PR #1397; 12 changed file(s)

Merged via the queue into agent-CI-Infra:main with commit 2f2195a Nov 26, 2026
12 checks passed
@zhaozhaozz
zhaozhaozz deleted the feat/issue-1396-on-demand-bot-pr-reconcile branch November 26, 2026 05:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bot PR reconcile: poll each open bot PR on demand with backoff (5 min to 4 h) and batch the reads

1 participant