From b513d87750035d5b9c78d819985655f26c13f1e6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 21 Jul 2026 19:04:23 +0800 Subject: [PATCH] feat(workflows): add similar issue backfill --- .github/scripts/backfill-similar-issues.mjs | 107 ++++++++++++++++++ .../scripts/backfill-similar-issues.test.mjs | 64 +++++++++++ .github/workflows/similar-issues-backfill.yml | 60 ++++++++++ 3 files changed, 231 insertions(+) create mode 100644 .github/scripts/backfill-similar-issues.mjs create mode 100644 .github/scripts/backfill-similar-issues.test.mjs create mode 100644 .github/workflows/similar-issues-backfill.yml diff --git a/.github/scripts/backfill-similar-issues.mjs b/.github/scripts/backfill-similar-issues.mjs new file mode 100644 index 000000000..26679bc73 --- /dev/null +++ b/.github/scripts/backfill-similar-issues.mjs @@ -0,0 +1,107 @@ +#!/usr/bin/env node +import { pathToFileURL } from "node:url"; + +import { GitHubClient, run } from "./suggest-similar-issues.mjs"; + +const DEFAULT_SEARCH_DELAY_MS = 7000; + +function integerValue(value, fallback, name) { + if (value === undefined || value === null || value === "") return fallback; + const parsed = Number.parseInt(String(value), 10); + if (!Number.isInteger(parsed) || parsed < 0) throw new Error(`${name} must be a non-negative integer`); + return parsed; +} + +function sleep(milliseconds) { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +export function selectChunk(issues, { chunkIndex, chunkCount, maxIssues = 0 }) { + if (!Number.isInteger(chunkCount) || chunkCount < 1) throw new Error("chunkCount must be at least 1"); + if (!Number.isInteger(chunkIndex) || chunkIndex < 0 || chunkIndex >= chunkCount) { + throw new Error("chunkIndex must be within chunkCount"); + } + + const selected = [...issues] + .sort((left, right) => right.number - left.number) + // Issue-number partitioning stays stable if new issues arrive while the + // serial matrix jobs are processing the backlog. + .filter((issue) => issue.number % chunkCount === chunkIndex); + return maxIssues > 0 ? selected.slice(0, maxIssues) : selected; +} + +export async function listOpenUnassignedIssues(client) { + const issues = []; + for (let page = 1; ; page += 1) { + const items = await client.request( + "GET", + `/repos/${client.repository}/issues?state=open&sort=created&direction=desc&per_page=100&page=${page}`, + ); + issues.push(...items.filter((issue) => !issue.pull_request && (issue.assignees || []).length === 0)); + if (items.length < 100) break; + } + return issues; +} + +export async function backfill({ + client, + chunkIndex, + chunkCount, + maxIssues = 0, + searchDelayMs = DEFAULT_SEARCH_DELAY_MS, +}) { + const issues = selectChunk(await listOpenUnassignedIssues(client), { chunkIndex, chunkCount, maxIssues }); + const originalSearchIssues = client.searchIssues.bind(client); + let lastSearchStartedAt = 0; + client.searchIssues = async (query) => { + const remainingDelay = searchDelayMs - (Date.now() - lastSearchStartedAt); + if (remainingDelay > 0) await sleep(remainingDelay); + lastSearchStartedAt = Date.now(); + return originalSearchIssues(query); + }; + + let suggestedIssues = 0; + let suggestionCount = 0; + const failures = []; + try { + for (const [index, issue] of issues.entries()) { + console.log(`[${index + 1}/${issues.length}] Processing #${issue.number}: ${issue.title}`); + try { + const candidates = await run({ issue, client }); + if (candidates.length > 0) { + suggestedIssues += 1; + suggestionCount += candidates.length; + } + } catch (error) { + failures.push({ number: issue.number, message: error instanceof Error ? error.message : String(error) }); + console.error(`Failed to process #${issue.number}: ${failures.at(-1).message}`); + } + } + } finally { + client.searchIssues = originalSearchIssues; + } + + const summary = { processed: issues.length, suggestedIssues, suggestionCount, failures }; + console.log(`Backfill summary: ${JSON.stringify(summary)}`); + if (failures.length > 0) throw new Error(`Backfill completed with ${failures.length} failed issue(s)`); + return summary; +} + +if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) { + const client = new GitHubClient({ + token: process.env.GITHUB_TOKEN, + repository: process.env.GITHUB_REPOSITORY, + apiBase: process.env.GITHUB_API_URL, + }); + await backfill({ + client, + chunkIndex: integerValue(process.env.BACKFILL_CHUNK_INDEX, 0, "BACKFILL_CHUNK_INDEX"), + chunkCount: integerValue(process.env.BACKFILL_CHUNK_COUNT, 1, "BACKFILL_CHUNK_COUNT"), + maxIssues: integerValue(process.env.BACKFILL_MAX_ISSUES, 0, "BACKFILL_MAX_ISSUES"), + searchDelayMs: integerValue( + process.env.BACKFILL_SEARCH_DELAY_MS, + DEFAULT_SEARCH_DELAY_MS, + "BACKFILL_SEARCH_DELAY_MS", + ), + }); +} diff --git a/.github/scripts/backfill-similar-issues.test.mjs b/.github/scripts/backfill-similar-issues.test.mjs new file mode 100644 index 000000000..4c5aeefcd --- /dev/null +++ b/.github/scripts/backfill-similar-issues.test.mjs @@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + backfill, + listOpenUnassignedIssues, + selectChunk, +} from "./backfill-similar-issues.mjs"; + +test("selectChunk partitions issue numbers deterministically", () => { + const issues = [1, 2, 3, 4, 5, 6].map((number) => ({ number })); + + assert.deepEqual(selectChunk(issues, { chunkIndex: 0, chunkCount: 3 }).map(({ number }) => number), [6, 3]); + assert.deepEqual(selectChunk(issues, { chunkIndex: 1, chunkCount: 3 }).map(({ number }) => number), [4, 1]); + assert.deepEqual( + selectChunk(issues, { chunkIndex: 2, chunkCount: 3, maxIssues: 1 }).map(({ number }) => number), + [5], + ); +}); + +test("listOpenUnassignedIssues filters pull requests and assigned issues across pages", async () => { + const firstPage = Array.from({ length: 100 }, (_, index) => ({ + number: index + 1, + assignees: index === 0 ? [{ login: "owner" }] : [], + ...(index === 1 ? { pull_request: { url: "https://example.test/pr/2" } } : {}), + })); + const client = { + repository: "t8y2/dbx", + request: async (_method, path) => { + const page = new URL(path, "https://api.github.test").searchParams.get("page"); + return page === "1" ? firstPage : [{ number: 101, assignees: [] }]; + }, + }; + + const issues = await listOpenUnassignedIssues(client); + assert.equal(issues.length, 99); + assert.equal(issues.some(({ number }) => number === 1), false); + assert.equal(issues.some(({ number }) => number === 2), false); + assert.equal(issues.at(-1).number, 101); +}); + +test("backfill skips existing comments and searches only its chunk", async () => { + const searchedTitles = []; + const client = { + repository: "t8y2/dbx", + request: async () => [ + { number: 6, title: "six", body: "body", labels: [], assignees: [] }, + { number: 5, title: "five", body: "body", labels: [], assignees: [] }, + { number: 3, title: "three", body: "body", labels: [], assignees: [] }, + ], + hasExistingComment: async (number) => number === 6, + searchIssues: async (query) => { + searchedTitles.push(query); + return { search_type: "hybrid", items: [] }; + }, + comment: async () => { + throw new Error("comment should not be called"); + }, + }; + + const summary = await backfill({ client, chunkIndex: 0, chunkCount: 3, searchDelayMs: 0 }); + assert.deepEqual(summary, { processed: 2, suggestedIssues: 0, suggestionCount: 0, failures: [] }); + assert.deepEqual(searchedTitles, ["three"]); +}); diff --git a/.github/workflows/similar-issues-backfill.yml b/.github/workflows/similar-issues-backfill.yml new file mode 100644 index 000000000..986e9d057 --- /dev/null +++ b/.github/workflows/similar-issues-backfill.yml @@ -0,0 +1,60 @@ +name: Backfill Similar Issues + +on: + workflow_dispatch: + inputs: + dry_run: + description: Log suggestions without posting comments + required: false + default: false + type: boolean + max_issues_per_chunk: + description: Maximum issues per chunk; 0 processes the full backlog + required: false + default: "0" + type: string + +permissions: + contents: read + +concurrency: + group: similar-issues-backfill + cancel-in-progress: false + +jobs: + backfill: + name: Backfill chunk ${{ matrix.chunk_index }} + runs-on: ubuntu-latest + timeout-minutes: 55 + strategy: + fail-fast: false + max-parallel: 1 + matrix: + chunk_index: [0, 1, 2] + steps: + - uses: actions/checkout@v5 + + - name: Create DBX bot token + id: app-token + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ vars.DBX_BOT_APP_ID }} + private-key: ${{ secrets.DBX_BOT_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: dbx + permission-issues: write + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: 22.13.0 + + - name: Backfill similar issue suggestions + run: node .github/scripts/backfill-similar-issues.mjs + env: + GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} + BACKFILL_CHUNK_INDEX: ${{ matrix.chunk_index }} + BACKFILL_CHUNK_COUNT: "3" + BACKFILL_MAX_ISSUES: ${{ inputs.max_issues_per_chunk }} + BACKFILL_SEARCH_DELAY_MS: "7000" + DRY_RUN: ${{ inputs.dry_run }}