diff --git a/.github/PROJECT_SYNC.md b/.github/PROJECT_SYNC.md index ccd8dc59c4f..61a27160027 100644 --- a/.github/PROJECT_SYNC.md +++ b/.github/PROJECT_SYNC.md @@ -46,7 +46,9 @@ or deletes source Issues/PRs. skip unchanged values and clear stale text. Paginate every GraphQL connection, reject stalled cursors, and serialize runs. Apply mode prints the plan first; on failure it reports confirmed, outcome-unknown and unattempted mutation counts, - with affected item/field, so partial writes can be reconciled. + with affected item/field, so partial writes can be reconciled. Apply uses four + workers across distinct Project items; mutations within each item stay ordered. + This is bounded concurrency, not a guarantee against GitHub rate limits. - Full scans log phase/page and candidate progress to the Actions log. Stable release membership is determined with one `git tag --contains` graph walk per distinct merge commit instead of one `git merge-base` process per commit/tag diff --git a/scripts/sync_github_project.py b/scripts/sync_github_project.py index 47a9cf95e43..5deb0dcb50b 100644 --- a/scripts/sync_github_project.py +++ b/scripts/sync_github_project.py @@ -9,6 +9,7 @@ import time import urllib.error import urllib.request +from concurrent.futures import ThreadPoolExecutor, as_completed from functools import cache from pathlib import Path @@ -22,6 +23,7 @@ "Closed unmerged", ) DELIVERY_OPTIONS = ("未关联实现", "尚未合入", "已合入待发布", "已发布") +APPLY_WORKERS = 4 def connection(query, path, *, initial=None, progress=None, **variables): @@ -317,11 +319,21 @@ def apply_plan(project, fields, plan, *, apply=False): if not apply: return total = sum(len(entry["changes"]) + (not entry["item"]) for entry in plan) - confirmed = 0 - for entry in plan: + + def apply_entry(entry): + """Apply one item sequentially inside one worker. + + Args: + entry: Precomputed item plan. + + Returns: + Confirmed mutation count and sanitized failure metadata. + """ + confirmed = 0 item = entry["item"] - if not item: - try: + failed_field = "addProjectItem" + try: + if not item: result = graphql( """mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: {projectId:$project, contentId:$content}) { item { id } } @@ -329,35 +341,11 @@ def apply_plan(project, fields, plan, *, apply=False): {"project": project, "content": entry["content"]}, ) item = result["addProjectV2ItemById"]["item"]["id"] - except (RuntimeError, ValueError, OSError, KeyError, TypeError): - print( - json.dumps( - { - "confirmed": confirmed, - "unknown": 1, - "unattempted": total - confirmed - 1, - "number": entry["number"], - "field": "addProjectItem", - } - ), - flush=True, - ) - raise - confirmed += 1 - for name, value in entry["changes"].items(): - field = fields[name] - variables = {"project": project, "item": item, "field": field["id"]} - if value != "": - variables["value"] = ( - { - "singleSelectOptionId": next( - o["id"] for o in field["options"] if o["name"] == value - ) - } - if "options" in field - else {"text": value} - ) - try: + confirmed += 1 + for name, value in entry["changes"].items(): + failed_field = name + field = fields[name] + variables = {"project": project, "item": item, "field": field["id"]} if value == "": graphql( """mutation($project:ID!,$item:ID!,$field:ID!){ @@ -366,28 +354,72 @@ def apply_plan(project, fields, plan, *, apply=False): variables, ) else: + variables["value"] = ( + { + "singleSelectOptionId": next( + o["id"] for o in field["options"] if o["name"] == value + ) + } + if "options" in field + else {"text": value} + ) graphql( """mutation($project:ID!,$item:ID!,$field:ID!,$value:ProjectV2FieldValue!){ - updateProjectV2ItemFieldValue(input:{projectId:$project,itemId:$item,fieldId:$field,value:$value}){projectV2Item{id}} + updateProjectV2ItemFieldValue(input:{projectId:$project,itemId:$item,fieldId:$field,value:$value}){projectV2Item{id}} }""", variables, ) - except (RuntimeError, ValueError, OSError): - print( - json.dumps( - { - "confirmed": confirmed, - "unknown": 1, - "unattempted": total - confirmed - 1, - "number": entry["number"], - "field": name, - }, - ensure_ascii=False, - ), - flush=True, - ) - raise - confirmed += 1 + confirmed += 1 + except (RuntimeError, ValueError, OSError, KeyError, TypeError, StopIteration): + return { + "confirmed": confirmed, + "unknown": 1, + "field": failed_field, + "number": entry["number"], + } + return { + "confirmed": confirmed, + "unknown": 0, + "field": None, + "number": entry["number"], + } + + confirmed = 0 + unknown = 0 + failures = [] + with ThreadPoolExecutor( + max_workers=APPLY_WORKERS, thread_name_prefix="project-sync" + ) as executor: + futures = [executor.submit(apply_entry, entry) for entry in plan] + for completed, future in enumerate(as_completed(futures), 1): + result = future.result() + confirmed += result["confirmed"] + unknown += result["unknown"] + if result["unknown"]: + failures.append(result) + print( + json.dumps( + {"completed_items": completed, "total_items": len(plan), **result} + ), + flush=True, + ) + if failures: + first = failures[0] + print( + json.dumps( + { + "confirmed": confirmed, + "unknown": unknown, + "unattempted": total - confirmed - unknown, + "number": first["number"], + "field": first["field"], + } + ), + flush=True, + ) + raise RuntimeError( + "Project mutation failed; rerun reconciliation to repair unknown outcomes" + ) print( json.dumps({"confirmed": confirmed, "unknown": 0, "unattempted": 0}), flush=True ) diff --git a/tests/test_project_delivery.py b/tests/test_project_delivery.py index cc457668822..9295972aa6b 100644 --- a/tests/test_project_delivery.py +++ b/tests/test_project_delivery.py @@ -3,6 +3,8 @@ import importlib.util import io import tempfile +import threading +import time import unittest from pathlib import Path from unittest.mock import Mock, patch @@ -646,6 +648,49 @@ def test_dry_run_does_not_mutate_and_apply_skips_equal_fields(self): api.call_args_list[1].args[1]["value"], {"singleSelectOptionId": "D"} ) + def test_apply_uses_four_workers_and_keeps_each_item_mutations_sequential(self): + plan = [ + { + "content": f"C{index}", + "item": f"I{index}", + "number": index, + "changes": {"Status": "Done", "发布版本": f"v{index}"}, + } + for index in range(8) + ] + fields = { + "Status": {"id": "S", "options": [{"name": "Done", "id": "D"}]}, + "发布版本": {"id": "V"}, + } + active, maximum, active_per_item, maximum_per_item = 0, 0, {}, {} + queries, lock = [], threading.Lock() + + def api(query, variables): + nonlocal active, maximum + with lock: + active += 1 + maximum = max(maximum, active) + active_per_item[variables["item"]] = ( + active_per_item.get(variables["item"], 0) + 1 + ) + maximum_per_item[variables["item"]] = max( + maximum_per_item.get(variables["item"], 0), + active_per_item[variables["item"]], + ) + queries.append((variables["item"], variables["field"])) + time.sleep(0.01) + with lock: + active -= 1 + active_per_item[variables["item"]] -= 1 + return {} + + with patch.object(sync, "graphql", side_effect=api): + sync.apply_plan("P", fields, plan, apply=True) + self.assertEqual(sync.APPLY_WORKERS, 4) + self.assertEqual(maximum, 4) + self.assertEqual(set(maximum_per_item.values()), {1}) + self.assertEqual(len(queries), 16) + if __name__ == "__main__": unittest.main()