From d618ac31ae18ea0341383d06811ab24555531a8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 1 Nov 2026 23:13:38 +0900 Subject: [PATCH 1/5] perf: speed up full Project reconciliation --- .github/PROJECT_SYNC.md | 9 +++ scripts/sync_github_project.py | 113 ++++++++++++++++++++++++---- tests/test_project_delivery.py | 132 +++++++++++++++++++++++++++++++-- 3 files changed, 231 insertions(+), 23 deletions(-) diff --git a/.github/PROJECT_SYNC.md b/.github/PROJECT_SYNC.md index b05cbf53389..ccd8dc59c4f 100644 --- a/.github/PROJECT_SYNC.md +++ b/.github/PROJECT_SYNC.md @@ -47,6 +47,15 @@ or deletes source Issues/PRs. 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. +- 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 + pair; missing fetched tags fail closed. +- Local microbenchmark against the full checkout: 237 version tags and 20 sampled + tag commits (version order used as a proxy for publication order). Pairwise + `merge-base` checks ran 2,110 processes in 31.67 s; `tag --contains` ran 20 in + 0.35 s (90x on this sample). This measures Git ancestry only, not GraphQL or + full-workflow wall time. - Privileged jobs run trusted default-branch code only, use full Git history/tags, and never execute PR code. PR tests use no Project secret. diff --git a/scripts/sync_github_project.py b/scripts/sync_github_project.py index 21ad26a155e..e5df9e578ec 100644 --- a/scripts/sync_github_project.py +++ b/scripts/sync_github_project.py @@ -5,6 +5,7 @@ import os import re import subprocess +import sys import urllib.error import urllib.request from functools import cache @@ -22,13 +23,14 @@ DELIVERY_OPTIONS = ("未关联实现", "尚未合入", "已合入待发布", "已发布") -def connection(query, path, *, initial=None, **variables): +def connection(query, path, *, initial=None, progress=None, **variables): """Read every page and fail if the cursor stalls. Args: query: GraphQL operation accepting a cursor variable. path: Keys leading to a connection in the response. initial: Optional first page already returned in a parent query. + progress: Optional label for flushed progress output. **variables: Other operation variables. Returns: @@ -37,7 +39,7 @@ def connection(query, path, *, initial=None, **variables): Raises: RuntimeError: A cursor does not advance or the connection is inaccessible. """ - nodes, cursor, seen = [], None, set() + nodes, cursor, seen, pages = [], None, set(), 0 while True: if initial is not None: data, initial = initial, None @@ -48,6 +50,13 @@ def connection(query, path, *, initial=None, **variables): if not isinstance(data, dict): raise RuntimeError("GitHub connection is inaccessible") nodes.extend(node for node in data["nodes"] if node) + pages += 1 + if progress: + print( + f"Project sync: {progress}, page {pages}, {len(nodes)} items", + file=sys.stderr, + flush=True, + ) page = data["pageInfo"] if not page["hasNextPage"]: return nodes @@ -171,6 +180,53 @@ def ancestor(commit, ref): return result.returncode == 0 +@cache +def tag_names(): + """Read fetched tag names once so missing release tags fail closed.""" + result = subprocess.run( + ["git", "tag", "--list"], + cwd=ROOT, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + if result.returncode: + raise RuntimeError("Cannot list fetched release tags") + return frozenset(result.stdout.splitlines()) + + +@cache +def tags_containing(commit): + """Return tags containing a full commit using one Git graph walk. + + Args: + commit: Full implementation commit OID. + + Returns: + Tag names whose peeled commit descends from the implementation commit. + + Raises: + ValueError: Commit OID is invalid. + RuntimeError: The repository cannot answer the containment query. + """ + if not re.fullmatch(r"[0-9a-f]{40}", commit): + raise ValueError("Invalid implementation commit") + result = subprocess.run( + ["git", "tag", "--contains", commit], + cwd=ROOT, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + if result.returncode: + raise RuntimeError( + "Cannot verify release tag ancestry; fetch full history and tags" + ) + return frozenset(result.stdout.splitlines()) + + def delivery(content, current, linked, releases, mainline): """Calculate implementation links and the earliest proven stable release. @@ -192,25 +248,28 @@ def delivery(content, current, linked, releases, mainline): all_integrated = ( bool(merged) and len(commits) == len(merged) and integrated == commits ) - published = None - for release in sorted( + stable_releases = sorted( ( r for r in releases if not r["isDraft"] and not r["isPrerelease"] and r.get("publishedAt") ), key=lambda r: r["publishedAt"], - ): - if ( - all_merged - and all_integrated - and all( - ancestor(commit, f"refs/tags/{release['tagName']}") - for commit in integrated + ) + published = None + if all_merged and all_integrated and stable_releases: + release_names = {r["tagName"] for r in stable_releases} + missing = release_names - tag_names() + if missing: + raise RuntimeError( + "Stable release tags are missing; fetch full history and tags" ) - ): - published = release - break + common_tags = release_names.copy() + for commit in integrated: + common_tags.intersection_update(tags_containing(commit)) + published = next( + (r for r in stable_releases if r["tagName"] in common_tags), None + ) progress = ( "已发布" if published @@ -580,6 +639,7 @@ def reconcile( ... on ProjectV2SingleSelectField{id name options{id name}} }pageInfo{hasNextPage endCursor}}}}}""", ("node", "fields"), + progress="Project fields", project=project, ) fields = {} @@ -632,6 +692,7 @@ def reconcile( }pageInfo{hasNextPage endCursor}} }pageInfo{hasNextPage endCursor}}}}}""", ("node", "items"), + progress="Project items", project=project, ) tracked = { @@ -648,6 +709,7 @@ def reconcile( labels(first:100){nodes{name}pageInfo{hasNextPage endCursor}}} pageInfo{hasNextPage endCursor}}}}""", ("repository", "issues"), + progress="Repository issues", states=["OPEN", "CLOSED"], **variables, ) @@ -659,6 +721,7 @@ def reconcile( pageInfo{hasNextPage endCursor}} }pageInfo{hasNextPage endCursor}}}}""", ("repository", "pullRequests"), + progress="Repository PRs", states=["OPEN", "CLOSED", "MERGED"], **variables, ) @@ -714,6 +777,7 @@ def reconcile( releases(first:100,after:$cursor){nodes{tagName url publishedAt isDraft isPrerelease} pageInfo{hasNextPage endCursor}}}}""", ("repository", "releases"), + progress="Repository releases", **variables, ) mainline = subprocess.run( @@ -725,7 +789,19 @@ def reconcile( check=True, ).stdout.strip() plan = [] - for content in candidates: + if subject is None: + print( + f"Project sync: calculating delivery for {len(candidates)} candidates", + file=sys.stderr, + flush=True, + ) + for index, content in enumerate(candidates, 1): + if subject is None and index % 50 == 0: + print( + f"Project sync: calculated {index}/{len(candidates)} candidates", + file=sys.stderr, + flush=True, + ) item = tracked.get(content["id"]) if item and item["isArchived"]: continue @@ -903,6 +979,13 @@ def main(argv=None): not isinstance(v, str) or not v.strip() for v in status_names.values() ) or len(set(status_names.values())) != len(STATUS_OPTIONS): raise ValueError("Status names must be nonempty and distinct") + print( + "Project sync: starting full reconciliation" + if subject is None + else f"Project sync: starting bounded sync for item #{subject}", + file=sys.stderr, + flush=True, + ) try: plan = reconcile( project, diff --git a/tests/test_project_delivery.py b/tests/test_project_delivery.py index 8520d049979..e239b70d4ac 100644 --- a/tests/test_project_delivery.py +++ b/tests/test_project_delivery.py @@ -1,6 +1,8 @@ """Network-free tests for full Project delivery reconciliation.""" import importlib.util +import io +import tempfile import unittest from pathlib import Path from unittest.mock import Mock, patch @@ -235,10 +237,10 @@ def test_multiple_implementations_need_all_commits_in_release(self): "isPrerelease": False, } ] - with patch.object( - sync, - "ancestor", - side_effect=lambda commit, ref: ref == "c" * 40 or commit == "a" * 40, + with ( + patch.object(sync, "ancestor", return_value=True), + patch.object(sync, "tag_names", return_value={"v1"}), + patch.object(sync, "tags_containing", side_effect=[{"v1"}, set()]), ): desired = sync.delivery(issue, {}, prs, releases, "c" * 40) self.assertEqual(desired["发布版本"], "") @@ -301,6 +303,110 @@ def test_git_ancestry_errors_fail_closed(self): with self.assertRaises(ValueError): sync.ancestor("--bad-option", "refs/tags/v1") + def test_tags_containing_commit_handles_annotated_lightweight_and_divergent_tags( + self, + ): + self.addCleanup(sync.tag_names.cache_clear) + self.addCleanup(sync.tags_containing.cache_clear) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + + def git(*args): + return sync.subprocess.run( + ["git", *args], cwd=root, capture_output=True, text=True, check=True + ).stdout.strip() + + git("init", "-b", "master") + git("config", "user.email", "test@example.com") + git("config", "user.name", "Test") + (root / "file").write_text("base") + git("add", "file") + git("commit", "-m", "base") + base = git("rev-parse", "HEAD") + git("tag", "v1") + (root / "file").write_text("release two") + git("commit", "-am", "release two") + second = git("rev-parse", "HEAD") + git("tag", "-a", "v2", "-m", "annotated") + (root / "file").write_text("release three") + git("commit", "-am", "release three") + git("tag", "v3") + with patch.object(sync, "ROOT", root): + sync.tag_names.cache_clear() + sync.tags_containing.cache_clear() + self.assertEqual(sync.tags_containing(base), {"v1", "v2", "v3"}) + self.assertEqual(sync.tags_containing(second), {"v2", "v3"}) + releases = [ + { + "tagName": tag, + "publishedAt": date, + "url": tag, + "isDraft": False, + "isPrerelease": False, + } + for tag, date in [ + ("v1", "2026-01-01"), + ("v2", "2026-02-01"), + ("v3", "2026-03-01"), + ] + ] + pr = { + "__typename": "PullRequest", + "state": "MERGED", + "mergeCommit": {"oid": second}, + "url": "pr", + } + self.assertEqual( + sync.delivery(pr, {}, [], releases, git("rev-parse", "HEAD"))[ + "发布版本" + ], + "v2", + ) + + def test_tag_containment_failure_fails_closed(self): + sync.tags_containing.cache_clear() + with patch.object(sync.subprocess, "run", return_value=Mock(returncode=128)): + with self.assertRaisesRegex(RuntimeError, "tags"): + sync.tags_containing("a" * 40) + + def test_missing_stable_release_tag_fails_closed(self): + pr = { + "__typename": "PullRequest", + "state": "MERGED", + "mergeCommit": {"oid": "a" * 40}, + "url": "pr", + } + releases = [ + { + "tagName": "v1", + "publishedAt": "2026-01-01", + "url": "release", + "isDraft": False, + "isPrerelease": False, + } + ] + with ( + patch.object(sync, "ancestor", return_value=True), + patch.object(sync, "tag_names", return_value=set()), + patch.object(sync, "tags_containing") as containing, + ): + with self.assertRaisesRegex( + RuntimeError, "Stable release tags are missing" + ): + sync.delivery(pr, {}, [], releases, "b" * 40) + containing.assert_not_called() + + def test_connection_logs_page_progress_only_when_requested(self): + data = {"page": {"nodes": [1], "pageInfo": {"hasNextPage": False}}} + with ( + patch.object(sync, "graphql", return_value=data), + patch("sys.stderr", new_callable=io.StringIO) as output, + ): + self.assertEqual( + sync.connection("query", ("page",), progress="Issues"), [1] + ) + self.assertIn("Issues, page 1, 1 items", output.getvalue()) + def test_missing_recovery_boundary_fails_before_mutations(self): for metadata in ( {"node": None}, @@ -448,16 +554,23 @@ def test_release_requires_mainline_and_actual_tag_ancestry(self): "isPrerelease": False, }, ] - with patch.object(sync, "ancestor", side_effect=[True, False, True]): + with ( + patch.object(sync, "ancestor", return_value=True), + patch.object(sync, "tag_names", return_value={"v1", "v2"}), + patch.object(sync, "tags_containing", return_value={"v2"}), + ): desired = sync.delivery(merged, {}, [], releases, "b" * 40) self.assertEqual(desired["发布版本"], "v2") self.assertEqual(desired["发布说明"], "release2") self.assertEqual(desired["交付进度"], "已发布") - with patch.object(sync, "ancestor", return_value=False) as ancestor: + with ( + patch.object(sync, "ancestor", return_value=True), + patch.object(sync, "tag_names", return_value={"v1", "v2"}), + patch.object(sync, "tags_containing", return_value=set()), + ): self.assertEqual( sync.delivery(merged, {}, [], releases, "b" * 40)["发布版本"], "" ) - self.assertEqual(ancestor.call_count, 1) def test_prerelease_and_draft_are_not_stable_delivery(self): merged = { @@ -475,7 +588,10 @@ def test_prerelease_and_draft_are_not_stable_delivery(self): } for draft, pre in [(True, False), (False, True)] ] - with patch.object(sync, "ancestor", return_value=True): + with ( + patch.object(sync, "ancestor", return_value=True), + patch.object(sync, "tag_names", return_value=set()), + ): desired = sync.delivery(merged, {}, [], releases, "b" * 40) self.assertEqual(desired["交付进度"], "已合入待发布") self.assertEqual(desired["发布版本"], "") From 80e7a2fb928ea280852a8871e32804db90521f55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 1 Nov 2026 23:36:01 +0900 Subject: [PATCH 2/5] fix: normalize nested Project field values --- scripts/sync_github_project.py | 11 +++++ tests/test_project_events.py | 90 ++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) diff --git a/scripts/sync_github_project.py b/scripts/sync_github_project.py index e5df9e578ec..7b93e561c30 100644 --- a/scripts/sync_github_project.py +++ b/scripts/sync_github_project.py @@ -489,6 +489,17 @@ def read_subject(repository, number): initial=content[field], id=content["id"], ) + for item in content["projectItems"]: + item["fieldValues"] = connection( + """query($id:ID!,$cursor:String){node(id:$id){... on ProjectV2Item{ + fieldValues(first:100,after:$cursor){nodes{ + ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} + ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}} + }pageInfo{hasNextPage endCursor}}}}} """.strip(), + ("node", "fieldValues"), + initial=item["fieldValues"], + id=item["id"], + ) return content diff --git a/tests/test_project_events.py b/tests/test_project_events.py index 442d5825c19..c5b41529e39 100644 --- a/tests/test_project_events.py +++ b/tests/test_project_events.py @@ -174,6 +174,96 @@ def test_subject_reads_never_scan_repository_or_project_connections(self): self.assertNotIn(forbidden, query) self.assertIn("issueOrPullRequest(number:", query) + def test_subject_normalizes_nested_project_field_values_connections(self): + node = { + "__typename": "Issue", + "id": "I", + "number": 1, + "issueState": "OPEN", + "stateReason": None, + "closedAt": None, + "labels": { + "nodes": [], + "pageInfo": {"hasNextPage": False, "endCursor": None}, + }, + "timelineItems": { + "nodes": [], + "pageInfo": {"hasNextPage": False, "endCursor": None}, + }, + "projectItems": { + "nodes": [ + { + "id": "ITEM", + "isArchived": False, + "project": {"id": "P"}, + "fieldValues": { + "nodes": [{"field": {"name": "实现关联"}, "text": "pr"}], + "pageInfo": {"hasNextPage": False, "endCursor": None}, + }, + } + ], + "pageInfo": {"hasNextPage": False, "endCursor": None}, + }, + } + with patch.object( + sync, "graphql", return_value={"repository": {"issueOrPullRequest": node}} + ): + result = sync.read_subject("AstrBotDevs/AstrBot", 1) + self.assertEqual(result["projectItems"][0]["fieldValues"][0]["text"], "pr") + + def test_subject_paginates_nested_project_field_values(self): + first_value = {"field": {"name": "Status"}, "name": "Todo"} + second_value = {"field": {"name": "实现关联"}, "text": "pr"} + node = { + "__typename": "Issue", + "id": "I", + "number": 1, + "issueState": "OPEN", + "stateReason": None, + "closedAt": None, + "labels": { + "nodes": [], + "pageInfo": {"hasNextPage": False, "endCursor": None}, + }, + "timelineItems": { + "nodes": [], + "pageInfo": {"hasNextPage": False, "endCursor": None}, + }, + "projectItems": { + "nodes": [ + { + "id": "ITEM", + "isArchived": False, + "project": {"id": "P"}, + "fieldValues": { + "nodes": [first_value], + "pageInfo": {"hasNextPage": True, "endCursor": "CURSOR"}, + }, + } + ], + "pageInfo": {"hasNextPage": False, "endCursor": None}, + }, + } + next_page = { + "node": { + "fieldValues": { + "nodes": [second_value], + "pageInfo": {"hasNextPage": False, "endCursor": None}, + } + } + } + with patch.object( + sync, + "graphql", + side_effect=[{"repository": {"issueOrPullRequest": node}}, next_page], + ) as graphql: + result = sync.read_subject("AstrBotDevs/AstrBot", 1) + self.assertEqual( + result["projectItems"][0]["fieldValues"], [first_value, second_value] + ) + self.assertEqual(graphql.call_count, 2) + self.assertEqual(graphql.call_args_list[1].args[1]["cursor"], "CURSOR") + def test_apply_failure_reports_confirmed_unknown_and_unattempted(self): plan = [ { From 547746deaaff870bed7192f9efd9dc6867ee9173 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 1 Nov 2026 23:42:25 +0900 Subject: [PATCH 3/5] test: assert nested Project item pagination ID --- tests/test_project_events.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_project_events.py b/tests/test_project_events.py index c5b41529e39..733e8f02d5c 100644 --- a/tests/test_project_events.py +++ b/tests/test_project_events.py @@ -263,6 +263,9 @@ def test_subject_paginates_nested_project_field_values(self): ) self.assertEqual(graphql.call_count, 2) self.assertEqual(graphql.call_args_list[1].args[1]["cursor"], "CURSOR") + self.assertEqual(graphql.call_args_list[1].args[1]["id"], "ITEM") + self.assertIn("ProjectV2Item", graphql.call_args_list[1].args[0]) + self.assertIn("fieldValues", graphql.call_args_list[1].args[0]) def test_apply_failure_reports_confirmed_unknown_and_unattempted(self): plan = [ From f431b9cecde3a972c472ee12523be57696d3f78f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 1 Nov 2026 23:50:43 +0900 Subject: [PATCH 4/5] test: verify all release commits are checked --- tests/test_project_delivery.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_project_delivery.py b/tests/test_project_delivery.py index e239b70d4ac..7d9d8d7e43c 100644 --- a/tests/test_project_delivery.py +++ b/tests/test_project_delivery.py @@ -240,11 +240,19 @@ def test_multiple_implementations_need_all_commits_in_release(self): with ( patch.object(sync, "ancestor", return_value=True), patch.object(sync, "tag_names", return_value={"v1"}), - patch.object(sync, "tags_containing", side_effect=[{"v1"}, set()]), + patch.object( + sync, + "tags_containing", + side_effect=lambda commit: {"v1"} if commit == "a" * 40 else set(), + ) as tags_containing, ): desired = sync.delivery(issue, {}, prs, releases, "c" * 40) self.assertEqual(desired["发布版本"], "") self.assertEqual(desired["Status"], "Needs verification") + self.assertEqual( + {call.args[0] for call in tags_containing.call_args_list}, + {"a" * 40, "b" * 40}, + ) def test_open_implementation_prevents_released_delivery(self): issue = {"__typename": "Issue", "state": "OPEN", "labels": []} From 9944db45dca28a0a9dc40e4c0571a2fb8e5fd657 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 1 Nov 2026 23:57:13 +0900 Subject: [PATCH 5/5] test: assert nested field values cursor binding --- tests/test_project_events.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_project_events.py b/tests/test_project_events.py index 733e8f02d5c..78f7d1a97f6 100644 --- a/tests/test_project_events.py +++ b/tests/test_project_events.py @@ -266,6 +266,9 @@ def test_subject_paginates_nested_project_field_values(self): self.assertEqual(graphql.call_args_list[1].args[1]["id"], "ITEM") self.assertIn("ProjectV2Item", graphql.call_args_list[1].args[0]) self.assertIn("fieldValues", graphql.call_args_list[1].args[0]) + self.assertIn( + "fieldValues(first:100,after:$cursor)", graphql.call_args_list[1].args[0] + ) def test_apply_failure_reports_confirmed_unknown_and_unattempted(self): plan = [