damccorm commented on code in PR #41494:
URL: https://github.com/apache/beam/pull/41494#discussion_r4787855490


##########
.github/workflows/update_ml_dependency_bounds.yml:
##########
@@ -0,0 +1,144 @@
+# 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.
+
+# Raises exclusive upper bounds of ML dependencies in setup.py / tox.ini when
+# PyPI has a newer stable release, then opens a pull request. Never merges.
+# Does not regenerate container requirements (see 
update_python_dependencies.yml).
+#
+# If an open pull request titled "Update ML dependency bounds*" already exists,
+# this run is skipped so reviewer edits on that branch are not overwritten.
+# Close that PR to get a fresh run.
+#
+# Behavior, holds, and an example generated PR body:
+#   scripts/tools/README_ml_dependency_bounds.md
+#
+# Example PR body the script generates:
+#
+#   This PR was created by automation and has not been reviewed by a human yet.
+#   ...
+#   Bumped bounds:
+#   - setup_torch_torch_extra (sdks/python/setup.py): torch>=2.3.0,<2.15.0 -> 
torch>=2.3.0,<2.16.0
+#   Held:
+#   - setup_torch_ml_base_core: torch 2.12 requires triton 3.7, ...
+
+name: Update ML Dependency Bounds
+
+on:
+  schedule:
+  - cron: "0 0 * * 0"
+  workflow_dispatch:
+permissions:
+  actions: write
+  contents: write
+  pull-requests: write
+
+concurrency:
+  group: '${{ github.workflow }} @ ${{ github.ref }}'
+  cancel-in-progress: true
+
+jobs:
+  update_ml_dependency_bounds:
+    if: github.event_name == 'workflow_dispatch' || github.repository == 
'apache/beam'
+    runs-on: [self-hosted, ubuntu-24.04, main]
+    name: Update ML Dependency Bounds
+    timeout-minutes: 30
+    steps:
+      - name: Checkout code
+        uses: actions/checkout@v7
+        with:
+          persist-credentials: false
+      - name: Setup environment
+        uses: $/.github/actions/setup-environment-action
+        with:
+          python-version: "3.11"
+          # The script does not use tox.
+          tox-cache: false
+      - name: Install script dependencies
+        run: pip install packaging pyyaml pytest
+      - name: Install gh cli
+        uses: $/.github/actions/setup-gh-cli-linux
+      - name: Check for an open pull request from this workflow
+        id: existing_pr
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+        run: |
+          existingPr=$(gh pr list --state open --limit 5 \
+            --search 'is:pr is:open in:title "Update ML dependency bounds"' \
+            --json number,isCrossRepository \
+            --jq '[.[] | select(.isCrossRepository | not)] | .[0].number // 
empty')
+          echo "number=$existingPr" >> "$GITHUB_OUTPUT"
+          if [ -n "$existingPr" ]; then
+            message="Open pull request #$existingPr from this workflow exists. 
Skipping this run. Close that pull request to get a new run."
+            echo "$message"
+            echo "$message" >> "$GITHUB_STEP_SUMMARY"
+          fi
+      - name: Test the update script
+        if: steps.existing_pr.outputs.number == ''
+        run: python -m pytest scripts/tools/update_ml_dependency_bounds_test.py
+      - name: Update ML dependency bounds
+        if: steps.existing_pr.outputs.number == ''
+        run: |
+          set -o pipefail
+          python scripts/tools/update_ml_dependency_bounds.py \
+            --pr-body-file "$RUNNER_TEMP/pr_body.md" | tee 
"$RUNNER_TEMP/report.txt"
+          {
+            echo "## ML dependency bounds"
+            echo '```'
+            cat "$RUNNER_TEMP/report.txt"
+            echo '```'
+          } >> "$GITHUB_STEP_SUMMARY"
+      - name: Commit changes and create PR
+        id: create_pr
+        if: steps.existing_pr.outputs.number == ''
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+        run: |
+          if [ -z "$(git status --porcelain)" ]; then
+            echo "No changes on the files"
+            echo "created=false" >> "$GITHUB_OUTPUT"
+            exit 0
+          fi
+          git config user.name "$GITHUB_ACTOR"
+          git config user.email actions@"$RUNNER_NAME".local
+          gh auth setup-git
+          branchName=update_ml_dependency_bounds_$(date +%s)
+          git checkout -b "$branchName"
+          git add -A
+          git commit -m "Update ML dependency bounds" --quiet
+          git push origin "$branchName" --quiet
+          GITHUB_PR_URL=$(gh pr create --title "Update ML dependency bounds" 
--label "python" --body-file "$RUNNER_TEMP/pr_body.md" --base master)
+          echo "Link of the new PR  $GITHUB_PR_URL"
+          echo "created=true" >> "$GITHUB_OUTPUT"
+          echo "branch=$branchName" >> "$GITHUB_OUTPUT"
+      - name: Trigger Python PostCommit workflows on the new branch
+        if: steps.create_pr.outputs.created == 'true'
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+          PR_BRANCH: ${{ steps.create_pr.outputs.branch }}
+        run: |
+          # Pick up current and future PostCommit workflows whose name mentions
+          # Python, so this list does not need hand updates.
+          mapfile -t workflows < <(gh workflow list --all --json 
name,path,state \
+            --jq '.[] | select(.state=="active") | select(.name | 
test("(?i)python")) | select(.name | test("(?i)post\\s*commit")) | .path')
+          if [ ${#workflows[@]} -eq 0 ]; then
+            echo "No matching Python PostCommit workflows found"
+            exit 0
+          fi

Review Comment:
   `gh workflow list` defaults to `--limit 50`, while `apache/beam` has 350+ 
active workflows—testing this command against `apache/beam` right now returns 0 
matches, hits `if [ ${#workflows[@]} -eq 0 ]`, and silently exits 0 without 
triggering any PostCommit workflows. Also, `mapfile -t workflows < <(...)` 
swallows non-zero exit codes from `gh`.
   
   Consider paginating via `gh api` (so we never hit an arbitrary limit) and 
failing loudly if the query fails or matches nothing:
   
   ```bash
   workflows_out=$(gh api --paginate 
"repos/$GITHUB_REPOSITORY/actions/workflows" \
     --jq '.workflows[] | select(.state=="active") | select(.name | 
test("(?i)python")) | select(.name | test("(?i)post\\s*commit")) | select(.name 
| test("(?i)with\\s*rc") | not) | .path')
   mapfile -t workflows <<< "$workflows_out"
   ```
   
   (Also worth checking whether we want to exclude 
`beam_PostCommit_Python_ValidatesContainer_Dataflow_With_RC.yml` as shown 
above, since it tests `-PtestRCDependencies=true` / pre-release deps rather 
than stable ML bounds.)



##########
scripts/tools/ml_dependency_bounds.yaml:
##########
@@ -0,0 +1,370 @@
+#
+# 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.
+#
+
+# Sites read by update_ml_dependency_bounds.py. Current bounds are read from 
the
+# files at run time, so no pattern or value here depends on a bound that the
+# script changes.
+#
+# Site fields:
+#   id             Unique name used in reports.
+#   file           Path from the repository root.
+#   package        Distribution name as written in the requirement.
+#   pypi           Project name used for https://pypi.org/pypi/<pypi>/json.
+#   pattern        Regex (multiline) that matches the requirement. The named
+#                  group "req" is the text that the script may rewrite.
+#   occurrence     Which match of the pattern (inside section, if set) is this
+#                  site (1-based). Default 1.
+#   section        Optional regex selecting a file substring. pattern and
+#                  occurrence then apply only inside that substring.
+#   role           "high" sites are updated. "low" sites are never edited.
+#   max_exclusive  Optional ceiling. The upper bound is never raised past it.
+#   allow_major    If true, a minor-capped bound may move into a newer major.
+#                  Default false.
+#   hold_reason    Reported when the site cannot move.
+#   follow         The id of an earlier site. The requirement becomes the
+#                  newest minor window that fits inside that site's upper 
bound.
+#   floor          Raise only the lower bound to the newest stable minor.
+#   rename         Key in "renames" for tox envs and Gradle tasks that carry
+#                  the window's factor (for example 214 for torch 2.14).
+
+renames:
+  pytorch:
+    env_prefix: pytorch
+    files:
+      - sdks/python/tox.ini
+      - sdks/python/test-suites/tox/py311/build.gradle
+      - sdks/python/test-suites/tox/py314/build.gradle
+  tensorflow:
+    env_prefix: tensorflow
+    files:
+      - sdks/python/tox.ini
+      - sdks/python/test-suites/tox/py311/build.gradle
+  tft:
+    env_prefix: tft
+    files:
+      - sdks/python/tox.ini
+      - sdks/python/test-suites/tox/py311/build.gradle
+
+sites:
+  # --- torch ---
+  # Matched inside each setup.py / tox section so adding unrelated torch lines
+  # elsewhere does not shift sites.
+  - id: setup_torch_ml_base_core
+    file: sdks/python/setup.py
+    package: torch
+    pypi: torch
+    section: '(?s)ml_base_core = \[.*?\]'
+    pattern: '(?<![\w-])(?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    role: high
+    max_exclusive: '2.12.0'
+    hold_reason: >-
+      torch 2.12 requires triton 3.7, which aborts when imported after
+      tensorflow, and ml_base_core installs tensorflow.
+
+  - id: setup_torch_torch_extra
+    file: sdks/python/setup.py
+    package: torch
+    pypi: torch
+    section: "'torch':\\s*\\[[^\\]]*\\]"
+    pattern: '(?<![\w-])(?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: setup_torch_transformers_extra
+    file: sdks/python/setup.py
+    package: torch
+    pypi: torch
+    section: "(?s)'transformers':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    role: high
+    max_exclusive: '2.12.0'
+    hold_reason: >-
+      torch 2.12 requires triton 3.7, which aborts when imported after
+      tensorflow, and the transformers extra installs tensorflow.
+
+  - id: setup_torch_onnx_extra
+    file: sdks/python/setup.py
+    package: torch
+    pypi: torch
+    section: "(?s)'onnx':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    role: high
+    max_exclusive: '2.12.0'
+    hold_reason: >-
+      torch 2.12 requires triton 3.7, which aborts when imported after
+      tensorflow, and the onnx extra installs tensorflow.
+
+  - id: tox_torch_low
+    file: sdks/python/tox.ini
+    package: torch
+    pypi: torch
+    section: '(?ms)^\[testenv:py\d+-pytorch-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    occurrence: 1
+    role: low
+
+  - id: tox_torch_high
+    file: sdks/python/tox.ini
+    package: torch
+    pypi: torch
+    section: '(?ms)^\[testenv:py\d+-pytorch-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    occurrence: 2
+    role: high
+    follow: setup_torch_torch_extra
+    rename: pytorch
+
+  - id: tox_torch_py314
+    file: sdks/python/tox.ini
+    package: torch
+    pypi: torch
+    section: '(?ms)^\[testenv:py\d+-pytorch-\d+\](?:(?!^\[).)*'
+    pattern: '^[ \t]+(?P<req>torch>=[0-9.]+,<[0-9.]+)(?=\s*$)'
+    role: high
+    follow: setup_torch_torch_extra
+    rename: pytorch
+
+  # --- tensorflow ---
+  - id: setup_tensorflow_ml_base_core
+    file: sdks/python/setup.py
+    package: tensorflow
+    pypi: tensorflow
+    section: '(?s)ml_base_core = \[.*?\]'
+    pattern: '(?<![\w-])(?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: setup_tensorflow_extra
+    file: sdks/python/setup.py
+    package: tensorflow
+    pypi: tensorflow
+    section: "(?s)'tensorflow':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: setup_tensorflow_onnx_extra
+    file: sdks/python/setup.py
+    package: tensorflow
+    pypi: tensorflow
+    section: "(?s)'onnx':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: tox_tensorflow_common_deps
+    file: sdks/python/tox.ini
+    package: tensorflow
+    pypi: tensorflow
+    pattern: "COMMON_DEPS = '(?P<req>tensorflow>=[0-9.]+,<[0-9.]+)"
+    role: high
+
+  - id: tox_tensorflow_low
+    file: sdks/python/tox.ini
+    package: tensorflow
+    pypi: tensorflow
+    section: '(?ms)^\[testenv:py\d+-tensorflow-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    occurrence: 1
+    role: low
+
+  - id: tox_tensorflow_high
+    file: sdks/python/tox.ini
+    package: tensorflow
+    pypi: tensorflow
+    section: '(?ms)^\[testenv:py\d+-tensorflow-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    occurrence: 2
+    role: high
+    follow: setup_tensorflow_ml_base_core
+    rename: tensorflow
+
+  - id: tox_tf_keras_high
+    file: sdks/python/tox.ini
+    package: tf-keras
+    pypi: tensorflow
+    section: '(?ms)^\[testenv:py\d+-tensorflow-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>tf-keras>=[0-9.]+,<[0-9.]+)'
+    occurrence: 2
+    role: high
+    follow: setup_tensorflow_ml_base_core
+    rename: tensorflow
+
+  # --- transformers ---
+  - id: setup_transformers_ml_base_core
+    file: sdks/python/setup.py
+    package: transformers
+    pypi: transformers
+    section: '(?s)ml_base_core = \[.*?\]'
+    pattern: '(?<![\w-])(?P<req>transformers>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: setup_transformers_extra
+    file: sdks/python/setup.py
+    package: transformers
+    pypi: transformers
+    section: "(?s)'transformers':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>transformers>=[0-9.]+,!=[0-9.*]+,<[0-9.]+)'
+    role: high
+    allow_major: true

Review Comment:
   Since `'transformers'` in `setup.py` is already `<5.21.0` (on major 5), 
`allow_major: true` isn't needed for `5.x` updates—instead it opts 
`setup_transformers_extra` (and `tox_transformers_latest`) into silently 
jumping to `6.x` when `transformers 6.0.0` ships. Let's drop `allow_major: 
true` here so `6.x` holds for human opt-in just like other packages.



##########
scripts/tools/ml_dependency_bounds.yaml:
##########
@@ -0,0 +1,370 @@
+#
+# 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.
+#
+
+# Sites read by update_ml_dependency_bounds.py. Current bounds are read from 
the
+# files at run time, so no pattern or value here depends on a bound that the
+# script changes.
+#
+# Site fields:
+#   id             Unique name used in reports.
+#   file           Path from the repository root.
+#   package        Distribution name as written in the requirement.
+#   pypi           Project name used for https://pypi.org/pypi/<pypi>/json.
+#   pattern        Regex (multiline) that matches the requirement. The named
+#                  group "req" is the text that the script may rewrite.
+#   occurrence     Which match of the pattern (inside section, if set) is this
+#                  site (1-based). Default 1.
+#   section        Optional regex selecting a file substring. pattern and
+#                  occurrence then apply only inside that substring.
+#   role           "high" sites are updated. "low" sites are never edited.
+#   max_exclusive  Optional ceiling. The upper bound is never raised past it.
+#   allow_major    If true, a minor-capped bound may move into a newer major.
+#                  Default false.
+#   hold_reason    Reported when the site cannot move.
+#   follow         The id of an earlier site. The requirement becomes the
+#                  newest minor window that fits inside that site's upper 
bound.
+#   floor          Raise only the lower bound to the newest stable minor.
+#   rename         Key in "renames" for tox envs and Gradle tasks that carry
+#                  the window's factor (for example 214 for torch 2.14).
+
+renames:
+  pytorch:
+    env_prefix: pytorch
+    files:
+      - sdks/python/tox.ini
+      - sdks/python/test-suites/tox/py311/build.gradle
+      - sdks/python/test-suites/tox/py314/build.gradle
+  tensorflow:
+    env_prefix: tensorflow
+    files:
+      - sdks/python/tox.ini
+      - sdks/python/test-suites/tox/py311/build.gradle
+  tft:
+    env_prefix: tft
+    files:
+      - sdks/python/tox.ini
+      - sdks/python/test-suites/tox/py311/build.gradle
+
+sites:
+  # --- torch ---
+  # Matched inside each setup.py / tox section so adding unrelated torch lines
+  # elsewhere does not shift sites.
+  - id: setup_torch_ml_base_core
+    file: sdks/python/setup.py
+    package: torch
+    pypi: torch
+    section: '(?s)ml_base_core = \[.*?\]'
+    pattern: '(?<![\w-])(?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    role: high
+    max_exclusive: '2.12.0'
+    hold_reason: >-
+      torch 2.12 requires triton 3.7, which aborts when imported after
+      tensorflow, and ml_base_core installs tensorflow.
+
+  - id: setup_torch_torch_extra
+    file: sdks/python/setup.py
+    package: torch
+    pypi: torch
+    section: "'torch':\\s*\\[[^\\]]*\\]"
+    pattern: '(?<![\w-])(?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: setup_torch_transformers_extra
+    file: sdks/python/setup.py
+    package: torch
+    pypi: torch
+    section: "(?s)'transformers':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    role: high
+    max_exclusive: '2.12.0'
+    hold_reason: >-
+      torch 2.12 requires triton 3.7, which aborts when imported after
+      tensorflow, and the transformers extra installs tensorflow.
+
+  - id: setup_torch_onnx_extra
+    file: sdks/python/setup.py
+    package: torch
+    pypi: torch
+    section: "(?s)'onnx':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    role: high
+    max_exclusive: '2.12.0'
+    hold_reason: >-
+      torch 2.12 requires triton 3.7, which aborts when imported after
+      tensorflow, and the onnx extra installs tensorflow.
+
+  - id: tox_torch_low
+    file: sdks/python/tox.ini
+    package: torch
+    pypi: torch
+    section: '(?ms)^\[testenv:py\d+-pytorch-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    occurrence: 1
+    role: low
+
+  - id: tox_torch_high
+    file: sdks/python/tox.ini
+    package: torch
+    pypi: torch
+    section: '(?ms)^\[testenv:py\d+-pytorch-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>torch>=[0-9.]+,<[0-9.]+)'
+    occurrence: 2
+    role: high
+    follow: setup_torch_torch_extra
+    rename: pytorch
+
+  - id: tox_torch_py314
+    file: sdks/python/tox.ini
+    package: torch
+    pypi: torch
+    section: '(?ms)^\[testenv:py\d+-pytorch-\d+\](?:(?!^\[).)*'
+    pattern: '^[ \t]+(?P<req>torch>=[0-9.]+,<[0-9.]+)(?=\s*$)'
+    role: high
+    follow: setup_torch_torch_extra
+    rename: pytorch
+
+  # --- tensorflow ---
+  - id: setup_tensorflow_ml_base_core
+    file: sdks/python/setup.py
+    package: tensorflow
+    pypi: tensorflow
+    section: '(?s)ml_base_core = \[.*?\]'
+    pattern: '(?<![\w-])(?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: setup_tensorflow_extra
+    file: sdks/python/setup.py
+    package: tensorflow
+    pypi: tensorflow
+    section: "(?s)'tensorflow':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: setup_tensorflow_onnx_extra
+    file: sdks/python/setup.py
+    package: tensorflow
+    pypi: tensorflow
+    section: "(?s)'onnx':\\s*\\[.*?\\]"
+    pattern: '(?<![\w-])(?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    role: high
+
+  - id: tox_tensorflow_common_deps
+    file: sdks/python/tox.ini
+    package: tensorflow
+    pypi: tensorflow
+    pattern: "COMMON_DEPS = '(?P<req>tensorflow>=[0-9.]+,<[0-9.]+)"
+    role: high
+
+  - id: tox_tensorflow_low
+    file: sdks/python/tox.ini
+    package: tensorflow
+    pypi: tensorflow
+    section: '(?ms)^\[testenv:py\d+-tensorflow-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    occurrence: 1
+    role: low
+
+  - id: tox_tensorflow_high
+    file: sdks/python/tox.ini
+    package: tensorflow
+    pypi: tensorflow
+    section: '(?ms)^\[testenv:py\d+-tensorflow-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>tensorflow>=[0-9.]+,<[0-9.]+)'
+    occurrence: 2
+    role: high
+    follow: setup_tensorflow_ml_base_core
+    rename: tensorflow
+
+  - id: tox_tf_keras_high
+    file: sdks/python/tox.ini
+    package: tf-keras
+    pypi: tensorflow
+    section: '(?ms)^\[testenv:py\d+-tensorflow-\{[^}]+\}\](?:(?!^\[).)*'
+    pattern: '^[ \t]+[0-9]+: (?P<req>tf-keras>=[0-9.]+,<[0-9.]+)'
+    occurrence: 2
+    role: high
+    follow: setup_tensorflow_ml_base_core
+    rename: tensorflow

Review Comment:
   `tox_tf_keras_high` has `pypi: tensorflow` and `follow: 
setup_tensorflow_ml_base_core`, and `_follow()` doesn't check PyPI for 
`tf-keras`.
   
   In practice, `tf-keras` lags `tensorflow` on PyPI by 1–22 days (`2.20.1`: 
+22 days with `2.20.0` yanked; `2.21.0`: +12 days; `2.22.0`: +29 hours), and 
each `tf-keras 2.N.*` pins `tensorflow<2.(N+1),>=2.N`. If the Sunday cron runs 
during that lag window, this writes an unresolvable `tf-keras>=2.N.0,<2.(N+1)` 
into `tox.ini` (and `py311-tensorflow-2NN` can't resolve with `tf-keras 
2.(N-1)` either).
   
   Could we set `pypi: tf-keras` here and gate/hold the TensorFlow high-window 
bump (or hold `tox_tf_keras_high` + `tox_tensorflow_high` / 
`setup_tensorflow_ml_base_core` via a companion-package check) until `tf-keras` 
has published a matching minor on PyPI?



##########
scripts/tools/update_ml_dependency_bounds.py:
##########
@@ -0,0 +1,491 @@
+#
+# 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.
+#
+"""Raises the exclusive upper bounds of ML dependencies.
+
+For every site listed in ml_dependency_bounds.yaml the script reads the current
+requirement from the repository files, compares it with the latest stable
+release on PyPI, and rewrites only the version number inside that requirement
+string. For example, torch>=2.3.0,<2.15.0 becomes torch>=2.3.0,<2.16.0: the
+package name, lower bound, != exclusions, quotes, and nearby comments stay as
+they are. Container lockfiles are not regenerated.
+
+Tox environments and Gradle tasks that carry the version of the highest tested
+window are renamed together with the window.
+
+See scripts/tools/README_ml_dependency_bounds.md for the full behavior, holds,
+and an example generated PR body.
+
+Run it from anywhere:
+
+  python scripts/tools/update_ml_dependency_bounds.py
+"""
+
+import argparse
+import http.client
+import json
+import re
+import sys
+import time
+import urllib.request
+from dataclasses import dataclass
+from dataclasses import field
+from pathlib import Path
+from typing import Callable
+from typing import Optional
+
+import yaml
+from packaging.requirements import Requirement
+from packaging.utils import canonicalize_name
+from packaging.version import InvalidVersion
+from packaging.version import Version
+
+PR_TITLE = 'Update ML dependency bounds'
+
+README_URL = ('https://github.com/apache/beam/blob/master/scripts/tools/'
+              'README_ml_dependency_bounds.md')
+
+PR_REVIEW_SENTENCE = (
+    'This PR was created by automation and has not been reviewed by a human '
+    'yet. By default GitHub Actions does not run the usual PR tests on this '
+    'branch. To review: (1) check the bound changes look right, (2) close and '
+    'reopen the PR so tests run, (3) approve/merge only if tests pass.')

Review Comment:
   Once the `gh workflow list` limit is fixed, this workflow will automatically 
dispatch the Python PostCommit workflows on the branch, while closing and 
reopening the PR is specifically needed to trigger the `pull_request` PreCommit 
checks (`PreCommit Python`, `PreCommit Python ML`, etc.). Updating this 
sentence (and the matching example in `README_ml_dependency_bounds.md`) will 
keep reviewer instructions accurate.



##########
.github/workflows/update_ml_dependency_bounds.yml:
##########
@@ -0,0 +1,144 @@
+# 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.
+
+# Raises exclusive upper bounds of ML dependencies in setup.py / tox.ini when
+# PyPI has a newer stable release, then opens a pull request. Never merges.
+# Does not regenerate container requirements (see 
update_python_dependencies.yml).
+#
+# If an open pull request titled "Update ML dependency bounds*" already exists,
+# this run is skipped so reviewer edits on that branch are not overwritten.
+# Close that PR to get a fresh run.
+#
+# Behavior, holds, and an example generated PR body:
+#   scripts/tools/README_ml_dependency_bounds.md
+#
+# Example PR body the script generates:
+#
+#   This PR was created by automation and has not been reviewed by a human yet.
+#   ...
+#   Bumped bounds:
+#   - setup_torch_torch_extra (sdks/python/setup.py): torch>=2.3.0,<2.15.0 -> 
torch>=2.3.0,<2.16.0
+#   Held:
+#   - setup_torch_ml_base_core: torch 2.12 requires triton 3.7, ...
+
+name: Update ML Dependency Bounds
+
+on:
+  schedule:
+  - cron: "0 0 * * 0"
+  workflow_dispatch:
+permissions:
+  actions: write
+  contents: write
+  pull-requests: write
+
+concurrency:
+  group: '${{ github.workflow }} @ ${{ github.ref }}'
+  cancel-in-progress: true
+
+jobs:
+  update_ml_dependency_bounds:
+    if: github.event_name == 'workflow_dispatch' || github.repository == 
'apache/beam'
+    runs-on: [self-hosted, ubuntu-24.04, main]

Review Comment:
   Since line 54 allows `workflow_dispatch` on forks and this job doesn't need 
GCP/Develocity/Gradle or large disk (just Python 3.11, `pip`, and `gh`), could 
we run it on `ubuntu-latest` (like `beam_PreCommit_ML_Dependency_Bounds.yml`) 
with `actions/setup-python@v7`? Right now `[self-hosted, ubuntu-24.04, main]` 
will queue indefinitely if someone tries to test via `workflow_dispatch` on a 
fork, and occupies a `main` runner unnecessarily.



##########
.github/workflows/update_ml_dependency_bounds.yml:
##########
@@ -0,0 +1,144 @@
+# 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.
+
+# Raises exclusive upper bounds of ML dependencies in setup.py / tox.ini when
+# PyPI has a newer stable release, then opens a pull request. Never merges.
+# Does not regenerate container requirements (see 
update_python_dependencies.yml).
+#
+# If an open pull request titled "Update ML dependency bounds*" already exists,
+# this run is skipped so reviewer edits on that branch are not overwritten.
+# Close that PR to get a fresh run.
+#
+# Behavior, holds, and an example generated PR body:
+#   scripts/tools/README_ml_dependency_bounds.md
+#
+# Example PR body the script generates:
+#
+#   This PR was created by automation and has not been reviewed by a human yet.
+#   ...
+#   Bumped bounds:
+#   - setup_torch_torch_extra (sdks/python/setup.py): torch>=2.3.0,<2.15.0 -> 
torch>=2.3.0,<2.16.0
+#   Held:
+#   - setup_torch_ml_base_core: torch 2.12 requires triton 3.7, ...
+
+name: Update ML Dependency Bounds
+
+on:
+  schedule:
+  - cron: "0 0 * * 0"
+  workflow_dispatch:
+permissions:
+  actions: write
+  contents: write
+  pull-requests: write
+
+concurrency:
+  group: '${{ github.workflow }} @ ${{ github.ref }}'
+  cancel-in-progress: true
+
+jobs:
+  update_ml_dependency_bounds:
+    if: github.event_name == 'workflow_dispatch' || github.repository == 
'apache/beam'
+    runs-on: [self-hosted, ubuntu-24.04, main]
+    name: Update ML Dependency Bounds
+    timeout-minutes: 30
+    steps:
+      - name: Checkout code
+        uses: actions/checkout@v7
+        with:
+          persist-credentials: false
+      - name: Setup environment
+        uses: $/.github/actions/setup-environment-action
+        with:
+          python-version: "3.11"
+          # The script does not use tox.
+          tox-cache: false
+      - name: Install script dependencies
+        run: pip install packaging pyyaml pytest
+      - name: Install gh cli
+        uses: $/.github/actions/setup-gh-cli-linux
+      - name: Check for an open pull request from this workflow
+        id: existing_pr
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+        run: |
+          existingPr=$(gh pr list --state open --limit 5 \

Review Comment:
   Nit: `--limit 5` is a bit tight if 5 fork/cross-repo PRs happen to match 
that title before `select(.isCrossRepository | not)` filters them—bumping to 
`--limit 50` is free and safer.



##########
.github/workflows/beam_PreCommit_ML_Dependency_Bounds.yml:
##########
@@ -0,0 +1,62 @@
+# 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.
+
+# Keeps scripts/tools/ml_dependency_bounds.yaml matched to setup.py / tox.ini
+# and runs the updater unit tests on PRs that touch those files.
+
+name: PreCommit ML Dependency Bounds
+
+on:
+  pull_request:
+    branches: ['master', 'release-*']
+    paths:
+      - 'scripts/tools/update_ml_dependency_bounds.py'
+      - 'scripts/tools/update_ml_dependency_bounds_test.py'
+      - 'scripts/tools/ml_dependency_bounds.yaml'
+      - 'scripts/tools/README_ml_dependency_bounds.md'
+      - 'sdks/python/setup.py'
+      - 'sdks/python/tox.ini'
+      - 'sdks/python/test-suites/tox/py311/build.gradle'
+      - 'sdks/python/test-suites/tox/py314/build.gradle'
+      - 'sdks/python/apache_beam/ml/inference/xgboost_tests_requirements.txt'
+      - '.github/workflows/beam_PreCommit_ML_Dependency_Bounds.yml'
+      - 'release/trigger_all_tests.json'
+  workflow_dispatch:
+
+permissions:
+  contents: read
+
+concurrency:
+  group: '${{ github.workflow }} @ ${{ github.event.pull_request.number || 
github.sha || github.head_ref || github.ref }}'
+  cancel-in-progress: true
+
+jobs:
+  ml_dependency_bounds_tests:
+    name: ML dependency bounds script tests
+    runs-on: ubuntu-latest
+    timeout-minutes: 15
+    steps:
+      - name: Checkout code
+        uses: actions/checkout@v7
+        with:
+          persist-credentials: false
+      - name: Setup Python
+        uses: actions/setup-python@v6

Review Comment:
   Nit: the rest of `.github/workflows/` uses `actions/setup-python@v7`—let's 
match that for consistency.



##########
scripts/tools/update_ml_dependency_bounds.py:
##########
@@ -0,0 +1,491 @@
+#

Review Comment:
   Optional style nit: Beam's Python formatter config (`sdks/python/setup.cfg`, 
`[yapf] indent_width = 2`, also used by `scripts/tools/bomupgrader.py`) uses 
2-space indentation (`beam_PreCommit_PythonFormatter` only scans 
`sdks/python/`). Feel free to reformat with `yapf --style 
sdks/python/setup.cfg` if you'd like to match repo style.



##########
scripts/tools/update_ml_dependency_bounds.py:
##########
@@ -0,0 +1,491 @@
+#
+# 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.
+#
+"""Raises the exclusive upper bounds of ML dependencies.
+
+For every site listed in ml_dependency_bounds.yaml the script reads the current
+requirement from the repository files, compares it with the latest stable
+release on PyPI, and rewrites only the version number inside that requirement
+string. For example, torch>=2.3.0,<2.15.0 becomes torch>=2.3.0,<2.16.0: the
+package name, lower bound, != exclusions, quotes, and nearby comments stay as
+they are. Container lockfiles are not regenerated.
+
+Tox environments and Gradle tasks that carry the version of the highest tested
+window are renamed together with the window.
+
+See scripts/tools/README_ml_dependency_bounds.md for the full behavior, holds,
+and an example generated PR body.
+
+Run it from anywhere:
+
+  python scripts/tools/update_ml_dependency_bounds.py
+"""
+
+import argparse
+import http.client
+import json
+import re
+import sys
+import time
+import urllib.request
+from dataclasses import dataclass
+from dataclasses import field
+from pathlib import Path
+from typing import Callable
+from typing import Optional
+
+import yaml
+from packaging.requirements import Requirement
+from packaging.utils import canonicalize_name
+from packaging.version import InvalidVersion
+from packaging.version import Version
+
+PR_TITLE = 'Update ML dependency bounds'
+
+README_URL = ('https://github.com/apache/beam/blob/master/scripts/tools/'
+              'README_ml_dependency_bounds.md')
+
+PR_REVIEW_SENTENCE = (
+    'This PR was created by automation and has not been reviewed by a human '
+    'yet. By default GitHub Actions does not run the usual PR tests on this '
+    'branch. To review: (1) check the bound changes look right, (2) close and '
+    'reopen the PR so tests run, (3) approve/merge only if tests pass.')
+
+TOKENIZERS_NOTE = (
+    'tokenizers is capped below 0.22/0.23 in ml_base_core because the CLIP '
+    'tokenizer still passes cls= (see setup.py). transformers is installed in '
+    'the same list, so if a transformers bump needs a newer tokenizers, hold '
+    'the transformers bump instead of raising the tokenizers cap.')
+
+
+@dataclass
+class Site:
+    id: str
+    file: str
+    package: str
+    pypi: str
+    pattern: str
+    role: str
+    occurrence: int = 1
+    max_exclusive: Optional[str] = None
+    hold_reason: Optional[str] = None
+    follow: Optional[str] = None
+    floor: bool = False
+    rename: Optional[str] = None
+    # Optional regex that selects a file substring. pattern/occurrence then
+    # apply only inside that substring so file-wide indexes do not drift when
+    # unrelated lines are added elsewhere.
+    section: Optional[str] = None
+    # When false (default), hold if the newest PyPI major is above the current
+    # exclusive upper bound's major.
+    allow_major: bool = False
+
+
+@dataclass
+class Change:
+    site: str
+    file: str
+    old: str
+    new: str
+
+
+@dataclass
+class Hold:
+    site: str
+    reason: str
+
+
+@dataclass
+class Rename:
+    group: str
+    old: str
+    new: str
+
+
+@dataclass
+class Report:
+    changes: list[Change] = field(default_factory=list)
+    holds: list[Hold] = field(default_factory=list)
+    renames: list[Rename] = field(default_factory=list)
+
+
+def latest_stable(payload: dict) -> Version:
+    """Returns the newest release that is not yanked, pre, dev or local."""
+    latest = None
+    for text, files in payload.get('releases', {}).items():
+        # PEP 592: a release is yanked only when every file is yanked.
+        if not files or all(entry.get('yanked') for entry in files):
+            continue
+        try:
+            version = Version(text)
+        except InvalidVersion:
+            continue
+        if (version.is_prerelease or version.is_devrelease
+                or version.local is not None):
+            continue
+        if latest is None or version > latest:
+            latest = version
+    if latest is None:
+        raise RuntimeError('No stable release found.')
+    return latest
+
+
+def fetch_latest_stable(project: str, attempts: int = 3) -> Version:
+    url = f'https://pypi.org/pypi/{project}/json'
+    for attempt in range(1, attempts + 1):
+        try:
+            with urllib.request.urlopen(url, timeout=60) as response:
+                return latest_stable(json.load(response))
+        except (OSError, http.client.HTTPException):

Review Comment:
   Nit: if a large PyPI JSON payload is cut off mid-stream (or returns a 
transient non-JSON error page), `json.load(response)` raises 
`json.JSONDecodeError` (a `ValueError` subclass), which won't be caught by 
`(OSError, http.client.HTTPException)`. Adding `json.JSONDecodeError` here 
makes the retry match the comment.



##########
scripts/tools/update_ml_dependency_bounds_test.py:
##########
@@ -0,0 +1,439 @@
+#
+# 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.
+#
+"""Tests for update_ml_dependency_bounds.py. No network access is needed."""
+
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import update_ml_dependency_bounds as bounds  # pylint: 
disable=wrong-import-position
+from packaging.version import Version  # pylint: disable=wrong-import-position
+
+SCRIPTS_DIR = Path(__file__).resolve().parent
+CONFIG = SCRIPTS_DIR / 'ml_dependency_bounds.yaml'
+
+SETUP_PY = """\
+ml_base_core = [
+    'onnx>=1.14.1,<2',
+    'tensorflow>=2.16.0,<2.22',
+    'tokenizers<0.23',
+    'torch>=2.3.0,<2.12.0',
+    'transformers>=4.28.0,<4.56.0',
+    'tokenizers>=0.13.3,<0.22.0',
+]
+extras = {
+    'torch': ['torch>=2.3.0,<2.15.0'],
+    'tensorflow': [
+        # Comment that must stay.
+        'tensorflow>=2.16.0,<2.22',
+        'absl-py>=0.12.0'
+    ],
+    'transformers': [
+        'transformers>=4.41.0,!=4.56.*,<5.21.0',
+        'tensorflow>=2.12.0',
+        'torch>=2.3.0,<2.12.0'
+    ],
+    'ml_cpu': [
+        'tensorflow>=2.12.0',
+        'torch==2.8.0+cpu',
+        'transformers>=4.28.0,<4.56.0',
+    ],
+    'onnx': [
+        'onnx>=1.16.0,<2',
+        'onnxruntime>=1.19.0,<2',
+        'skl2onnx>=1.17.0,<2',
+        'tensorflow>=2.18.0,<2.22',
+        'torch>=2.3.0,<2.12.0',
+    ],
+}
+"""
+
+TOX_INI = """\
+[testenv:py311-pytorch-{23,214}]
+deps =
+  23: torch>=2.3.0,<2.4.0
+  214: torch>=2.14.0,<2.15.0
+extras = test,gcp
+
+[testenv:py314-pytorch-214]
+deps =
+  torch>=2.14.0,<2.15.0
+extras = test,gcp
+
+[testenv:py311-onnx-{119,latest}]
+deps =
+  119: onnxruntime>=1.19.0,<1.20
+  119: torch>=2.3.0,<2.4.0
+  latest: onnxruntime>=1.31.0,<2
+  latest: onnx>=1.23.0,<2
+  latest: skl2onnx>=1.20.0,<2
+  latest: torch>=2.11.0,<2.12.0
+
+[testenv:py311-tensorflow-{216,221}]
+deps =
+  216: tensorflow>=2.16.0,<2.17
+  216: tf-keras>=2.16.0,<2.17
+  221: tensorflow>=2.21.0,<2.22
+  221: tf-keras>=2.21.0,<2.22
+extras =
+  216: test
+  221: test,gcp
+
+[testenv:py311-transformers-{441,457,latest}]
+setenv =
+    COMMON_DEPS = 'tensorflow>=2.16,<2.22' tf-keras
+    latest: DEPS = 'transformers>=5.20.0,<5.21.0' 'torch>=2.11.0,<2.12.0'
+"""
+
+PY311_GRADLE = """\
+toxTask "testPy311pytorch-23", "py311-pytorch-23", "${posargs}"
+toxTask "testPy311pytorch-214", "py311-pytorch-214", "${posargs}"
+toxTask "testPy311onnx-latest", "py311-onnx-latest", "${posargs}"
+toxTask "testPy311tensorflow-216", "py311-tensorflow-216", "${posargs}"
+toxTask "testPy311tensorflow-221", "py311-tensorflow-221", "${posargs}"
+toxTask "testPy311transformers-latest", "py311-transformers-latest", 
"${posargs}"
+"""
+
+PY314_GRADLE = """\
+// Keep in sync with [testenv:py314-pytorch-214] in tox.ini.
+toxTask "testPy314pytorch-214", "py314-pytorch-214", "${posargs}"
+"""
+
+FILES = {
+    'sdks/python/setup.py': SETUP_PY,
+    'sdks/python/tox.ini': TOX_INI,
+    'sdks/python/test-suites/tox/py311/build.gradle': PY311_GRADLE,
+    'sdks/python/test-suites/tox/py314/build.gradle': PY314_GRADLE,
+}
+
+
+def fake_pypi(releases: dict[str, list[str]]):
+    """Returns a latest_of function backed by fake PyPI JSON payloads."""
+    payloads = {
+        project: {
+            'releases': {
+                version: [{
+                    'yanked': False
+                }]
+                for version in versions
+            }
+        }
+        for project, versions in releases.items()
+    }
+    return lambda project: bounds.latest_stable(payloads[project])
+
+
+class UpdateMlDependencyBoundsTest(unittest.TestCase):
+
+    def setUp(self):
+        self.temp_dir = tempfile.TemporaryDirectory()
+        self.addCleanup(self.temp_dir.cleanup)
+        self.root = Path(self.temp_dir.name)
+        for name, text in FILES.items():
+            path = self.root / name
+            path.parent.mkdir(parents=True, exist_ok=True)
+            bounds.write_text(path, text)
+
+    def updater(self, site_ids, releases):
+        sites, renames = bounds.load_config(CONFIG)
+        selected = [site for site in sites if site.id in site_ids]
+        self.assertEqual(len(selected), len(site_ids))
+        return bounds.BoundsUpdater(self.root, selected, renames,
+                                    fake_pypi(releases))
+
+    def run_updates(self, site_ids, releases):
+        updater = self.updater(site_ids, releases)
+        report = updater.run()
+        updater.write()
+        return report
+
+    def read(self, name):
+        return bounds.read_text(self.root / name)
+
+    def test_minor_cap_rises_and_low_factor_stays(self):
+        report = self.run_updates(['setup_torch_torch_extra', 'tox_torch_low'],
+                                  {'torch': ['2.3.0', '2.14.0', '2.15.1']})
+        setup_py = self.read('sdks/python/setup.py')
+        self.assertIn("'torch': ['torch>=2.3.0,<2.16.0']", setup_py)
+        self.assertEqual([(c.old, c.new) for c in report.changes],
+                         [('torch>=2.3.0,<2.15.0', 'torch>=2.3.0,<2.16.0')])
+        self.assertIn('23: torch>=2.3.0,<2.4.0',
+                      self.read('sdks/python/tox.ini'))
+
+    def test_minor_cap_without_new_release_is_unchanged(self):
+        report = self.run_updates(['setup_torch_torch_extra'],
+                                  {'torch': ['2.3.0', '2.14.2']})
+        self.assertEqual(report.changes, [])
+        self.assertEqual(report.holds, [])
+        self.assertEqual(self.read('sdks/python/setup.py'), SETUP_PY)
+
+    def test_site_at_max_exclusive_holds_and_reports_reason(self):
+        report = self.run_updates(['setup_torch_ml_base_core'],
+                                  {'torch': ['2.14.0', '2.15.1']})
+        self.assertEqual(self.read('sdks/python/setup.py'), SETUP_PY)
+        self.assertEqual(report.changes, [])
+        self.assertEqual([h.site for h in report.holds],
+                         ['setup_torch_ml_base_core'])
+        self.assertIn('triton', report.holds[0].reason)
+        self.assertIn(report.holds[0].reason, bounds.render_pr_body(report))
+
+    def test_major_cap_stays_when_latest_is_inside(self):
+        report = self.run_updates(['setup_onnx_ml_base_core'],
+                                  {'onnx': ['1.23.0']})
+        self.assertEqual(self.read('sdks/python/setup.py'), SETUP_PY)
+        self.assertEqual(report.holds, [])
+
+    def test_major_cap_stays_and_holds_when_latest_is_next_major(self):
+        report = self.run_updates(['setup_onnx_ml_base_core'],
+                                  {'onnx': ['1.23.0', '2.0.0']})
+        self.assertEqual(self.read('sdks/python/setup.py'), SETUP_PY)
+        self.assertEqual(report.changes, [])
+        self.assertEqual([h.site for h in report.holds],
+                         ['setup_onnx_ml_base_core'])
+
+    def test_transformers_exclusion_survives(self):
+        self.run_updates(['setup_transformers_extra'],
+                         {'transformers': ['4.57.0', '5.23.1']})
+        self.assertIn("'transformers>=4.41.0,!=4.56.*,<5.24.0'",
+                      self.read('sdks/python/setup.py'))
+
+    def test_transformers_base_core_holds_across_major(self):
+        report = self.run_updates(['setup_transformers_ml_base_core'],
+                                  {'transformers': ['4.57.0', '5.23.1']})
+        setup_py = self.read('sdks/python/setup.py')
+        self.assertIn("'transformers>=4.28.0,<4.56.0'", setup_py)
+        self.assertEqual(report.changes, [])
+        self.assertEqual([h.site for h in report.holds],
+                         ['setup_transformers_ml_base_core'])
+        self.assertIn('crosses major', report.holds[0].reason)
+
+    def test_transformers_extra_allow_major_can_cross(self):
+        # The transformers extra already tracks 5.x and sets allow_major.
+        self.run_updates(['setup_transformers_extra'],
+                         {'transformers': ['5.23.1']})
+        self.assertIn("'transformers>=4.41.0,!=4.56.*,<5.24.0'",
+                      self.read('sdks/python/setup.py'))

Review Comment:
   In `SETUP_PY`, `setup_transformers_extra` is already `<5.21.0`, so passing 
`5.23.1` stays within major `5` and doesn't exercise the `allow_major=True` 
branch in `_raise_upper()`. Once `allow_major: true` is removed from 
`setup_transformers_extra` in the YAML, could we update this test to set 
`selected[0].allow_major = True` on a site (like 
`test_site_below_ceiling_stops_at_ceiling` does) and pass `6.0.0` to verify 
major-crossing opt-in actually works?



-- 
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]

Reply via email to