This is an automated email from the ASF dual-hosted git repository.

shuke987 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 57bc92eaefd [improvement](ci) Reduce hosted runner waits for TeamCity 
and cloud review (#71162)
57bc92eaefd is described below

commit 57bc92eaefd1d6f37489b7fb175179caf2252f89
Author: shuke <[email protected]>
AuthorDate: Tue Dec 1 16:56:54 2026 +0800

    [improvement](ci) Reduce hosted runner waits for TeamCity and cloud review 
(#71162)
    
    PR comments select TeamCity lanes, record one approval per lane and
    submit the batch through FC. For automated reviews, a trusted cloud
    publisher writes a verified receipt that feeds the required
    `code-review` status.
---
 .github/scripts/debug_review.py                    |  67 ++++++-------
 .github/scripts/resolve_code_review_status.py      |  72 ++++++++++++--
 .github/scripts/test_debug_review.py               | 104 ++++++++++++---------
 .github/scripts/test_resolve_code_review_status.py |  88 +++++++++++++++++
 .github/workflows/approve-label-trigger.yml        |   2 +-
 .github/workflows/approve-label.yml                |   2 +-
 .github/workflows/code-review-runner.yml           |  14 ++-
 .github/workflows/comment-to-trigger-teamcity.yml  |   8 +-
 .github/workflows/title-checker.yml                |   2 +-
 .../pipeline/common/tests/test_teamcity_utils.py   |   2 +-
 10 files changed, 259 insertions(+), 102 deletions(-)

diff --git a/.github/scripts/debug_review.py b/.github/scripts/debug_review.py
index a41410d4cf9..e79b4cf1bdf 100644
--- a/.github/scripts/debug_review.py
+++ b/.github/scripts/debug_review.py
@@ -16,7 +16,7 @@
 # specific language governing permissions and limitations
 # under the License.
 
-"""Submit an authorized PR snapshot and synchronize its verified result with 
the merge gate."""
+"""Submit an authorized PR snapshot. The cloud publisher supplies the verified 
gate receipt."""
 import hashlib
 import http.client
 import json
@@ -56,15 +56,14 @@ def json_request(url, token, body=None):
         conn.close()
 
 
-def fc(path, body, expected):
+def submit_to_fc(body):
     url = os.environ["ACTIONS_ID_TOKEN_REQUEST_URL"]
     url += ("&" if "?" in url else "?") + urlencode({"audience": AUDIENCE})
-    # Each poll can outlive the previous GitHub OIDC token.
     for attempt in range(3):
         try:
             _, identity = json_request(url, 
os.environ["ACTIONS_ID_TOKEN_REQUEST_TOKEN"])
-            status, result = json_request(FC + path, identity["value"], body)
-            if status not in expected:
+            status, result = json_request(FC, identity["value"], body)
+            if status != 202:
                 raise ValueError(f"Unexpected FC HTTP {status}")
             return result
         except (OSError, http.client.HTTPException, TransientHTTPError):
@@ -141,7 +140,6 @@ def review(pr, head, base):
     request_id = "github:review:" + run
     repo_url = f"https://github.com/{repo}";
     run_url = f"{repo_url}/actions/runs/{run}"
-    pr_url = f"{repo_url}/pull/{pr}"
     source = f"code-review/source/automated/pr-{pr}/base-{base}"
 
     def current():
@@ -149,45 +147,40 @@ def review(pr, head, base):
         return live["state"] == "open" and live["head"]["sha"] == head and 
live["base"]["sha"] == base
 
     focus = requested_focus()
+    rerun = int(os.environ.get("GITHUB_RUN_ATTEMPT", "1")) > 1
     if not current():
+        if rerun:
+            raise ValueError("The PR snapshot changed. Post a new /review.")
         print("PR changed before dispatch")
         return
+    if rerun:
+        # FC and its inbox deduplicate by run ID across GitHub reruns. A run
+        # that already authorized another snapshot needs a new /review event.
+        expected = f"fc-review/v1/{pr}/{head}/{base}{focus_suffix(focus)}"
+        pages = 
gh(f"repos/{repo}/actions/runs/{run}/jobs?filter=all&per_page=100", 
"--paginate", "--slurp")
+        for page in pages:
+            for job in page["jobs"]:
+                if (job["conclusion"] == "success" and 
job["name"].startswith("fc-review/v1/")
+                        and job["name"] != expected):
+                    raise ValueError("This run authorized a different PR 
snapshot. Post a new /review.")
     snapshot = dict(pr_number=pr, head_sha=head, base_sha=base)
-    with Path(os.environ["GITHUB_OUTPUT"]).open("a") as outputs:
-        print(f"aggregate_head={head}", file=outputs)
     for context in ("code-review", source):
         gh(f"repos/{repo}/statuses/{head}", "-X", "POST", "-f", 
f"context={context}",
-           "-f", "state=pending", "-f", f"description=Automated review is 
running for PR #{pr}.",
+           "-f", "state=pending", "-f", "description=Waiting for the cloud 
review receipt.",
            "-f", f"target_url={run_url}")
-    if len(focus.encode()) > 8192:
-        raise ValueError("The cloud review focus exceeds 8192 UTF-8 bytes")
     payload = dict(snapshot, review_focus=focus) if focus else snapshot
-    receipt = fc("", payload, (202,))
-    if receipt.get("request_id") != request_id:
-        raise ValueError("Receipt belongs to another run")
-    print(f"Submitted {request_id} for PR #{pr}", flush=True)
-    while True:
-        row = fc("/status", {"request_id": request_id}, (200, 202))
-        if row.get("request_id") != request_id:
-            raise ValueError("Status belongs to another run")
-        state = row["state"]
-        if state != "awaiting_status":
-            if (any(row.get(k) != v for k, v in snapshot.items())
-                    or type(row.get("preview_only")) is not bool):
-                raise ValueError("Status does not match the authorized 
snapshot")
-            if row["preview_only"] or state == "previewed":
-                raise RuntimeError("The default review requires a publishing 
cloud worker")
-            if state == "completed":
-                if row["result"].get("gate_receipt") is not True:
-                    raise RuntimeError("The cloud publisher did not record a 
gate receipt")
-                verdict(row["result"], pr_url, run_url, pr)
-                return
-            if state == "superseded":
-                print("PR changed during review")
-                return
-            if state not in {"queued", "running", "publishing", "uncertain"}:
-                raise RuntimeError(f"Review ended with state {state}")
-        time.sleep(30)
+    try:
+        if len(focus.encode()) > 8192:
+            raise ValueError("The cloud review focus exceeds 8192 UTF-8 bytes")
+        receipt = submit_to_fc(payload)
+        if receipt.get("request_id") != request_id:
+            raise ValueError("Receipt belongs to another run")
+    except Exception:
+        gh(f"repos/{repo}/statuses/{head}", "-X", "POST", "-f", 
f"context={source}",
+           "-f", "state=error", "-f", f"description=Cloud review submission 
failed for PR #{pr}.",
+           "-f", f"target_url={run_url}")
+        raise
+    print(f"FC accepted {request_id} for PR #{pr}. The cloud publisher will 
report the result.")
 
 
 if __name__ == "__main__":
diff --git a/.github/scripts/resolve_code_review_status.py 
b/.github/scripts/resolve_code_review_status.py
index f23366e5ac1..9d5f65b2099 100644
--- a/.github/scripts/resolve_code_review_status.py
+++ b/.github/scripts/resolve_code_review_status.py
@@ -42,8 +42,31 @@ def completed_counts(pr, description):
                         description)
 
 
-def cloud_sources(statuses, repo_url):
-    # Replayed POSTs keep their first status ID, so an older run cannot 
displace a later verdict.
+def cloud_requests(statuses, repo_url):
+    # A rerun reuses the same durable request. Order distinct runs by the
+    # first pending status each one wrote, regardless of API page order.
+    first = {}
+    workflow_run = re.compile(re.escape(repo_url) + 
r"/actions/runs/[1-9][0-9]*")
+    for item in statuses:
+        if (isinstance(item, dict) and item.get("state") == "pending"
+                and 
re.fullmatch(r"code-review/source/automated/pr-[1-9][0-9]*/base-[0-9a-f]{40}", 
item.get("context") or "")
+                and (item.get("creator") or {}).get("login") == 
"github-actions[bot]"
+                and workflow_run.fullmatch(item.get("target_url") or "")):
+            key = (item["context"], item["target_url"])
+            if key not in first or item["id"] < first[key]["id"]:
+                first[key] = item
+    latest = {}
+    for (context, _), item in first.items():
+        # Legacy dispatchers submitted before polling. A poll was never proof
+        # that every subsequent submission had registered a pending status.
+        if item.get("description") != "Waiting for the cloud review receipt.":
+            continue
+        if context not in latest or item["id"] > latest[context]["id"]:
+            latest[context] = item
+    return first, latest
+
+
+def cloud_sources(statuses, repo_url, requests_by_run, requests):
     bot = os.getenv("DORIS_REVIEW_APP_BOT")
     receipts = {}
     for item in statuses:
@@ -51,9 +74,22 @@ def cloud_sources(statuses, repo_url):
             continue
         match = 
re.fullmatch(r"code-review/cloud/([1-9][0-9]*)/pr-([1-9][0-9]*)/base-([0-9a-f]{40})",
                              item.get("context") or "")
-        if not match or item.get("state") not in ("failure", "success"):
+        if not match or item.get("state") not in ("failure", "success", 
"error"):
             continue
         run, pr, base = match.groups()
+        context = f"code-review/source/automated/pr-{pr}/base-{base}"
+        run_url = f"{repo_url}/actions/runs/{run}"
+        key = (context, run_url)
+        latest = requests.get(context)
+        if item["state"] == "error":
+            # Operational failures belong to their submission, even on retry.
+            origin = requests_by_run.get(key)
+            if (origin and (not latest or latest["target_url"] == run_url) and 
item.get("target_url") == run_url
+                    and item.get("description") == f"Cloud review failed 
before a verdict for PR #{pr}."):
+                receipts.setdefault(key, dict(item, id=origin["id"], 
context=context))
+            continue
+        if item["state"] == "success" and latest and latest["target_url"] != 
run_url:
+            continue
         if not 
re.fullmatch(re.escape(f"{repo_url}/pull/{pr}#pullrequestreview-") + 
r"[1-9][0-9]*",
                             item.get("target_url") or ""):
             continue
@@ -68,9 +104,7 @@ def cloud_sources(statuses, repo_url):
             continue
         if item["state"] != expected:
             continue
-        context = f"code-review/source/automated/pr-{pr}/base-{base}"
-        key = (context, f"{repo_url}/actions/runs/{run}")
-        if key not in receipts or item["id"] < receipts[key]["id"]:
+        if key not in receipts or receipts[key]["state"] == "error" or 
item["id"] < receipts[key]["id"]:
             receipts[key] = dict(item, context=context)
     return receipts
 
@@ -105,7 +139,8 @@ def resolve_status(
             "pending", f"No open pull request currently uses {head_sha[:12]}."
         )
 
-    receipts = cloud_sources(statuses, repo_url)
+    requests_by_run, requests = cloud_requests(statuses, repo_url)
+    receipts = cloud_sources(statuses, repo_url, requests_by_run, requests)
     receipt_ids = {receipt["id"] for receipt in receipts.values()}
     latest_by_context: dict[str, dict[str, object]] = {}
     for item in [*statuses, *receipts.values()]:
@@ -118,8 +153,21 @@ def resolve_status(
             raise ResolutionError("commit status context or id is invalid")
         if not isinstance(state, str):
             raise ResolutionError("commit status state is invalid")
+        # Replaying an old submission must not reset a newer request on the
+        # same snapshot. Keep legacy non-run URLs and verified blockers intact.
+        latest = requests.get(context)
+        # The async dispatcher completes its automated source only through
+        # a verified cloud receipt. A rerun of the old poller can repost its 
PASS.
+        if latest and state == "success" and status_id not in receipt_ids:
+            continue
+        if (latest and state in ("pending", "error")
+                and (item.get("creator") or {}).get("login") == 
"github-actions[bot]"
+                and (context, item.get("target_url")) in requests_by_run
+                and item["target_url"] != latest["target_url"]):
+            continue
         # A cached running response may arrive after this run's terminal 
receipt.
-        if state == "pending" and (context, item.get("target_url")) in 
receipts:
+        terminal = receipts.get((context, item.get("target_url")))
+        if state in ("pending", "error") and terminal and item is not terminal:
             continue
         previous = latest_by_context.get(context)
         if previous is None or status_id > int(previous["id"]):
@@ -139,10 +187,15 @@ def resolve_status(
     approved_contexts: set[tuple[int, str]] = set()
     blocked_contexts: set[tuple[int, str]] = set()
     incomplete_contexts: set[tuple[int, str]] = set()
+    error_contexts = {}
     for context, item in latest_by_context.items():
         match = SOURCE_CONTEXT_RE.fullmatch(context)
         if match is not None and item["state"] == "success":
             approved_contexts.add((int(match.group(1)), 
match.group(2).casefold()))
+        elif match is not None and item["state"] == "error" and 
context.startswith("code-review/source/automated/"):
+            key = (int(match.group(1)), match.group(2).casefold())
+            blocked_contexts.add(key)
+            error_contexts[key] = item.get("target_url") or ""
         elif (match is not None and item["state"] == "failure"
               and context.startswith("code-review/source/automated/")):
             key = (int(match.group(1)), match.group(2).casefold())
@@ -166,6 +219,9 @@ def resolve_status(
     blocked = sorted((open_contexts - approved_contexts) & blocked_contexts)
     if blocked:
         number, base_sha = blocked[0]
+        if (number, base_sha) in error_contexts:
+            return Resolution("error", f"Cloud review failed for PR #{number} 
at {base_sha[:12]}. Retry /review.",
+                              error_contexts[(number, base_sha)])
         if (number, base_sha) in incomplete_contexts:
             return Resolution(
                 "failure", f"Review did not converge for PR #{number} at 
{base_sha[:12]}.",
diff --git a/.github/scripts/test_debug_review.py 
b/.github/scripts/test_debug_review.py
index ec65d3a99e3..869771be614 100644
--- a/.github/scripts/test_debug_review.py
+++ b/.github/scripts/test_debug_review.py
@@ -32,27 +32,21 @@ class DebugReviewTest(unittest.TestCase):
     def setUp(self):
         tmp = self.enterContext(tempfile.TemporaryDirectory())
         self.enterContext(patch.dict(os.environ, 
GITHUB_REPOSITORY="apache/doris", GITHUB_RUN_ID="27",
-                                    GITHUB_OUTPUT=str(Path(tmp) / "outputs")))
+                                    GITHUB_RUN_ATTEMPT="1"))
         self.event = Path(tmp) / "event.json"
         self.enterContext(patch.dict(os.environ, 
GITHUB_EVENT_PATH=str(self.event)))
         self.event.write_text(json.dumps({"comment": {"body": "/review"}}))
         self.pr = dict(state="open", head={"sha": "a"*40}, base={"sha": 
"b"*40})
         self.snapshot = dict(pr_number=42, head_sha="a"*40, base_sha="b"*40)
         self.receipt = {"request_id": "github:review:27"}
-        self.row = dict(self.snapshot, **self.receipt, preview_only=False)
         self.url = 
"https://github.com/apache/doris/pull/42#pullrequestreview-89";
         self.result = dict(state="failure", converged=True, rounds=2, 
review_id=89,
                            review_url=self.url, p0=0, p1=1)
         self.api = self.enterContext(patch.object(debug, "gh", 
return_value=self.pr))
-        self.real_fc = debug.fc
-        self.fc = self.enterContext(patch.object(debug, "fc"))
+        self.real_fc = debug.submit_to_fc
+        self.fc = self.enterContext(patch.object(debug, "submit_to_fc"))
         self.enterContext(patch.object(debug.time, "sleep"))
 
-    def run_review(self, *rows):
-        self.fc.side_effect = [self.receipt, *rows]
-        debug.review(42, "a"*40, "b"*40)
-        self.assertEqual(("", self.snapshot, (202,)), 
self.fc.call_args_list[0].args)
-
     def posts(self):
         return [call.args for call in self.api.call_args_list if "-X" in 
call.args]
 
@@ -63,27 +57,47 @@ class DebugReviewTest(unittest.TestCase):
             self.assertEqual(expected, debug.requested_focus())
         self.assertEqual("", debug.focus_suffix(""))
         self.assertEqual("/" + hashlib.sha256(expected.encode()).hexdigest(), 
debug.focus_suffix(expected))
-        def dispatch(path, payload, codes):
-            if not path:
-                self.assertEqual(dict(self.snapshot, review_focus=expected), 
payload)
-                self.assertEqual(2, len(self.posts()))
-                return self.receipt
-            return dict(self.row, state="completed", result=dict(self.result, 
gate_receipt=True))
+        def dispatch(payload):
+            self.assertEqual(dict(self.snapshot, review_focus=expected), 
payload)
+            self.assertEqual(2, len(self.posts()))
+            return self.receipt
         self.fc.side_effect = dispatch
         debug.review(42, "a"*40, "b"*40)
+        self.fc.assert_called_once()
         self.assertTrue(all("state=pending" in post for post in self.posts()))
 
-    def test_slash_review_requires_publication_and_a_durable_verdict(self):
-        self.event.write_text(json.dumps({"comment": {"body": "/review"}}))
-        for row in (dict(self.row, state="queued", preview_only=True),
-                    dict(self.row, state="previewed"), dict(self.row, 
state="completed", result=self.result)):
-            with self.subTest(row=row), self.assertRaises(RuntimeError):
-                self.fc.side_effect = [self.receipt, row]
+    @patch.dict(os.environ, GITHUB_RUN_ATTEMPT="3")
+    def test_rerun_cannot_bind_an_admitted_run_to_a_different_snapshot(self):
+        expected = f"fc-review/v1/42/{'a'*40}/{'b'*40}"
+        current = {"name": expected, "conclusion": "success"}
+        for changed in (expected.replace("a"*40, "c"*40), 
expected.replace("b"*40, "d"*40),
+                        expected + "/" + "e"*64):
+            with self.subTest(changed=changed):
+                self.api.reset_mock()
+                self.api.side_effect = [self.pr, [{"jobs": [current]}, 
{"jobs": [dict(current, name=changed)]}]]
+                with self.assertRaisesRegex(ValueError, "Post a new /review"):
+                    debug.review(42, "a"*40, "b"*40)
+                self.fc.assert_not_called()
+                self.assertEqual([], self.posts())
+
+    @patch.dict(os.environ, GITHUB_RUN_ATTEMPT="2")
+    def test_rerun_reuses_matching_or_previously_unadmitted_snapshot(self):
+        expected = f"fc-review/v1/42/{'a'*40}/{'b'*40}"
+        for job in ({"name": expected, "conclusion": "success"},
+                    {"name": expected.replace("a"*40, "c"*40), "conclusion": 
"skipped"}):
+            with self.subTest(job=job):
+                self.fc.reset_mock()
+                self.api.side_effect = [self.pr, [{"jobs": [job]}], {}, {}]
+                self.fc.return_value = self.receipt
                 debug.review(42, "a"*40, "b"*40)
+                self.fc.assert_called_once_with(self.snapshot)
+
+    def test_oversized_focus_reports_an_error_before_submission(self):
         self.event.write_text(json.dumps({"comment": {"body": "/review " + 
"重"*2800}}))
         with self.assertRaisesRegex(ValueError, "8192"):
             debug.review(42, "a"*40, "b"*40)
-        self.assertTrue(all("state=pending" in post for post in self.posts()))
+        self.fc.assert_not_called()
+        self.assertIn("state=error", self.posts()[-1])
 
     def test_retired_command_and_other_slash_commands_do_not_dispatch(self):
         for command in ("run debugreview", "/reviewer", "example /review"):
@@ -95,11 +109,13 @@ class DebugReviewTest(unittest.TestCase):
                 self.fc.assert_not_called()
 
     def test_actions_only_marks_aggregate_and_source_pending(self):
-        self.run_review(dict(self.receipt, state="awaiting_status"), 
dict(self.row, state="running"),
-                        dict(self.row, state="completed", 
result=dict(self.result, gate_receipt=True)))
+        self.fc.return_value = self.receipt
+        debug.review(42, "a"*40, "b"*40)
+        self.fc.assert_called_once_with(self.snapshot)
         aggregate, source = self.posts()
         self.assertIn("context=code-review", aggregate)
         self.assertIn("context=code-review/source/automated/pr-42/base-" + 
"b"*40, source)
+        self.assertIn("description=Waiting for the cloud review receipt.", 
source)
         self.assertTrue(all("state=pending" in post for post in (aggregate, 
source)))
 
     def test_publisher_records_verified_result_once_after_lost_ack(self):
@@ -132,19 +148,16 @@ class DebugReviewTest(unittest.TestCase):
                 debug.publish_receipt("apache/doris", "27", 42, "a"*40, 
"b"*40, result, "cloud[bot]")
         self.assertEqual([], self.posts())
 
-    def test_each_fc_request_uses_a_fresh_review_audience_token(self):
-        values = [(200, {"value": "first"}), (202, self.receipt),
-                  (200, {"value": "next"}), (200, self.row)]
+    def test_fc_retry_gets_a_fresh_token_and_reuses_the_payload(self):
+        responses = [(200, {"value": "first"}), TimeoutError(), (200, 
{"value": "next"}), (202, self.receipt)]
         identity_url = "https://issuer.example/token?job=17";
         with patch.dict(os.environ, ACTIONS_ID_TOKEN_REQUEST_URL=identity_url,
                         ACTIONS_ID_TOKEN_REQUEST_TOKEN="runner"), patch.object(
-                            debug, "json_request", side_effect=values) as 
request:
-            self.assertEqual(self.receipt, self.real_fc("", self.snapshot, 
(202,)))
-            self.assertEqual(self.row, self.real_fc("/status", self.receipt, 
(200, 202)))
+                            debug, "json_request", side_effect=responses) as 
request:
+            self.assertEqual(self.receipt, self.real_fc(self.snapshot))
         identity = (identity_url + 
"&audience=urn%3Aapache%3Adoris%3Aci%3Areview", "runner")
         self.assertEqual([identity, (debug.FC, "first", self.snapshot), 
identity,
-                          (debug.FC + "/status", "next", self.receipt)],
-                         [c.args for c in request.call_args_list])
+                          (debug.FC, "next", self.snapshot)], [c.args for c in 
request.call_args_list])
 
     def test_converged_pass_and_incomplete_review(self):
         for change, expected in ((dict(state="success", p1=0), "success"),
@@ -153,17 +166,20 @@ class DebugReviewTest(unittest.TestCase):
                 verdict = debug.verdict(dict(self.result, **change), 
self.url.split("#")[0], "run", 42)
                 self.assertEqual((expected, "run"), (verdict[0], verdict[2]))
 
-    def test_superseded_and_replayed_snapshots(self):
-        self.run_review(dict(self.row, state="superseded"))
-        for fields in ({"head_sha": "c"*40}, {"base_sha": "c"*40}, 
{"request_id": "github:review:1"}):
-            with self.subTest(fields=fields), self.assertRaises(ValueError):
-                self.run_review(dict(self.row, **fields, state="completed", 
result=self.result))
-        self.assertTrue(all("state=pending" in post for post in self.posts()))
+    def test_failed_submission_and_wrong_ack_report_operational_errors(self):
+        for response, error in ((TimeoutError(), TimeoutError), 
({"request_id": "github:review:1"}, ValueError)):
+            with self.subTest(response=response):
+                self.api.reset_mock()
+                self.fc.side_effect = [response]
+                with self.assertRaises(error):
+                    debug.review(42, "a"*40, "b"*40)
+                aggregate, source, failed = self.posts()
+                self.assertIn("state=pending", aggregate)
+                self.assertIn("state=pending", source)
+                self.assertIn("state=error", failed)
+                
self.assertIn("context=code-review/source/automated/pr-42/base-" + "b"*40, 
failed)
 
-    def test_failure_or_pr_change_never_writes_a_verdict(self):
-        with self.assertRaises(RuntimeError):
-            self.run_review(dict(self.row, state="failed"))
-        self.assertTrue(all("state=pending" in post for post in self.posts()))
+    def test_stale_snapshot_does_not_submit(self):
         self.api.reset_mock()
         self.fc.reset_mock()
         self.api.return_value = dict(self.pr, base={"sha": "c"*40})
@@ -196,3 +212,7 @@ class ReviewWorkflowTest(unittest.TestCase):
         self.assertIn("group: code-review-pr-${{ github.event.issue.number 
}}", jobs)
         self.assertIn("cancel-in-progress: false", jobs)
         self.assertIn("queue: max", jobs)
+        aggregate = jobs.split("  aggregate-review:", 1)[1]
+        self.assertIn("needs: [review-inputs, cloud-review]", aggregate)
+        self.assertIn("if: always() && needs.review-inputs.outputs.head != '' 
&& needs.cloud-review.result != 'skipped'", aggregate)
+        self.assertIn("head_sha: ${{ needs.review-inputs.outputs.head }}", 
aggregate)
diff --git a/.github/scripts/test_resolve_code_review_status.py 
b/.github/scripts/test_resolve_code_review_status.py
index cb5e829c97b..ff1d11f424a 100644
--- a/.github/scripts/test_resolve_code_review_status.py
+++ b/.github/scripts/test_resolve_code_review_status.py
@@ -209,5 +209,93 @@ class ResolveCodeReviewStatusTest(unittest.TestCase):
             resolve_status([pull(123, base="short")], [], head_sha=HEAD_SHA)
 
 
+    @patch.dict("os.environ", DORIS_REVIEW_APP_BOT="cloud[bot]")
+    def test_outstanding_review_and_terminal_worker_failure(self):
+        repo = "https://github.com/apache/doris";
+        run1, run2 = (repo + "/actions/runs/" + n for n in ("10", "11"))
+        def pending(n, url):
+            return dict(status(n, source="automated", state="pending"),
+                        creator={"login": "github-actions[bot]"}, 
target_url=url,
+                        description="Waiting for the cloud review receipt.")
+        def receipt(n, run, state, description, url):
+            return dict(id=n, 
context=f"code-review/cloud/{run}/pr-123/base-{BASE_SHA}", state=state,
+                        description=description, target_url=url, 
creator={"login": "cloud[bot]"})
+        def resolve(*rows):
+            return resolve_status([pull(123)], list(rows), head_sha=HEAD_SHA, 
repo_url=repo)
+        req1, req2 = pending(1, run1), pending(2, run2)
+        ok = receipt(3, 10, "success", "Review completed for PR #123: P0=0, 
P1=0.",
+                     repo + "/pull/123#pullrequestreview-81")
+        failure = receipt(4, 11, "error", "Cloud review failed before a 
verdict for PR #123.", run2)
+        self.assertEqual("pending", resolve(req1, req2, ok).state)
+        self.assertEqual("error", resolve(req1, req2, ok, failure).state)
+        self.assertEqual(run2, resolve(req2, failure).target_url)
+        for bad in (dict(failure, creator={"login": "other"}), dict(failure, 
target_url=run1)):
+            self.assertEqual("pending", resolve(req2, bad).state)
+        newer = dict(ok, id=5, context=failure["context"])
+        for receipts in ((newer, failure), (failure, newer)):
+            self.assertEqual("success", resolve(req1, req2, *receipts).state)
+
+        # Replaying an older run must not reset the later distinct request,
+        # whether its predecessor passed, failed, or still lacks a verdict.
+        first_pass = dict(ok, id=2)
+        second_pending = dict(req2, id=3)
+        replay = dict(req1, id=4)
+        first_blocker = dict(first_pass, state="failure", description="Review 
completed for PR #123: P0=0, P1=1.")
+        for first in ([first_pass], [first_blocker], []):
+            rows = [req1, *first, second_pending, replay, newer]
+            for history in (rows, list(reversed(rows))):
+                self.assertEqual("success", resolve(*history).state)
+            self.assertEqual("pending", resolve(req1, *first, second_pending, 
replay).state)
+            self.assertEqual("success", resolve(*rows, dict(replay, 
id=6)).state)
+        self.assertEqual("failure", resolve(req1, second_pending, newer, 
dict(first_blocker, id=7)).state)
+        self.assertEqual("error", resolve(req1, second_pending, failure, 
replay).state)
+        self.assertEqual("pending", resolve(req1, req2, failure, pending(6, 
repo + "/actions/runs/12")).state)
+
+
+    @patch.dict("os.environ", DORIS_REVIEW_APP_BOT="cloud[bot]")
+    def 
test_pre_registration_history_and_new_async_request_on_same_snapshot(self):
+        repo = "https://github.com/apache/doris";
+        run_url = repo + "/actions/runs/"
+        cloud_context = f"code-review/cloud/{{}}/pr-123/base-{BASE_SHA}"
+        legacy = dict(status(1, source="automated", state="pending"), 
target_url=run_url + "10",
+                      creator={"login": "github-actions[bot]"}, 
description="Automated review is running for PR #123.")
+        blocker = dict(id=2, state="failure", 
context=cloud_context.format(10), creator={"login": "cloud[bot]"},
+                       target_url=repo + "/pull/123#pullrequestreview-81",
+                       description="Review completed for PR #123: P0=0, P1=1.")
+        clean = dict(blocker, id=3, context=cloud_context.format(11), 
state="success",
+                     description="Review completed for PR #123: P0=0, P1=0.",
+                     target_url=repo + "/pull/123#pullrequestreview-82")
+        error = dict(blocker, state="error", target_url=legacy["target_url"],
+                     description="Cloud review failed before a verdict for PR 
#123.")
+
+        def state(*rows):
+            return resolve_status([pull(123)], list(rows), head_sha=HEAD_SHA, 
repo_url=repo).state
+
+        # The old dispatcher submitted before polling. Run 11 can have a
+        # verified verdict even when it never wrote a pending status.
+        for previous in ([legacy], [legacy, blocker], [legacy, error]):
+            self.assertEqual("success", state(*previous, clean))
+            self.assertEqual("success", state(clean, *reversed(previous)))
+        self.assertEqual("error", state(legacy, error))
+
+        # Once a new request is explicitly registered, an old PASS cannot
+        # satisfy it, while a late verified blocker still takes effect.
+        current = dict(legacy, id=4, target_url=run_url + "12",
+                       description="Waiting for the cloud review receipt.")
+        self.assertEqual("pending", state(legacy, current, dict(clean, id=5)))
+        self.assertEqual("failure", state(legacy, current, dict(blocker, 
id=5)))
+
+        legacy_pass = dict(legacy, id=7, state="success")
+        replayed_poll = dict(legacy, id=6)
+        self.assertEqual("success", state(legacy, legacy_pass))
+        self.assertEqual("pending", state(legacy, current, replayed_poll, 
legacy_pass))
+        self.assertEqual("pending", state(legacy_pass, replayed_poll, current, 
legacy))
+        verified = dict(clean, id=8, context=cloud_context.format(12))
+        self.assertEqual("success", state(legacy, current, legacy_pass, 
verified))
+        self.assertEqual("failure", state(legacy, current, dict(blocker, 
id=5), legacy_pass))
+        for source in ("local", "skip"):
+            self.assertEqual("success", state(current, legacy_pass, status(8, 
source=source)))
+
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/.github/workflows/approve-label-trigger.yml 
b/.github/workflows/approve-label-trigger.yml
index 1a9cb8415ff..4b174d4d19d 100644
--- a/.github/workflows/approve-label-trigger.yml
+++ b/.github/workflows/approve-label-trigger.yml
@@ -22,7 +22,7 @@ jobs:
 
   label-when-reviewed:
     name: "Label PRs when reviewed"
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-slim
     steps:
       - name: "Do nothing. Only trigger corresponding workflow_run event"
         run: echo
diff --git a/.github/workflows/approve-label.yml 
b/.github/workflows/approve-label.yml
index ef93e86fd45..a1a894c270e 100644
--- a/.github/workflows/approve-label.yml
+++ b/.github/workflows/approve-label.yml
@@ -32,7 +32,7 @@ jobs:
 
   label-when-approved:
     name: "Label when approved"
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-slim
     steps:
       - name: "Resolve the pull request of the triggering review run"
         id: pr
diff --git a/.github/workflows/code-review-runner.yml 
b/.github/workflows/code-review-runner.yml
index 86950f549b5..7d837ec504d 100644
--- a/.github/workflows/code-review-runner.yml
+++ b/.github/workflows/code-review-runner.yml
@@ -57,22 +57,20 @@ jobs:
       group: code-review-pr-${{ github.event.issue.number }}
       cancel-in-progress: false
       queue: max
-    timeout-minutes: 238
+    timeout-minutes: 10
     permissions:
+      actions: read
       contents: read
       pull-requests: read
       statuses: write
       id-token: write
-    outputs:
-      aggregate_head: ${{ steps.review.outputs.aggregate_head }}
     steps:
       - uses: actions/checkout@v4
         with:
           ref: ${{ github.workflow_sha || github.sha }}
           persist-credentials: false
           sparse-checkout: .github/scripts
-      - name: Run cloud review and update its source status
-        id: review
+      - name: Submit the review to FC
         env:
           GH_TOKEN: ${{ github.token }}
           PR_NUMBER: ${{ github.event.issue.number }}
@@ -81,11 +79,11 @@ jobs:
         run: python3 .github/scripts/debug_review.py
 
   aggregate-review:
-    needs: cloud-review
-    if: always() && needs.cloud-review.outputs.aggregate_head != ''
+    needs: [review-inputs, cloud-review]
+    if: always() && needs.review-inputs.outputs.head != '' && 
needs.cloud-review.result != 'skipped'
     uses: ./.github/workflows/code-review-aggregate-status.yml
     with:
-      head_sha: ${{ needs.cloud-review.outputs.aggregate_head }}
+      head_sha: ${{ needs.review-inputs.outputs.head }}
     permissions:
       contents: read
       pull-requests: read
diff --git a/.github/workflows/comment-to-trigger-teamcity.yml 
b/.github/workflows/comment-to-trigger-teamcity.yml
index 18786fd401f..53e041cdcfd 100644
--- a/.github/workflows/comment-to-trigger-teamcity.yml
+++ b/.github/workflows/comment-to-trigger-teamcity.yml
@@ -57,7 +57,7 @@ jobs:
       head: ${{ steps.parse.outputs.COMMIT_ID_FROM_TRIGGER }}
       base: ${{ steps.parse.outputs.TARGET_BRANCH }}
       repeat: ${{ steps.parse.outputs.COMMENT_REPEAT_TIMES }}
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-slim
     env:
       COMMENT_BODY: ${{ github.event.comment.body }}
       COMMENT_USER_ID: ${{ github.event.comment.user.id }}
@@ -162,6 +162,7 @@ jobs:
       with:
         ref: ${{ github.sha }}
         persist-credentials: false
+        sparse-checkout: regression-test/pipeline/common
 
     - name: "Check if pr need run build"
       if: ${{ fromJSON(steps.parse.outputs.comment_trigger) }}
@@ -435,14 +436,15 @@ jobs:
       matrix:
         lane: ${{ 
fromJSON(needs.check-comment-if-need-to-trigger-teamcity.outputs.lanes) }}
     name: fc-approve/v1/${{ 
needs.check-comment-if-need-to-trigger-teamcity.outputs.pr }}/${{ 
needs.check-comment-if-need-to-trigger-teamcity.outputs.head }}/${{ 
needs.check-comment-if-need-to-trigger-teamcity.outputs.base }}/${{ matrix.lane 
}}/${{ needs.check-comment-if-need-to-trigger-teamcity.outputs.repeat }}
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-slim
     permissions: {}
     steps:
       - run: 'true'
 
   submit-fc:
     needs: [check-comment-if-need-to-trigger-teamcity, approve-fc]
-    runs-on: ubuntu-latest
+    # FC can take five minutes per lane. Keep long sequential batches on a 
full VM.
+    runs-on: ${{ 
fromJSON(needs.check-comment-if-need-to-trigger-teamcity.outputs.lanes || 
'[]')[2] && 'ubuntu-latest' || 'ubuntu-slim' }}
     permissions:
       contents: read
       id-token: write
diff --git a/.github/workflows/title-checker.yml 
b/.github/workflows/title-checker.yml
index b430250d2bf..b8323ce75e8 100644
--- a/.github/workflows/title-checker.yml
+++ b/.github/workflows/title-checker.yml
@@ -29,7 +29,7 @@ permissions:
 jobs:
   PR-title-checker:
     name: "PR title checker"
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-slim
     steps:
       - name: Check Title
         env:
diff --git a/regression-test/pipeline/common/tests/test_teamcity_utils.py 
b/regression-test/pipeline/common/tests/test_teamcity_utils.py
index b28c6d88af7..8d4e65e25b7 100644
--- a/regression-test/pipeline/common/tests/test_teamcity_utils.py
+++ b/regression-test/pipeline/common/tests/test_teamcity_utils.py
@@ -164,7 +164,7 @@ curl(){ python3 "$FIXTURE_ROOT/status_mock.py" "$@"; }
 
     def test_keywords_match_required_checks(self):
         repo = HELPER.parents[3]
-        required = set(re.findall(r'- (TeamCity/\S+)', (repo / 
'.asf.yaml').read_text()))
+        required = set(re.findall(r'^\s*- (?:context: )?(TeamCity/\S+)\s*$', 
(repo / '.asf.yaml').read_text(), re.M))
         result = self.run_shell('for lane in "${!conment_to_context[@]}"; do 
echo "$lane ${conment_to_context[$lane]}"; done')
         mappings = dict(line.split() for line in result.stdout.splitlines())
         self.assertEqual(set(mappings.values()), required | 
{'TeamCity/external', 'TeamCity/performance'})


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to