spark-test commented on code in PR #60365:
URL: https://github.com/apache/spark/pull/60365#discussion_r4546497781


##########
dev/visualize_ci_schedule.py:
##########
@@ -0,0 +1,1200 @@
+#!/usr/bin/env python3
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+Render the schedule of the scheduled CI workflows as an SVG timeline.
+
+The schedules are read from the cron entries in .github/workflows: workflows 
scheduled
+directly run on master, and the branch CI schedulers (branch*_scheduler.yml) 
dispatch
+workflows on maintenance branches through dev/dispatch-if-changed.sh. Each run 
is drawn
+from its cron start time for its estimated duration, with its estimated number 
of runners,
+both from ESTIMATES below. There is one panel per cadence (daily, every N 
days, weekly),
+followed by a heatmap of the combined runner load.
+
+Every scheduled workflow must be listed in either ESTIMATES or 
EXCLUDED_WORKFLOWS, so adding
+a scheduled workflow requires deciding whether it belongs in the image.
+
+Usage:
+    dev/visualize_ci_schedule.py           Regenerate the image.
+    dev/visualize_ci_schedule.py --check   Exit with an error if the image is 
out of date.
+    dev/visualize_ci_schedule.py --sample  Print estimates measured from 
recent runs.
+
+The image only depends on the workflow files and this script, and the script 
only uses the
+Python standard library. --sample additionally needs an authenticated GitHub 
CLI (gh).
+"""
+
+import argparse
+import concurrent.futures
+import datetime
+import glob
+import json
+import math
+import os
+import re
+import statistics
+import subprocess
+import sys
+import textwrap
+from collections import namedtuple
+from xml.sax.saxutils import escape
+
+SPARK_HOME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+WORKFLOW_DIR = os.path.join(SPARK_HOME, ".github", "workflows")
+DEFAULT_OUTPUT = os.path.join(WORKFLOW_DIR, "images", "scheduled-ci.svg")
+SCRIPT_NAME = "dev/visualize_ci_schedule.py"
+
+
+# 
---------------------------------------------------------------------------------------
+# Configuration
+# 
---------------------------------------------------------------------------------------
+
+# Estimated cost of one run of each scheduled workflow, keyed by the workflow 
file that does
+# the work (for branch builds, the dispatched workflow):
+#   hours:   wall-clock time from the start of the first job to the end of the 
last one.
+#   runners: average number of runners in use during that time, i.e. the 
job-hours of a run
+#            divided by `hours`. ASF limits GitHub Actions usage in full-time 
runners.
+# The values are medians of recent apache/spark runs printed by `--sample` 
(last sampled on
+# 2026-11-11), with the range of the sampled runs in the comments. They are 
rough; refresh
+# them when a workflow becomes notably faster, slower, or wider.
+Estimate = namedtuple("Estimate", ["hours", "runners"])
+
+ESTIMATES = {
+    "build_codegen_jdk.yml": Estimate(3.5, 8),  # 10 runs: 2.4-9.7h, 3-11 
runners
+    "build_coverage.yml": Estimate(2, 5),  # 10 runs: 1.8-11.3h, 1-5 runners
+    "build_java17.yml": Estimate(2.5, 7),  # 10 runs: 1.8-4.2h, 4-8 runners
+    "build_java21.yml": Estimate(2.5, 8),  # 10 runs: 2.1-3.8h, 6-9 runners
+    "build_java25.yml": Estimate(2.5, 8),  # 10 runs: 2.1-4.3h, 5-9 runners
+    "build_maven.yml": Estimate(2.5, 4),  # 10 runs: 2.1-3.0h, 3-5 runners
+    "build_maven_java21.yml": Estimate(3, 4),  # 10 runs: 2.3-3.9h, 3-5 runners
+    "build_maven_java21_arm.yml": Estimate(2.5, 4),  # 10 runs: 2.4-3.0h, 4-5 
runners
+    "build_maven_java21_macos26.yml": Estimate(4.5, 4),  # 10 runs: 4.1-5.9h, 
4-4 runners
+    "build_maven_java25.yml": Estimate(2.5, 4),  # 10 runs: 2.2-4.0h, 3-5 
runners
+    "build_non_ansi.yml": Estimate(2.5, 9),  # 10 runs: 1.6-2.9h, 7-10 runners
+    "build_python_3.11.yml": Estimate(2, 4),  # 10 runs: 1.3-4.0h, 2-5 runners
+    "build_python_3.12_arm.yml": Estimate(1.5, 6),  # 10 runs: 1.3-1.5h, 5-6 
runners
+    "build_python_3.12_classic_only.yml": Estimate(1.5, 3),  # 10 runs: 
1.3-3.8h, 1-4 runners
+    "build_python_3.12_macos26.yml": Estimate(2, 5),  # 10 runs: 1.7-2.1h, 5-5 
runners
+    "build_python_3.12_pandas_3.yml": Estimate(0.5, 2),  # 10 runs: 0.3-2.8h, 
1-5 runners
+    "build_python_3.13.yml": Estimate(1.5, 5),  # 10 runs: 1.3-3.1h, 2-5 
runners
+    "build_python_3.14.yml": Estimate(1.5, 5),  # 10 runs: 1.3-2.3h, 3-6 
runners
+    "build_python_3.14_nogil.yml": Estimate(1.5, 3),  # 10 runs: 1.3-5.8h, 1-4 
runners
+    "build_python_3.15.yml": Estimate(1, 2),  # 10 runs: 0.5-1.6h, 1-2 runners
+    "build_python_3.9.yml": Estimate(4.5, 4),  # 10 runs: 3.5-8.4h, 2-4 runners
+    "build_python_connect.yml": Estimate(1, 1),  # 10 runs: 1.0-1.2h, 1-1 
runners
+    "build_python_connect40.yml": Estimate(1, 1),  # 10 runs: 0.7-1.1h, 1-1 
runners
+    "build_python_minimum.yml": Estimate(2, 4),  # 10 runs: 1.4-8.9h, 1-6 
runners
+    "build_python_pypy3.10.yml": Estimate(1, 2),  # 10 runs: 0.7-2.8h, 1-2 
runners
+    "build_rockdb_as_ui_backend.yml": Estimate(2, 7),  # 10 runs: 1.9-3.4h, 
5-8 runners
+    "build_scala213.yml": Estimate(2, 6),  # 10 runs: 1.7-6.5h, 2-7 runners
+    "build_sparkr_window.yml": Estimate(1.5, 1),  # 10 runs: 1.0-1.4h, 1-1 
runners
+    "build_uds.yml": Estimate(2, 8),  # 10 runs: 2.0-2.6h, 7-9 runners
+    "publish_snapshot.yml": Estimate(1.5, 5),  # 10 runs: 1.0-1.5h, 4-6 runners
+    "release.yml": Estimate(2, 1),  # 10 runs: 1.4-2.5h, 1-1 runners
+}
+
+# Scheduled workflows that are not drawn, because they usually finish within 
an hour and do
+# not run tests, with what they do.
+EXCLUDED_WORKFLOWS = {
+    "build_infra_images_cache.yml": "refreshes the CI image cache",
+    "labeler.yml": "labels PRs",
+    "pages.yml": "deploys the documentation site",
+    "stale.yml": "closes stale PRs",
+    "update_build_status.yml": "syncs PR build status",
+}
+
+# Branch that workflows scheduled directly (not through a branch scheduler) 
run on.
+DEFAULT_BRANCH = "master"
+
+# ASF limits on the GitHub Actions usage of apache/spark, as averages in 
full-time runners over
+# all of its workflows: over a calendar week, and over any five consecutive 
days. See
+# https://infra.apache.org/github-actions-policy.html.
+ASF_WEEKLY_RUNNERS = 25
+ASF_FIVE_DAY_RUNNERS = 30
+
+
+# 
---------------------------------------------------------------------------------------
+# Workflow parsing
+# 
---------------------------------------------------------------------------------------
+
+# A scheduled run of `workflow` on `branch`, triggered by `cron` in the 
`source` workflow.
+Schedule = namedtuple("Schedule", ["workflow", "branch", "cron", "source"])
+
+# A schedule placed on a timeline repeating every `period` days. `starts` are 
the start
+# minutes within the period, `duration` is in minutes, `runners` is the 
average number of
+# runners in use, and `days` are the days of the month for day-of-month 
cadences (None
+# otherwise).
+Timeline = namedtuple("Timeline", ["schedule", "period", "starts", "duration", 
"runners", "days"])
+
+CRON_LINE_RE = 
re.compile(r"""^\s*-\s*cron:\s*(?:&([\w-]+)\s+)?(["'])([^"']+)\2\s*(?:#.*)?$""")
+ENV_ALIAS_RE = re.compile(r"^\s*(\w+):\s*\*([\w-]+)\s*$", re.MULTILINE)
+STEP_RE = re.compile(r"^\s*- name:", re.MULTILINE)
+DISPATCH_RE = re.compile(r"dispatch-if-changed\.sh\s+(\S+)\s+(\S+)")
+SCHEDULE_CONDITION_RE = 
re.compile(r"github\.event\.schedule\s*==\s*env\.(\w+)")
+
+WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
+
+
+class ScheduleError(Exception):
+    pass
+
+
+def read_crons(path, text):
+    """Returns the (anchor, cron) pairs of the cron entries in a workflow 
file."""
+    crons = []
+    for lineno, line in enumerate(text.splitlines(), 1):
+        if not re.match(r"^\s*-?\s*cron:", line):
+            continue
+        m = CRON_LINE_RE.match(line)
+        if not m:
+            raise ScheduleError("%s:%d: cannot parse the cron entry %r" % 
(path, lineno, line))
+        crons.append((m.group(1), m.group(3).strip()))
+    return crons
+
+
+def parse_scheduler(name, text, crons):
+    """Returns the schedules of a branch scheduler that dispatches workflows 
on branches."""
+    anchors = {}
+    for anchor, cron in crons:
+        if anchor is None:
+            raise ScheduleError("%s: cron '%s' needs a YAML anchor" % (name, 
cron))
+        anchors[anchor] = cron
+    env_to_anchor = dict(ENV_ALIAS_RE.findall(text))
+    used = set()
+    schedules = []
+    for step in STEP_RE.split(text)[1:]:
+        dispatch = DISPATCH_RE.search(step)
+        if not dispatch:
+            continue
+        conditions = SCHEDULE_CONDITION_RE.findall(step)
+        if len(conditions) != 1:
+            raise ScheduleError(
+                "%s: the step dispatching %s on %s must check exactly one 
cron, found %s"
+                % (name, dispatch.group(1), dispatch.group(2), conditions)
+            )
+        anchor = env_to_anchor.get(conditions[0])
+        if anchor not in anchors:
+            raise ScheduleError(
+                "%s: env.%s does not refer to a cron anchor" % (name, 
conditions[0])
+            )
+        used.add(anchor)
+        schedules.append(Schedule(dispatch.group(1), dispatch.group(2), 
anchors[anchor], name))
+    unused = sorted(set(anchors) - used)
+    if unused:
+        raise ScheduleError("%s: crons not used by any dispatch step: %s" % 
(name, unused))
+    return schedules
+
+
+def collect_schedules(workflow_dir):
+    schedules = []
+    paths = glob.glob(os.path.join(workflow_dir, "*.yml"))
+    paths += glob.glob(os.path.join(workflow_dir, "*.yaml"))
+    for path in sorted(paths):
+        name = os.path.basename(path)
+        with open(path, encoding="utf-8") as f:
+            text = f.read()
+        crons = read_crons(name, text)
+        if not crons:
+            continue
+        if DISPATCH_RE.search(text):
+            schedules.extend(parse_scheduler(name, text, crons))
+        else:
+            schedules.extend(Schedule(name, DEFAULT_BRANCH, cron, name) for _, 
cron in crons)
+    return schedules
+
+
+# 
---------------------------------------------------------------------------------------
+# Cron handling
+# 
---------------------------------------------------------------------------------------
+
+
+def parse_cron_field(field, lo, hi):
+    """Expands a cron field such as '*', '5', '1-28/3', '*/10' or '1,3' into 
its values."""
+    values = set()
+    for part in field.split(","):
+        m = re.match(r"^(\*|\d+(?:-\d+)?)(?:/(\d+))?$", part)
+        if not m:
+            raise ScheduleError("unsupported cron field '%s'" % field)
+        step = int(m.group(2) or 1)
+        if m.group(1) == "*":
+            start, end = lo, hi
+        elif "-" in m.group(1):
+            start, end = (int(v) for v in m.group(1).split("-"))
+        else:
+            start = int(m.group(1))
+            end = hi if m.group(2) else start
+        if not lo <= start <= end <= hi or step < 1:
+            raise ScheduleError("cron field '%s' is out of range [%d, %d]" % 
(field, lo, hi))
+        values.update(range(start, end + 1, step))
+    return sorted(values)
+
+
+def to_timeline(schedule, estimate):
+    """Places a schedule on a repeating timeline according to its cron 
expression.
+
+    Supported cadences are daily ('* *' day of month and week), weekly (a 
day-of-week
+    list) and every N days (an arithmetic day-of-month progression such as 
'1-28/3').
+    """
+    fields = schedule.cron.split()
+    if len(fields) != 5:
+        raise ScheduleError("%s: invalid cron '%s'" % (schedule.source, 
schedule.cron))
+    minute, hour, dom, month, dow = fields
+    try:
+        minutes = parse_cron_field(minute, 0, 59)
+        hours = parse_cron_field(hour, 0, 23)
+        if month != "*":
+            raise ScheduleError("month restrictions are not supported")
+        if dom == "*" and dow == "*":
+            period, day_offsets, days = 1, [0], None
+        elif dom == "*":
+            period, days = 7, None
+            day_offsets = sorted({d % 7 for d in parse_cron_field(dow, 0, 7)})
+        elif dow == "*":
+            days = parse_cron_field(dom, 1, 31)
+            period = days[1] - days[0] if len(days) > 1 else 0

Review Comment:
   **Nit (P3):** Here the step of a day-of-month progression becomes its 
period, and line 270 rejects only steps below 2 or uneven steps. So `'17 3 
1-28/7 * *'` (days 1, 8, 15, and 22) gets period 7, the same as `'17 3 * * 0'`. 
It is drawn in the Weekly panel as `Sun 03:17`, counted as weekly in the 
header, and pinned to Sundays in the heatmap and the busiest-window ASF 
figures, while `--check` passes. The real run falls on a different weekday from 
month to month.
   
   The same happens for every step that is a multiple of 7, because the 
combined cycle gives cycle day N the weekday N mod 7 (line 627). Steps 14 and 
21 get their own panel, but their load still lands on one weekday, and the 
heatmap note claims that every combination of phase and weekday is covered. 
With today's 3-day and weekly cadences, step 28 makes the cycle exactly 84 
days, which passes the length check, and `hour_axis()` then raises an uncaught 
`StopIteration`, because no hour-label step fits a 28-day panel.
   
   No current cron uses such a step, but the docstring advertises every-N-days 
progressions. Rejecting steps that are multiples of 7 next to the check on line 
270, with a message that points to a day-of-week cron such as `'17 3 * * 0'`, 
covers all four cases.
   
   **Verification:**
   - **Regression:** Generating from copies of the workflow files in which one 
weekly cron is rewritten as a day-of-month progression with step 7, 14, 21, or 
28 fails with the new error for each step, instead of drawing the run on one 
fixed weekday or raising StopIteration.
   - **Behavior:** Day-of-month progressions with steps 2, 3, 4, and 6 and a 
day-of-week list keep the cadences and start labels they had before the change, 
a step of 5 still stops with the existing cycle-length error, and the image 
generated from the current workflow files is the same as before.



##########
dev/visualize_ci_schedule.py:
##########
@@ -0,0 +1,1200 @@
+#!/usr/bin/env python3
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+Render the schedule of the scheduled CI workflows as an SVG timeline.
+
+The schedules are read from the cron entries in .github/workflows: workflows 
scheduled
+directly run on master, and the branch CI schedulers (branch*_scheduler.yml) 
dispatch
+workflows on maintenance branches through dev/dispatch-if-changed.sh. Each run 
is drawn
+from its cron start time for its estimated duration, with its estimated number 
of runners,
+both from ESTIMATES below. There is one panel per cadence (daily, every N 
days, weekly),
+followed by a heatmap of the combined runner load.
+
+Every scheduled workflow must be listed in either ESTIMATES or 
EXCLUDED_WORKFLOWS, so adding
+a scheduled workflow requires deciding whether it belongs in the image.
+
+Usage:
+    dev/visualize_ci_schedule.py           Regenerate the image.
+    dev/visualize_ci_schedule.py --check   Exit with an error if the image is 
out of date.
+    dev/visualize_ci_schedule.py --sample  Print estimates measured from 
recent runs.
+
+The image only depends on the workflow files and this script, and the script 
only uses the
+Python standard library. --sample additionally needs an authenticated GitHub 
CLI (gh).
+"""
+
+import argparse
+import concurrent.futures
+import datetime
+import glob
+import json
+import math
+import os
+import re
+import statistics
+import subprocess
+import sys
+import textwrap
+from collections import namedtuple
+from xml.sax.saxutils import escape
+
+SPARK_HOME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+WORKFLOW_DIR = os.path.join(SPARK_HOME, ".github", "workflows")
+DEFAULT_OUTPUT = os.path.join(WORKFLOW_DIR, "images", "scheduled-ci.svg")
+SCRIPT_NAME = "dev/visualize_ci_schedule.py"
+
+
+# 
---------------------------------------------------------------------------------------
+# Configuration
+# 
---------------------------------------------------------------------------------------
+
+# Estimated cost of one run of each scheduled workflow, keyed by the workflow 
file that does
+# the work (for branch builds, the dispatched workflow):
+#   hours:   wall-clock time from the start of the first job to the end of the 
last one.
+#   runners: average number of runners in use during that time, i.e. the 
job-hours of a run
+#            divided by `hours`. ASF limits GitHub Actions usage in full-time 
runners.
+# The values are medians of recent apache/spark runs printed by `--sample` 
(last sampled on
+# 2026-11-11), with the range of the sampled runs in the comments. They are 
rough; refresh
+# them when a workflow becomes notably faster, slower, or wider.
+Estimate = namedtuple("Estimate", ["hours", "runners"])
+
+ESTIMATES = {
+    "build_codegen_jdk.yml": Estimate(3.5, 8),  # 10 runs: 2.4-9.7h, 3-11 
runners
+    "build_coverage.yml": Estimate(2, 5),  # 10 runs: 1.8-11.3h, 1-5 runners
+    "build_java17.yml": Estimate(2.5, 7),  # 10 runs: 1.8-4.2h, 4-8 runners
+    "build_java21.yml": Estimate(2.5, 8),  # 10 runs: 2.1-3.8h, 6-9 runners
+    "build_java25.yml": Estimate(2.5, 8),  # 10 runs: 2.1-4.3h, 5-9 runners
+    "build_maven.yml": Estimate(2.5, 4),  # 10 runs: 2.1-3.0h, 3-5 runners
+    "build_maven_java21.yml": Estimate(3, 4),  # 10 runs: 2.3-3.9h, 3-5 runners
+    "build_maven_java21_arm.yml": Estimate(2.5, 4),  # 10 runs: 2.4-3.0h, 4-5 
runners
+    "build_maven_java21_macos26.yml": Estimate(4.5, 4),  # 10 runs: 4.1-5.9h, 
4-4 runners
+    "build_maven_java25.yml": Estimate(2.5, 4),  # 10 runs: 2.2-4.0h, 3-5 
runners
+    "build_non_ansi.yml": Estimate(2.5, 9),  # 10 runs: 1.6-2.9h, 7-10 runners
+    "build_python_3.11.yml": Estimate(2, 4),  # 10 runs: 1.3-4.0h, 2-5 runners
+    "build_python_3.12_arm.yml": Estimate(1.5, 6),  # 10 runs: 1.3-1.5h, 5-6 
runners
+    "build_python_3.12_classic_only.yml": Estimate(1.5, 3),  # 10 runs: 
1.3-3.8h, 1-4 runners
+    "build_python_3.12_macos26.yml": Estimate(2, 5),  # 10 runs: 1.7-2.1h, 5-5 
runners
+    "build_python_3.12_pandas_3.yml": Estimate(0.5, 2),  # 10 runs: 0.3-2.8h, 
1-5 runners
+    "build_python_3.13.yml": Estimate(1.5, 5),  # 10 runs: 1.3-3.1h, 2-5 
runners
+    "build_python_3.14.yml": Estimate(1.5, 5),  # 10 runs: 1.3-2.3h, 3-6 
runners
+    "build_python_3.14_nogil.yml": Estimate(1.5, 3),  # 10 runs: 1.3-5.8h, 1-4 
runners
+    "build_python_3.15.yml": Estimate(1, 2),  # 10 runs: 0.5-1.6h, 1-2 runners
+    "build_python_3.9.yml": Estimate(4.5, 4),  # 10 runs: 3.5-8.4h, 2-4 runners
+    "build_python_connect.yml": Estimate(1, 1),  # 10 runs: 1.0-1.2h, 1-1 
runners
+    "build_python_connect40.yml": Estimate(1, 1),  # 10 runs: 0.7-1.1h, 1-1 
runners
+    "build_python_minimum.yml": Estimate(2, 4),  # 10 runs: 1.4-8.9h, 1-6 
runners
+    "build_python_pypy3.10.yml": Estimate(1, 2),  # 10 runs: 0.7-2.8h, 1-2 
runners
+    "build_rockdb_as_ui_backend.yml": Estimate(2, 7),  # 10 runs: 1.9-3.4h, 
5-8 runners
+    "build_scala213.yml": Estimate(2, 6),  # 10 runs: 1.7-6.5h, 2-7 runners
+    "build_sparkr_window.yml": Estimate(1.5, 1),  # 10 runs: 1.0-1.4h, 1-1 
runners
+    "build_uds.yml": Estimate(2, 8),  # 10 runs: 2.0-2.6h, 7-9 runners
+    "publish_snapshot.yml": Estimate(1.5, 5),  # 10 runs: 1.0-1.5h, 4-6 runners
+    "release.yml": Estimate(2, 1),  # 10 runs: 1.4-2.5h, 1-1 runners
+}
+
+# Scheduled workflows that are not drawn, because they usually finish within 
an hour and do
+# not run tests, with what they do.
+EXCLUDED_WORKFLOWS = {
+    "build_infra_images_cache.yml": "refreshes the CI image cache",
+    "labeler.yml": "labels PRs",
+    "pages.yml": "deploys the documentation site",
+    "stale.yml": "closes stale PRs",
+    "update_build_status.yml": "syncs PR build status",
+}
+
+# Branch that workflows scheduled directly (not through a branch scheduler) 
run on.
+DEFAULT_BRANCH = "master"
+
+# ASF limits on the GitHub Actions usage of apache/spark, as averages in 
full-time runners over
+# all of its workflows: over a calendar week, and over any five consecutive 
days. See
+# https://infra.apache.org/github-actions-policy.html.
+ASF_WEEKLY_RUNNERS = 25
+ASF_FIVE_DAY_RUNNERS = 30
+
+
+# 
---------------------------------------------------------------------------------------
+# Workflow parsing
+# 
---------------------------------------------------------------------------------------
+
+# A scheduled run of `workflow` on `branch`, triggered by `cron` in the 
`source` workflow.
+Schedule = namedtuple("Schedule", ["workflow", "branch", "cron", "source"])
+
+# A schedule placed on a timeline repeating every `period` days. `starts` are 
the start
+# minutes within the period, `duration` is in minutes, `runners` is the 
average number of
+# runners in use, and `days` are the days of the month for day-of-month 
cadences (None
+# otherwise).
+Timeline = namedtuple("Timeline", ["schedule", "period", "starts", "duration", 
"runners", "days"])
+
+CRON_LINE_RE = 
re.compile(r"""^\s*-\s*cron:\s*(?:&([\w-]+)\s+)?(["'])([^"']+)\2\s*(?:#.*)?$""")
+ENV_ALIAS_RE = re.compile(r"^\s*(\w+):\s*\*([\w-]+)\s*$", re.MULTILINE)
+STEP_RE = re.compile(r"^\s*- name:", re.MULTILINE)
+DISPATCH_RE = re.compile(r"dispatch-if-changed\.sh\s+(\S+)\s+(\S+)")
+SCHEDULE_CONDITION_RE = 
re.compile(r"github\.event\.schedule\s*==\s*env\.(\w+)")
+
+WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
+
+
+class ScheduleError(Exception):
+    pass
+
+
+def read_crons(path, text):
+    """Returns the (anchor, cron) pairs of the cron entries in a workflow 
file."""
+    crons = []
+    for lineno, line in enumerate(text.splitlines(), 1):
+        if not re.match(r"^\s*-?\s*cron:", line):
+            continue
+        m = CRON_LINE_RE.match(line)
+        if not m:
+            raise ScheduleError("%s:%d: cannot parse the cron entry %r" % 
(path, lineno, line))
+        crons.append((m.group(1), m.group(3).strip()))
+    return crons
+
+
+def parse_scheduler(name, text, crons):
+    """Returns the schedules of a branch scheduler that dispatches workflows 
on branches."""
+    anchors = {}
+    for anchor, cron in crons:
+        if anchor is None:
+            raise ScheduleError("%s: cron '%s' needs a YAML anchor" % (name, 
cron))
+        anchors[anchor] = cron
+    env_to_anchor = dict(ENV_ALIAS_RE.findall(text))
+    used = set()
+    schedules = []
+    for step in STEP_RE.split(text)[1:]:
+        dispatch = DISPATCH_RE.search(step)
+        if not dispatch:
+            continue
+        conditions = SCHEDULE_CONDITION_RE.findall(step)
+        if len(conditions) != 1:
+            raise ScheduleError(
+                "%s: the step dispatching %s on %s must check exactly one 
cron, found %s"
+                % (name, dispatch.group(1), dispatch.group(2), conditions)
+            )
+        anchor = env_to_anchor.get(conditions[0])
+        if anchor not in anchors:
+            raise ScheduleError(
+                "%s: env.%s does not refer to a cron anchor" % (name, 
conditions[0])
+            )
+        used.add(anchor)
+        schedules.append(Schedule(dispatch.group(1), dispatch.group(2), 
anchors[anchor], name))
+    unused = sorted(set(anchors) - used)
+    if unused:
+        raise ScheduleError("%s: crons not used by any dispatch step: %s" % 
(name, unused))
+    return schedules
+
+
+def collect_schedules(workflow_dir):
+    schedules = []
+    paths = glob.glob(os.path.join(workflow_dir, "*.yml"))
+    paths += glob.glob(os.path.join(workflow_dir, "*.yaml"))
+    for path in sorted(paths):
+        name = os.path.basename(path)
+        with open(path, encoding="utf-8") as f:
+            text = f.read()
+        crons = read_crons(name, text)
+        if not crons:
+            continue
+        if DISPATCH_RE.search(text):
+            schedules.extend(parse_scheduler(name, text, crons))
+        else:
+            schedules.extend(Schedule(name, DEFAULT_BRANCH, cron, name) for _, 
cron in crons)
+    return schedules
+
+
+# 
---------------------------------------------------------------------------------------
+# Cron handling
+# 
---------------------------------------------------------------------------------------
+
+
+def parse_cron_field(field, lo, hi):
+    """Expands a cron field such as '*', '5', '1-28/3', '*/10' or '1,3' into 
its values."""
+    values = set()
+    for part in field.split(","):
+        m = re.match(r"^(\*|\d+(?:-\d+)?)(?:/(\d+))?$", part)
+        if not m:
+            raise ScheduleError("unsupported cron field '%s'" % field)
+        step = int(m.group(2) or 1)
+        if m.group(1) == "*":
+            start, end = lo, hi
+        elif "-" in m.group(1):
+            start, end = (int(v) for v in m.group(1).split("-"))
+        else:
+            start = int(m.group(1))
+            end = hi if m.group(2) else start
+        if not lo <= start <= end <= hi or step < 1:
+            raise ScheduleError("cron field '%s' is out of range [%d, %d]" % 
(field, lo, hi))
+        values.update(range(start, end + 1, step))
+    return sorted(values)
+
+
+def to_timeline(schedule, estimate):
+    """Places a schedule on a repeating timeline according to its cron 
expression.
+
+    Supported cadences are daily ('* *' day of month and week), weekly (a 
day-of-week
+    list) and every N days (an arithmetic day-of-month progression such as 
'1-28/3').
+    """
+    fields = schedule.cron.split()
+    if len(fields) != 5:
+        raise ScheduleError("%s: invalid cron '%s'" % (schedule.source, 
schedule.cron))
+    minute, hour, dom, month, dow = fields
+    try:
+        minutes = parse_cron_field(minute, 0, 59)
+        hours = parse_cron_field(hour, 0, 23)
+        if month != "*":
+            raise ScheduleError("month restrictions are not supported")
+        if dom == "*" and dow == "*":
+            period, day_offsets, days = 1, [0], None
+        elif dom == "*":
+            period, days = 7, None
+            day_offsets = sorted({d % 7 for d in parse_cron_field(dow, 0, 7)})
+        elif dow == "*":
+            days = parse_cron_field(dom, 1, 31)
+            period = days[1] - days[0] if len(days) > 1 else 0
+            if period < 2 or any(b - a != period for a, b in zip(days, 
days[1:])):
+                raise ScheduleError("the day of month must be a range with a 
step, e.g. 1-28/3")
+            day_offsets = [(days[0] - 1) % period]
+        else:
+            raise ScheduleError("restricting both day of month and day of week 
is unsupported")
+    except ScheduleError as e:
+        raise ScheduleError("%s: cron '%s': %s" % (schedule.source, 
schedule.cron, e))
+    starts = sorted(d * 1440 + h * 60 + m for d in day_offsets for h in hours 
for m in minutes)
+    duration = int(round(estimate.hours * 60))
+    return Timeline(schedule, period, starts, duration, estimate.runners, days)
+
+
+def build_timelines(schedules):
+    scheduled = {s.workflow for s in schedules}
+    errors = []
+    for workflow in sorted(scheduled):
+        if workflow not in ESTIMATES and workflow not in EXCLUDED_WORKFLOWS:
+            errors.append(
+                "%s is scheduled but has no estimate. Add it to ESTIMATES (see 
--sample), or "
+                "to EXCLUDED_WORKFLOWS if it usually finishes within an hour 
and does not run "
+                "tests, in %s." % (workflow, SCRIPT_NAME)
+            )
+        if workflow in ESTIMATES and workflow in EXCLUDED_WORKFLOWS:
+            errors.append("%s is in both ESTIMATES and EXCLUDED_WORKFLOWS." % 
workflow)
+    for table, entries in (
+        ("ESTIMATES", ESTIMATES),
+        ("EXCLUDED_WORKFLOWS", EXCLUDED_WORKFLOWS),
+    ):
+        for workflow in sorted(set(entries) - scheduled):
+            errors.append(
+                "%s is no longer scheduled. Remove it from %s in %s."
+                % (workflow, table, SCRIPT_NAME)
+            )
+    if errors:
+        raise ScheduleError("\n".join(errors))
+    timelines = [
+        to_timeline(s, ESTIMATES[s.workflow])
+        for s in schedules
+        if s.workflow not in EXCLUDED_WORKFLOWS
+    ]
+    excluded = [s for s in schedules if s.workflow in EXCLUDED_WORKFLOWS]
+    return timelines, excluded
+
+
+def phase_name(offset):
+    return chr(ord("A") + offset)
+
+
+def describe_start(period, start):
+    """Formats a start minute within a period, e.g. 'Sat 15:17' or 'B 
06:17'."""
+    day, minute = divmod(start, 1440)
+    clock = "%02d:%02d" % divmod(minute, 60)
+    if period == 7:
+        return "%s %s" % (WEEKDAYS[day], clock)
+    if period > 1:
+        return "%s %s" % (phase_name(day), clock)
+    return clock
+
+
+def describe_cadence(timeline):
+    period = timeline.period
+    if period == 1:
+        return "daily"
+    if period == 7:
+        return "weekly"
+    return "every %d days" % period
+
+
+def concurrency(intervals, length):
+    """Returns the total weight of the running intervals at each minute of a 
cyclic timeline.
+
+    `intervals` are (start, duration, weight) triples, in minutes; they wrap 
around at
+    `length`.
+    """
+    diff = [0] * (length + 1)
+    for start, duration, weight in intervals:
+        remaining = duration
+        start %= length
+        while remaining > 0:
+            end = min(length, start + remaining)
+            diff[start] += weight
+            diff[end] -= weight
+            remaining -= end - start
+            start = 0
+    counts, running = [], 0
+    for value in diff[:length]:
+        running += value
+        counts.append(running)
+    return counts
+
+
+def lcm(a, b):
+    return a * b // math.gcd(a, b)
+
+
+# 
---------------------------------------------------------------------------------------
+# Sampling recent runs
+# 
---------------------------------------------------------------------------------------
+
+SAMPLE_REPO = "apache/spark"
+# Only first attempts of scheduled or dispatched runs that ran to the end are 
sampled, since
+# re-running failed jobs keeps the timestamps of the jobs that passed. 
Successful runs are
+# preferred because failed runs may have stopped early.
+SAMPLE_EVENTS = ("schedule", "workflow_dispatch")
+SAMPLE_CONCLUSIONS = ("success", "failure")
+SAMPLE_PARALLELISM = 8
+JOB_TIMES_JQ = (
+    '.jobs[] | select(.conclusion != "skipped" and .started_at != null'
+    ' and .completed_at != null) | "\\(.started_at) \\(.completed_at)"'
+)
+
+
+def gh(args):
+    try:
+        result = subprocess.run(
+            ["gh"] + args,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            universal_newlines=True,
+        )
+    except OSError:
+        raise ScheduleError("--sample needs the GitHub CLI (gh).")
+    if result.returncode != 0:
+        raise ScheduleError("gh %s failed: %s" % (" ".join(args), 
result.stderr.strip()))
+    return result.stdout
+
+
+def parse_time(text):
+    return datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ")
+
+
+def sample_run(run_id):
+    """Returns the (wall-clock hours, job-hours) of a workflow run, or None if 
it has no jobs."""
+    path = "repos/%s/actions/runs/%d/jobs?per_page=100" % (SAMPLE_REPO, run_id)
+    jobs = []
+    for line in gh(["api", "--paginate", path, "--jq", 
JOB_TIMES_JQ]).splitlines():
+        if line.strip():
+            started, completed = (parse_time(t) for t in line.split())
+            jobs.append((started, max(started, completed)))
+    if not jobs:
+        return None
+    wall = (max(c for _, c in jobs) - min(s for s, _ in jobs)).total_seconds() 
/ 3600.0
+    busy = sum((c - s).total_seconds() for s, c in jobs) / 3600.0
+    return (wall, busy) if wall > 0 else None
+
+
+def sample_workflow(workflow, runs):
+    """Returns the (wall-clock hours, job-hours) of the latest `runs` runs of 
a workflow."""
+    fields = "databaseId,event,status,conclusion,attempt"
+    listing = json.loads(
+        gh(
+            ["run", "list", "--repo", SAMPLE_REPO, "--workflow", workflow, 
"--limit", "100"]
+            + ["--json", fields]
+        )
+    )
+    candidates = [
+        run
+        for run in listing
+        if run["event"] in SAMPLE_EVENTS
+        and run["status"] == "completed"
+        and run["conclusion"] in SAMPLE_CONCLUSIONS
+        and run["attempt"] == 1
+    ]
+    # Latest successful runs first, then the latest failed runs if there are 
not enough.
+    candidates.sort(key=lambda run: run["conclusion"] != "success")
+    samples = []
+    for run in candidates:
+        if len(samples) == runs:
+            break
+        sample = sample_run(run["databaseId"])
+        if sample:
+            samples.append(sample)
+    return samples
+
+
+def sample_estimates(runs):
+    """Prints an ESTIMATES table measured from the latest runs of every 
scheduled workflow."""
+    workflows = sorted({s.workflow for s in collect_schedules(WORKFLOW_DIR)})
+    print("Sampling %d workflows in %s ..." % (len(workflows), SAMPLE_REPO), 
file=sys.stderr)
+    with concurrent.futures.ThreadPoolExecutor(SAMPLE_PARALLELISM) as pool:
+        all_samples = list(pool.map(lambda w: sample_workflow(w, runs), 
workflows))
+    lines = []
+    for workflow, samples in zip(workflows, all_samples):
+        if not samples:
+            lines.append("    # %s: no completed runs found" % workflow)
+            continue
+        walls = [w for w, _ in samples]
+        widths = [b / w for w, b in samples]
+        hours = max(0.5, round(statistics.median(walls) * 2) / 2.0)
+        runners = max(1, int(round(statistics.median(widths))))
+        lines.append(
+            '    "%s": Estimate(%g, %d),  # %d runs: %.1f-%.1fh, %.0f-%.0f 
runners'
+            % (
+                workflow,
+                hours,
+                runners,
+                len(samples),
+                min(walls),
+                max(walls),
+                min(widths),
+                max(widths),
+            )
+        )
+    print("\n".join(lines))
+
+
+# 
---------------------------------------------------------------------------------------
+# SVG rendering
+# 
---------------------------------------------------------------------------------------
+
+WIDTH = 1240
+MARGIN = 20
+LEFT = 372  # x where the plots start; the row labels live to the left of it.
+PLOT_WIDTH = WIDTH - LEFT - 36
+ROW_HEIGHT = 18
+# Bar thickness grows with the number of runners, up to the widest workflow.
+MIN_BAR_HEIGHT = 4
+MAX_BAR_HEIGHT = 14
+
+FONT_SANS = 'system-ui, -apple-system, "Segoe UI", Helvetica, Arial, 
sans-serif'
+FONT_MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", 
monospace'
+
+SURFACE = "#fcfcfb"
+ZEBRA = "#f4f3ef"
+INK = "#0b0b0b"
+INK_SECONDARY = "#52514e"
+INK_MUTED = "#898781"
+GRID = "#e1e0d9"
+AXIS = "#c3c2b7"
+# Categorical colors assigned to branches in a fixed order: master, then 
newest first.
+BRANCH_COLORS = [
+    "#2a78d6",
+    "#eb6834",
+    "#1baf7a",
+    "#eda100",
+    "#e87ba4",
+    "#008300",
+    "#6250d6",
+    "#e34948",
+]
+OTHER_BRANCH_COLOR = "#898781"
+# Sequential ramp for the load heatmap, from no load to the peak.
+HEAT_RAMP = ["#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5", "#256abf", "#184f95", 
"#0d366b"]
+HEAT_ZERO = "#f4f3ef"
+
+
+def branch_sort_key(branch):
+    if branch == DEFAULT_BRANCH:
+        return (0, ())
+    version = re.findall(r"\d+|x", branch)
+    return (1, tuple(-(10**6) if v == "x" else -int(v) for v in version), 
branch)
+
+
+def fmt(value):
+    """Formats a coordinate deterministically with at most one decimal."""
+    text = "%.1f" % value
+    return text[:-2] if text.endswith(".0") else text
+
+
+def fmt_hours(minutes):
+    return "%gh" % (minutes / 60.0)
+
+
+class Svg:
+    def __init__(self):
+        self.parts = []
+
+    def add(self, element):
+        self.parts.append(element)
+
+    def text(
+        self, x, y, content, size=12, fill=INK, anchor="start", weight=None, 
mono=False, title=None
+    ):
+        attrs = 'x="%s" y="%s" font-size="%s" fill="%s"' % (fmt(x), fmt(y), 
size, fill)
+        if anchor != "start":
+            attrs += ' text-anchor="%s"' % anchor
+        if weight:
+            attrs += ' font-weight="%s"' % weight
+        if mono:
+            attrs += " font-family='%s'" % FONT_MONO
+        body = escape(content)
+        if title:
+            body = "<title>%s</title>%s" % (escape(title), body)
+        self.add("<text %s>%s</text>" % (attrs, body))
+
+    def rect(self, x, y, w, h, fill, rx=0, title=None, extra=""):

Review Comment:
   **Nit (P3):** None of the seven `rect()` calls (lines 697, 780, 809, 962, 
963, 1004, and 1046) passes `extra`, and nothing forwards keyword arguments to 
it. So the `if extra:` branch on lines 565-566 never runs, and the parameter 
suggests an extension point that nothing uses. Removing the parameter and those 
two lines leaves the generated SVG unchanged.
   
   **Verification:**
   - **Inspection:** Svg.rect() has no extra parameter or 'if extra:' branch, 
and no call site passes or forwards an extra argument.



##########
dev/visualize_ci_schedule.py:
##########
@@ -0,0 +1,1200 @@
+#!/usr/bin/env python3
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+Render the schedule of the scheduled CI workflows as an SVG timeline.
+
+The schedules are read from the cron entries in .github/workflows: workflows 
scheduled
+directly run on master, and the branch CI schedulers (branch*_scheduler.yml) 
dispatch
+workflows on maintenance branches through dev/dispatch-if-changed.sh. Each run 
is drawn
+from its cron start time for its estimated duration, with its estimated number 
of runners,
+both from ESTIMATES below. There is one panel per cadence (daily, every N 
days, weekly),
+followed by a heatmap of the combined runner load.
+
+Every scheduled workflow must be listed in either ESTIMATES or 
EXCLUDED_WORKFLOWS, so adding
+a scheduled workflow requires deciding whether it belongs in the image.
+
+Usage:
+    dev/visualize_ci_schedule.py           Regenerate the image.
+    dev/visualize_ci_schedule.py --check   Exit with an error if the image is 
out of date.
+    dev/visualize_ci_schedule.py --sample  Print estimates measured from 
recent runs.
+
+The image only depends on the workflow files and this script, and the script 
only uses the
+Python standard library. --sample additionally needs an authenticated GitHub 
CLI (gh).
+"""
+
+import argparse
+import concurrent.futures
+import datetime
+import glob
+import json
+import math
+import os
+import re
+import statistics
+import subprocess
+import sys
+import textwrap
+from collections import namedtuple
+from xml.sax.saxutils import escape
+
+SPARK_HOME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+WORKFLOW_DIR = os.path.join(SPARK_HOME, ".github", "workflows")
+DEFAULT_OUTPUT = os.path.join(WORKFLOW_DIR, "images", "scheduled-ci.svg")
+SCRIPT_NAME = "dev/visualize_ci_schedule.py"
+
+
+# 
---------------------------------------------------------------------------------------
+# Configuration
+# 
---------------------------------------------------------------------------------------
+
+# Estimated cost of one run of each scheduled workflow, keyed by the workflow 
file that does
+# the work (for branch builds, the dispatched workflow):
+#   hours:   wall-clock time from the start of the first job to the end of the 
last one.
+#   runners: average number of runners in use during that time, i.e. the 
job-hours of a run
+#            divided by `hours`. ASF limits GitHub Actions usage in full-time 
runners.
+# The values are medians of recent apache/spark runs printed by `--sample` 
(last sampled on
+# 2026-11-11), with the range of the sampled runs in the comments. They are 
rough; refresh
+# them when a workflow becomes notably faster, slower, or wider.
+Estimate = namedtuple("Estimate", ["hours", "runners"])
+
+ESTIMATES = {
+    "build_codegen_jdk.yml": Estimate(3.5, 8),  # 10 runs: 2.4-9.7h, 3-11 
runners
+    "build_coverage.yml": Estimate(2, 5),  # 10 runs: 1.8-11.3h, 1-5 runners
+    "build_java17.yml": Estimate(2.5, 7),  # 10 runs: 1.8-4.2h, 4-8 runners
+    "build_java21.yml": Estimate(2.5, 8),  # 10 runs: 2.1-3.8h, 6-9 runners
+    "build_java25.yml": Estimate(2.5, 8),  # 10 runs: 2.1-4.3h, 5-9 runners
+    "build_maven.yml": Estimate(2.5, 4),  # 10 runs: 2.1-3.0h, 3-5 runners
+    "build_maven_java21.yml": Estimate(3, 4),  # 10 runs: 2.3-3.9h, 3-5 runners
+    "build_maven_java21_arm.yml": Estimate(2.5, 4),  # 10 runs: 2.4-3.0h, 4-5 
runners
+    "build_maven_java21_macos26.yml": Estimate(4.5, 4),  # 10 runs: 4.1-5.9h, 
4-4 runners
+    "build_maven_java25.yml": Estimate(2.5, 4),  # 10 runs: 2.2-4.0h, 3-5 
runners
+    "build_non_ansi.yml": Estimate(2.5, 9),  # 10 runs: 1.6-2.9h, 7-10 runners
+    "build_python_3.11.yml": Estimate(2, 4),  # 10 runs: 1.3-4.0h, 2-5 runners
+    "build_python_3.12_arm.yml": Estimate(1.5, 6),  # 10 runs: 1.3-1.5h, 5-6 
runners
+    "build_python_3.12_classic_only.yml": Estimate(1.5, 3),  # 10 runs: 
1.3-3.8h, 1-4 runners
+    "build_python_3.12_macos26.yml": Estimate(2, 5),  # 10 runs: 1.7-2.1h, 5-5 
runners
+    "build_python_3.12_pandas_3.yml": Estimate(0.5, 2),  # 10 runs: 0.3-2.8h, 
1-5 runners
+    "build_python_3.13.yml": Estimate(1.5, 5),  # 10 runs: 1.3-3.1h, 2-5 
runners
+    "build_python_3.14.yml": Estimate(1.5, 5),  # 10 runs: 1.3-2.3h, 3-6 
runners
+    "build_python_3.14_nogil.yml": Estimate(1.5, 3),  # 10 runs: 1.3-5.8h, 1-4 
runners
+    "build_python_3.15.yml": Estimate(1, 2),  # 10 runs: 0.5-1.6h, 1-2 runners
+    "build_python_3.9.yml": Estimate(4.5, 4),  # 10 runs: 3.5-8.4h, 2-4 runners
+    "build_python_connect.yml": Estimate(1, 1),  # 10 runs: 1.0-1.2h, 1-1 
runners
+    "build_python_connect40.yml": Estimate(1, 1),  # 10 runs: 0.7-1.1h, 1-1 
runners
+    "build_python_minimum.yml": Estimate(2, 4),  # 10 runs: 1.4-8.9h, 1-6 
runners
+    "build_python_pypy3.10.yml": Estimate(1, 2),  # 10 runs: 0.7-2.8h, 1-2 
runners
+    "build_rockdb_as_ui_backend.yml": Estimate(2, 7),  # 10 runs: 1.9-3.4h, 
5-8 runners
+    "build_scala213.yml": Estimate(2, 6),  # 10 runs: 1.7-6.5h, 2-7 runners
+    "build_sparkr_window.yml": Estimate(1.5, 1),  # 10 runs: 1.0-1.4h, 1-1 
runners
+    "build_uds.yml": Estimate(2, 8),  # 10 runs: 2.0-2.6h, 7-9 runners
+    "publish_snapshot.yml": Estimate(1.5, 5),  # 10 runs: 1.0-1.5h, 4-6 runners
+    "release.yml": Estimate(2, 1),  # 10 runs: 1.4-2.5h, 1-1 runners
+}
+
+# Scheduled workflows that are not drawn, because they usually finish within 
an hour and do
+# not run tests, with what they do.
+EXCLUDED_WORKFLOWS = {
+    "build_infra_images_cache.yml": "refreshes the CI image cache",
+    "labeler.yml": "labels PRs",
+    "pages.yml": "deploys the documentation site",
+    "stale.yml": "closes stale PRs",
+    "update_build_status.yml": "syncs PR build status",
+}
+
+# Branch that workflows scheduled directly (not through a branch scheduler) 
run on.
+DEFAULT_BRANCH = "master"
+
+# ASF limits on the GitHub Actions usage of apache/spark, as averages in 
full-time runners over
+# all of its workflows: over a calendar week, and over any five consecutive 
days. See
+# https://infra.apache.org/github-actions-policy.html.
+ASF_WEEKLY_RUNNERS = 25
+ASF_FIVE_DAY_RUNNERS = 30
+
+
+# 
---------------------------------------------------------------------------------------
+# Workflow parsing
+# 
---------------------------------------------------------------------------------------
+
+# A scheduled run of `workflow` on `branch`, triggered by `cron` in the 
`source` workflow.
+Schedule = namedtuple("Schedule", ["workflow", "branch", "cron", "source"])
+
+# A schedule placed on a timeline repeating every `period` days. `starts` are 
the start
+# minutes within the period, `duration` is in minutes, `runners` is the 
average number of
+# runners in use, and `days` are the days of the month for day-of-month 
cadences (None
+# otherwise).
+Timeline = namedtuple("Timeline", ["schedule", "period", "starts", "duration", 
"runners", "days"])
+
+CRON_LINE_RE = 
re.compile(r"""^\s*-\s*cron:\s*(?:&([\w-]+)\s+)?(["'])([^"']+)\2\s*(?:#.*)?$""")
+ENV_ALIAS_RE = re.compile(r"^\s*(\w+):\s*\*([\w-]+)\s*$", re.MULTILINE)
+STEP_RE = re.compile(r"^\s*- name:", re.MULTILINE)
+DISPATCH_RE = re.compile(r"dispatch-if-changed\.sh\s+(\S+)\s+(\S+)")
+SCHEDULE_CONDITION_RE = 
re.compile(r"github\.event\.schedule\s*==\s*env\.(\w+)")
+
+WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
+
+
+class ScheduleError(Exception):
+    pass
+
+
+def read_crons(path, text):
+    """Returns the (anchor, cron) pairs of the cron entries in a workflow 
file."""
+    crons = []
+    for lineno, line in enumerate(text.splitlines(), 1):
+        if not re.match(r"^\s*-?\s*cron:", line):
+            continue
+        m = CRON_LINE_RE.match(line)
+        if not m:
+            raise ScheduleError("%s:%d: cannot parse the cron entry %r" % 
(path, lineno, line))
+        crons.append((m.group(1), m.group(3).strip()))
+    return crons
+
+
+def parse_scheduler(name, text, crons):
+    """Returns the schedules of a branch scheduler that dispatches workflows 
on branches."""
+    anchors = {}
+    for anchor, cron in crons:
+        if anchor is None:
+            raise ScheduleError("%s: cron '%s' needs a YAML anchor" % (name, 
cron))
+        anchors[anchor] = cron
+    env_to_anchor = dict(ENV_ALIAS_RE.findall(text))
+    used = set()
+    schedules = []
+    for step in STEP_RE.split(text)[1:]:
+        dispatch = DISPATCH_RE.search(step)

Review Comment:
   **Nit (P3):** `DISPATCH_RE.search(step)` keeps only the first 
`dev/dispatch-if-changed.sh` call in a step, and each step yields one 
`Schedule` (line 196). The other checks (an anchor on every cron, exactly one 
`github.event.schedule` comparison per dispatching step, every anchor used) all 
pass for a step that runs two dispatches under one schedule condition, for 
example `build_maven.yml` and `build_maven_java21.yml` under `MAVEN_CRON`. The 
second build then disappears from the image and from its runner-hour, peak, and 
ASF-share figures, while `--check` passes. If the dropped workflow is scheduled 
nowhere else, `build_timelines()` instead reports it as no longer scheduled and 
asks for its estimate to be removed, and following that advice makes the check 
pass with the run missing.
   
   Every scheduler step today dispatches one workflow, so this only affects 
future edits. Recording one schedule per `DISPATCH_RE.finditer(step)` match at 
the step's single cron, and naming all of a step's dispatches in its error 
messages, closes both cases.
   
   **Verification:**
   - **Regression:** Parsing a scheduler step whose single schedule condition 
guards dispatches of build_maven.yml and build_maven_java21.yml on one branch 
yields both builds at that cron, and an image rendered from workflow files 
containing that step draws both rows and counts both in the load figures.
   - **Regression:** When the branch-3.5 scheduler dispatches 
build_python_3.9.yml from the same step as build_scala213.yml, generation draws 
both builds at the shared cron instead of failing with the error that 
build_python_3.9.yml is no longer scheduled.
   - **Behavior:** With the current workflow files, whose scheduler steps each 
dispatch one workflow, the generated image is the same as before the change.



##########
dev/visualize_ci_schedule.py:
##########
@@ -0,0 +1,1200 @@
+#!/usr/bin/env python3
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+Render the schedule of the scheduled CI workflows as an SVG timeline.
+
+The schedules are read from the cron entries in .github/workflows: workflows 
scheduled
+directly run on master, and the branch CI schedulers (branch*_scheduler.yml) 
dispatch
+workflows on maintenance branches through dev/dispatch-if-changed.sh. Each run 
is drawn
+from its cron start time for its estimated duration, with its estimated number 
of runners,
+both from ESTIMATES below. There is one panel per cadence (daily, every N 
days, weekly),
+followed by a heatmap of the combined runner load.
+
+Every scheduled workflow must be listed in either ESTIMATES or 
EXCLUDED_WORKFLOWS, so adding
+a scheduled workflow requires deciding whether it belongs in the image.
+
+Usage:
+    dev/visualize_ci_schedule.py           Regenerate the image.
+    dev/visualize_ci_schedule.py --check   Exit with an error if the image is 
out of date.
+    dev/visualize_ci_schedule.py --sample  Print estimates measured from 
recent runs.
+
+The image only depends on the workflow files and this script, and the script 
only uses the
+Python standard library. --sample additionally needs an authenticated GitHub 
CLI (gh).
+"""
+
+import argparse
+import concurrent.futures
+import datetime
+import glob
+import json
+import math
+import os
+import re
+import statistics
+import subprocess
+import sys
+import textwrap
+from collections import namedtuple
+from xml.sax.saxutils import escape
+
+SPARK_HOME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+WORKFLOW_DIR = os.path.join(SPARK_HOME, ".github", "workflows")
+DEFAULT_OUTPUT = os.path.join(WORKFLOW_DIR, "images", "scheduled-ci.svg")
+SCRIPT_NAME = "dev/visualize_ci_schedule.py"
+
+
+# 
---------------------------------------------------------------------------------------
+# Configuration
+# 
---------------------------------------------------------------------------------------
+
+# Estimated cost of one run of each scheduled workflow, keyed by the workflow 
file that does
+# the work (for branch builds, the dispatched workflow):
+#   hours:   wall-clock time from the start of the first job to the end of the 
last one.
+#   runners: average number of runners in use during that time, i.e. the 
job-hours of a run
+#            divided by `hours`. ASF limits GitHub Actions usage in full-time 
runners.
+# The values are medians of recent apache/spark runs printed by `--sample` 
(last sampled on
+# 2026-11-11), with the range of the sampled runs in the comments. They are 
rough; refresh
+# them when a workflow becomes notably faster, slower, or wider.
+Estimate = namedtuple("Estimate", ["hours", "runners"])
+
+ESTIMATES = {
+    "build_codegen_jdk.yml": Estimate(3.5, 8),  # 10 runs: 2.4-9.7h, 3-11 
runners
+    "build_coverage.yml": Estimate(2, 5),  # 10 runs: 1.8-11.3h, 1-5 runners
+    "build_java17.yml": Estimate(2.5, 7),  # 10 runs: 1.8-4.2h, 4-8 runners
+    "build_java21.yml": Estimate(2.5, 8),  # 10 runs: 2.1-3.8h, 6-9 runners
+    "build_java25.yml": Estimate(2.5, 8),  # 10 runs: 2.1-4.3h, 5-9 runners
+    "build_maven.yml": Estimate(2.5, 4),  # 10 runs: 2.1-3.0h, 3-5 runners
+    "build_maven_java21.yml": Estimate(3, 4),  # 10 runs: 2.3-3.9h, 3-5 runners
+    "build_maven_java21_arm.yml": Estimate(2.5, 4),  # 10 runs: 2.4-3.0h, 4-5 
runners
+    "build_maven_java21_macos26.yml": Estimate(4.5, 4),  # 10 runs: 4.1-5.9h, 
4-4 runners
+    "build_maven_java25.yml": Estimate(2.5, 4),  # 10 runs: 2.2-4.0h, 3-5 
runners
+    "build_non_ansi.yml": Estimate(2.5, 9),  # 10 runs: 1.6-2.9h, 7-10 runners
+    "build_python_3.11.yml": Estimate(2, 4),  # 10 runs: 1.3-4.0h, 2-5 runners
+    "build_python_3.12_arm.yml": Estimate(1.5, 6),  # 10 runs: 1.3-1.5h, 5-6 
runners
+    "build_python_3.12_classic_only.yml": Estimate(1.5, 3),  # 10 runs: 
1.3-3.8h, 1-4 runners
+    "build_python_3.12_macos26.yml": Estimate(2, 5),  # 10 runs: 1.7-2.1h, 5-5 
runners
+    "build_python_3.12_pandas_3.yml": Estimate(0.5, 2),  # 10 runs: 0.3-2.8h, 
1-5 runners
+    "build_python_3.13.yml": Estimate(1.5, 5),  # 10 runs: 1.3-3.1h, 2-5 
runners
+    "build_python_3.14.yml": Estimate(1.5, 5),  # 10 runs: 1.3-2.3h, 3-6 
runners
+    "build_python_3.14_nogil.yml": Estimate(1.5, 3),  # 10 runs: 1.3-5.8h, 1-4 
runners
+    "build_python_3.15.yml": Estimate(1, 2),  # 10 runs: 0.5-1.6h, 1-2 runners
+    "build_python_3.9.yml": Estimate(4.5, 4),  # 10 runs: 3.5-8.4h, 2-4 runners
+    "build_python_connect.yml": Estimate(1, 1),  # 10 runs: 1.0-1.2h, 1-1 
runners
+    "build_python_connect40.yml": Estimate(1, 1),  # 10 runs: 0.7-1.1h, 1-1 
runners
+    "build_python_minimum.yml": Estimate(2, 4),  # 10 runs: 1.4-8.9h, 1-6 
runners
+    "build_python_pypy3.10.yml": Estimate(1, 2),  # 10 runs: 0.7-2.8h, 1-2 
runners
+    "build_rockdb_as_ui_backend.yml": Estimate(2, 7),  # 10 runs: 1.9-3.4h, 
5-8 runners
+    "build_scala213.yml": Estimate(2, 6),  # 10 runs: 1.7-6.5h, 2-7 runners
+    "build_sparkr_window.yml": Estimate(1.5, 1),  # 10 runs: 1.0-1.4h, 1-1 
runners
+    "build_uds.yml": Estimate(2, 8),  # 10 runs: 2.0-2.6h, 7-9 runners
+    "publish_snapshot.yml": Estimate(1.5, 5),  # 10 runs: 1.0-1.5h, 4-6 runners
+    "release.yml": Estimate(2, 1),  # 10 runs: 1.4-2.5h, 1-1 runners
+}
+
+# Scheduled workflows that are not drawn, because they usually finish within 
an hour and do
+# not run tests, with what they do.
+EXCLUDED_WORKFLOWS = {
+    "build_infra_images_cache.yml": "refreshes the CI image cache",
+    "labeler.yml": "labels PRs",
+    "pages.yml": "deploys the documentation site",
+    "stale.yml": "closes stale PRs",
+    "update_build_status.yml": "syncs PR build status",
+}
+
+# Branch that workflows scheduled directly (not through a branch scheduler) 
run on.
+DEFAULT_BRANCH = "master"
+
+# ASF limits on the GitHub Actions usage of apache/spark, as averages in 
full-time runners over
+# all of its workflows: over a calendar week, and over any five consecutive 
days. See
+# https://infra.apache.org/github-actions-policy.html.
+ASF_WEEKLY_RUNNERS = 25
+ASF_FIVE_DAY_RUNNERS = 30
+
+
+# 
---------------------------------------------------------------------------------------
+# Workflow parsing
+# 
---------------------------------------------------------------------------------------
+
+# A scheduled run of `workflow` on `branch`, triggered by `cron` in the 
`source` workflow.
+Schedule = namedtuple("Schedule", ["workflow", "branch", "cron", "source"])
+
+# A schedule placed on a timeline repeating every `period` days. `starts` are 
the start
+# minutes within the period, `duration` is in minutes, `runners` is the 
average number of
+# runners in use, and `days` are the days of the month for day-of-month 
cadences (None
+# otherwise).
+Timeline = namedtuple("Timeline", ["schedule", "period", "starts", "duration", 
"runners", "days"])
+
+CRON_LINE_RE = 
re.compile(r"""^\s*-\s*cron:\s*(?:&([\w-]+)\s+)?(["'])([^"']+)\2\s*(?:#.*)?$""")
+ENV_ALIAS_RE = re.compile(r"^\s*(\w+):\s*\*([\w-]+)\s*$", re.MULTILINE)
+STEP_RE = re.compile(r"^\s*- name:", re.MULTILINE)
+DISPATCH_RE = re.compile(r"dispatch-if-changed\.sh\s+(\S+)\s+(\S+)")
+SCHEDULE_CONDITION_RE = 
re.compile(r"github\.event\.schedule\s*==\s*env\.(\w+)")
+
+WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
+
+
+class ScheduleError(Exception):
+    pass
+
+
+def read_crons(path, text):
+    """Returns the (anchor, cron) pairs of the cron entries in a workflow 
file."""
+    crons = []
+    for lineno, line in enumerate(text.splitlines(), 1):
+        if not re.match(r"^\s*-?\s*cron:", line):
+            continue
+        m = CRON_LINE_RE.match(line)
+        if not m:
+            raise ScheduleError("%s:%d: cannot parse the cron entry %r" % 
(path, lineno, line))
+        crons.append((m.group(1), m.group(3).strip()))
+    return crons
+
+
+def parse_scheduler(name, text, crons):
+    """Returns the schedules of a branch scheduler that dispatches workflows 
on branches."""
+    anchors = {}
+    for anchor, cron in crons:
+        if anchor is None:
+            raise ScheduleError("%s: cron '%s' needs a YAML anchor" % (name, 
cron))
+        anchors[anchor] = cron
+    env_to_anchor = dict(ENV_ALIAS_RE.findall(text))
+    used = set()
+    schedules = []
+    for step in STEP_RE.split(text)[1:]:
+        dispatch = DISPATCH_RE.search(step)
+        if not dispatch:
+            continue
+        conditions = SCHEDULE_CONDITION_RE.findall(step)
+        if len(conditions) != 1:
+            raise ScheduleError(
+                "%s: the step dispatching %s on %s must check exactly one 
cron, found %s"
+                % (name, dispatch.group(1), dispatch.group(2), conditions)
+            )
+        anchor = env_to_anchor.get(conditions[0])
+        if anchor not in anchors:
+            raise ScheduleError(
+                "%s: env.%s does not refer to a cron anchor" % (name, 
conditions[0])
+            )
+        used.add(anchor)
+        schedules.append(Schedule(dispatch.group(1), dispatch.group(2), 
anchors[anchor], name))
+    unused = sorted(set(anchors) - used)
+    if unused:
+        raise ScheduleError("%s: crons not used by any dispatch step: %s" % 
(name, unused))
+    return schedules
+
+
+def collect_schedules(workflow_dir):
+    schedules = []
+    paths = glob.glob(os.path.join(workflow_dir, "*.yml"))
+    paths += glob.glob(os.path.join(workflow_dir, "*.yaml"))
+    for path in sorted(paths):
+        name = os.path.basename(path)
+        with open(path, encoding="utf-8") as f:
+            text = f.read()
+        crons = read_crons(name, text)
+        if not crons:
+            continue
+        if DISPATCH_RE.search(text):
+            schedules.extend(parse_scheduler(name, text, crons))
+        else:
+            schedules.extend(Schedule(name, DEFAULT_BRANCH, cron, name) for _, 
cron in crons)

Review Comment:
   **Nit (P3):** This attributes every cron outside a branch scheduler to 
`DEFAULT_BRANCH`, which is wrong for `publish_snapshot.yml`. On its schedule, 
`matrix.branch` defaults to master, branch-4.x, branch-4.3, branch-4.2, 
branch-4.1, branch-4.0, and branch-3.5, and each job checks out and publishes 
its branch (publish_snapshot.yml lines 42 and 47). The checked-in image 
nevertheless draws it as a master row in master's color with the tooltip 
`publish_snapshot.yml on master: ...`, and its notes say "Workflows scheduled 
directly run on master." Its load is right, because the 1.5h x 5 estimate was 
measured from whole matrix runs; only the label, color, tooltip, and note are 
wrong. These snapshot builds do not go through `dev/dispatch-if-changed.sh`, so 
the note that unchanged maintenance branches are skipped should not cover a 
corrected row. No other directly scheduled workflow builds a branch other than 
master.
   
   One way to fix it: map such workflows to a label like `matrix` in a small 
table next to `DEFAULT_BRANCH`, validated like `ESTIMATES`. Draw that row in a 
neutral color outside the per-branch palette, so the other branches keep their 
colors, with its own legend entry and a tooltip naming the matrix. Then reword 
the note, the module docstring, and the `DEFAULT_BRANCH` comment.
   
   **Verification:**
   - **Behavior:** Regenerating the image shows the publish_snapshot.yml row 
with the matrix label, a color no branch uses, a legend entry for that color, 
and a tooltip saying the run publishes every branch in the workflow's strategy 
matrix, and the notes name publish_snapshot.yml as the exception to directly 
scheduled workflows running on master.
   - **Regression:** Comparing the regenerated image with the current one shows 
every other row with its old branch label and color and identical header 
figures, panel load strips, and heatmap cells.
   - **Behavior:** Generation fails with an error naming the new table when an 
entry names a workflow that is not scheduled directly, such as one that only 
the branch schedulers dispatch.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to