From b8121fec70f7d6797f4c7c2af1861643b8851323 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 18 Nov 2026 20:14:49 -0600 Subject: [PATCH 1/4] ci(py): gate PRs on minimum dep versions, add find_min_dep_version, and document policy --- .github/workflows/python.yml | 86 +++++++++++++- README.md | 2 +- bin/find_min_dep_version | 209 +++++++++++++++++++++++++++++++++++ docs/dependencies.md | 63 +++++++++++ pyproject.toml | 3 +- scripts/check_consistency.py | 1 + 6 files changed, 358 insertions(+), 6 deletions(-) create mode 100755 bin/find_min_dep_version create mode 100644 docs/dependencies.md diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index fb173a989..e54478561 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -63,6 +63,22 @@ jobs: - name: Run consistency checks run: python3 ./scripts/check_consistency.py + - name: Ensure minor/patch Dependabot PRs only update uv.lock + if: >- + github.event_name == 'pull_request' && + github.event.pull_request.user.login == 'dependabot[bot]' && + (startsWith(github.head_ref, 'dependabot/uv/py-minor-and-patch') || + startsWith(github.head_ref, 'dependabot/uv/py-dependencies')) + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + git fetch --no-tags --depth=1 origin "$BASE_SHA" + touched=$(git diff --name-only "$BASE_SHA" HEAD -- 'packages/*/pyproject.toml') + if [[ -n "$touched" ]]; then + echo "::error title=Unexpected pyproject.toml edit::Routine minor/patch Dependabot PRs must only update uv.lock, not published bounds in packages/*/pyproject.toml ($touched). Revert the pyproject.toml edit and run 'uv lock'." + exit 1 + fi + type-check: name: Type Check (${{ matrix.checker }}) runs-on: ubuntu-latest @@ -199,6 +215,68 @@ jobs: uv run --no-sync --python "$PY_VER" pytest fi + # Floors in packages/*/pyproject.toml are what users resolve against, but the + # tests job only runs uv.lock (newest). This job resolves every direct dep at + # its declared floor. If it fails, the PR started using a newer API: run + # `bin/find_min_dep_version ` and raise the floor in the same PR. + tests-minimum-deps: + name: Tests (minimum pyproject.toml versions, Python 3.10) + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y build-essential libffi-dev cmake libjpeg-dev zlib1g-dev + + - name: Install uv and setup Python + uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5 + with: + enable-cache: true + python-version: "3.10" + + - name: Resolve direct deps at their floors + run: | + uv lock --resolution lowest-direct + echo "=== Direct deps downgraded from uv.lock -> declared floors ===" + git diff -U1 uv.lock | grep -E '^[ +-](name|version) = ' || echo 'uv.lock already at floors' + + - name: Install dependencies + run: uv sync --frozen --python 3.10 + + - name: Generate schema typing + run: ./bin/generate_schema_typing --ci + + - name: Run tests + run: uv run --no-sync --python 3.10 pytest + + - name: Print self-triage guide on failure + if: failure() + run: | + cat <<'EOF' | tee -a "$GITHUB_STEP_SUMMARY" + ### `tests-minimum-deps` failed — how to fix + + This job tests `packages/*/pyproject.toml` at their minimum `>=` versions (`uv lock --resolution lowest-direct`). If regular `tests` passed and this job failed, a package calls an API newer than its declared floor. + + 1. **Find the failing package & dep** from the pytest traceback above (e.g. `packages/genkit-openai/tests/...` -> package `genkit-openai`, dep `openai`; check the `Resolve direct deps` step above to see which deps moved down). + 2. **Auto-bump the exact minimum passing floor and refresh `uv.lock`:** + ```bash + bin/find_min_dep_version --apply + ``` + *(Shortcut if `find_min_dep_version` has too many releases to search: set the floor in `packages//pyproject.toml` straight to the version in `uv.lock`, then run `uv lock`.)* + 3. **Verify policy & commit** `packages//pyproject.toml` + `uv.lock` (keep existing `=' floor in packages/*/pyproject.toml is too old. Run 'bin/find_min_dep_version --apply' locally (see step log / summary for full steps and docs/dependencies.md)." + build: name: Build Distributions runs-on: ubuntu-latest @@ -206,7 +284,7 @@ jobs: permissions: contents: read if: always() && !failure() && !cancelled() - needs: [lint-and-format, type-check, security-and-compliance, tests] + needs: [lint-and-format, type-check, security-and-compliance, tests, tests-minimum-deps] steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: @@ -263,16 +341,16 @@ jobs: runs-on: ubuntu-latest permissions: contents: read - needs: [lint-and-format, type-check, security-and-compliance, tests, build] + needs: [lint-and-format, type-check, security-and-compliance, tests, tests-minimum-deps, build] if: always() steps: - name: Verify all Python jobs succeeded env: RESULTS: >- - ${{ needs.lint-and-format.result }},${{ needs.type-check.result }},${{ needs.security-and-compliance.result }},${{ needs.tests.result }},${{ needs.build.result }} + ${{ needs.lint-and-format.result }},${{ needs.type-check.result }},${{ needs.security-and-compliance.result }},${{ needs.tests.result }},${{ needs.tests-minimum-deps.result }},${{ needs.build.result }} run: | echo "Python job results: $RESULTS" - if [[ "$RESULTS" != "success,success,success,success,success" ]]; then + if [[ "$RESULTS" != "success,success,success,success,success,success" ]]; then echo "::error::One or more Python checks did not succeed: $RESULTS" exit 1 fi diff --git a/README.md b/README.md index b85247c70..37bf01bb5 100644 --- a/README.md +++ b/README.md @@ -258,7 +258,7 @@ If you're contributing to the Python SDK: 2. **Install Dependencies**: `uv sync` 3. **Run Linters & Tests**: `just lint` and `just test` -For coding standards and detailed guidelines, see [CONTRIBUTING.md](CONTRIBUTING.md). +For coding standards and detailed guidelines, see [CONTRIBUTING.md](CONTRIBUTING.md). For version bounds and lockfile updates, see [docs/dependencies.md](docs/dependencies.md). --- diff --git a/bin/find_min_dep_version b/bin/find_min_dep_version new file mode 100755 index 000000000..2a731ddf4 --- /dev/null +++ b/bin/find_min_dep_version @@ -0,0 +1,209 @@ +#!/usr/bin/env -S uv run --script +# /// script +# requires-python = ">=3.11" +# dependencies = ["certifi", "packaging"] +# /// +# Copyright 2026 Google LLC +# +# Licensed 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. +# +# SPDX-License-Identifier: Apache-2.0 +# ruff: noqa: T201, S603, S607 + +"""Find (and optionally apply) the lowest passing version of a dependency. + +Use when the `tests-minimum-deps` CI job fails on a PR: it binary-searches PyPI +releases between the declared floor in `packages//pyproject.toml` and +the version in `uv.lock`, running `packages//tests` in an isolated env +at each step. + + bin/find_min_dep_version genkit-openai openai --apply +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import ssl +import subprocess +import sys +import tomllib +import urllib.request +from pathlib import Path + +import certifi +from packaging.version import InvalidVersion, Version + +PY_DIR = Path(__file__).resolve().parents[1] + + +def _toml_path(package: str) -> Path: + path = PY_DIR / 'packages' / package / 'pyproject.toml' + if not path.exists(): + available = sorted(p.parent.name for p in (PY_DIR / 'packages').glob('*/pyproject.toml')) + sys.exit(f"unknown package '{package}'. Available: {', '.join(available)}") + return path + + +def _all_specs(data: dict) -> list[str]: + proj = data.get('project', {}) + specs = list(proj.get('dependencies', [])) + for extra_specs in proj.get('optional-dependencies', {}).values(): + specs.extend(extra_specs) + return specs + + +def _declared_floor(package: str, dep: str) -> Version: + data = tomllib.loads(_toml_path(package).read_text()) + found_deps: list[str] = [] + for spec in _all_specs(data): + m = re.match(r'([A-Za-z0-9._-]+)(?:\[[^\]]*\])?\s*([^;]*)', spec) + if not m: + continue + name = m.group(1).lower().replace('_', '-') + found_deps.append(name) + if name == dep: + floor = re.search(r'>=\s*([^,\s]+)', m.group(2)) + if floor: + return Version(floor.group(1)) + sys.exit(f"{package} has no '>=' floor for '{dep}'. Declared deps: {', '.join(sorted(set(found_deps)))}") + + +def _apply_floor(package: str, dep: str, new_floor: Version) -> None: + path = _toml_path(package) + original = path.read_text() + pattern = re.compile( + rf'("(?P[A-Za-z0-9._-]+)(?P\[[^\]]*\])?\s*>=\s*)(?P[^,",;\s]+)', + ) + + def _replace(match: re.Match[str]) -> str: + if match.group('name').lower().replace('_', '-') != dep: + return match.group(0) + return f'{match.group(1)}{new_floor}' + + updated = pattern.sub(_replace, original) + if updated == original: + sys.exit(f'failed to rewrite {dep} floor in {path}') + path.write_text(updated) + subprocess.run(['uv', 'lock'], cwd=PY_DIR, check=True) + + +def _locked_versions(dep: str) -> list[Version]: + text = (PY_DIR / 'uv.lock').read_text() + return [Version(v) for v in re.findall(rf'name = "{re.escape(dep)}"\nversion = "([^"]+)"', text)] + + +def _releases(dep: str) -> list[Version]: + ctx = ssl.create_default_context(cafile=certifi.where()) + with urllib.request.urlopen(f'https://pypi.org/pypi/{dep}/json', timeout=30, context=ctx) as r: + data = json.load(r) + out = [] + for v, files in data['releases'].items(): + try: + pv = Version(v) + except InvalidVersion: + continue + if files and not pv.is_devrelease and not any(f.get('yanked') for f in files): + out.append(pv) + return sorted(out) + + +def _passes(package: str, dep: str, version: Version, python: str | None) -> bool: + cmd = ['uv', 'run', '-q', '--isolated', '--directory', str(PY_DIR), '--package', package] + if python: + cmd += ['--python', python] + for extra in (f'{dep}=={version}', 'pytest', 'pytest-asyncio', 'pytest-mock', 'psutil'): + cmd += ['--with', extra] + cmd += ['pytest', '-q', '-p', 'no:cacheprovider', f'packages/{package}/tests'] + env = {**os.environ, 'PYTEST_ADDOPTS': '-o addopts='} + proc = subprocess.run(cmd, capture_output=True, text=True, env=env, check=False) + last = (proc.stdout.strip().splitlines() or proc.stderr.strip().splitlines() or ['?'])[-1] + print(f'{dep}=={version}: {"PASS" if proc.returncode == 0 else "FAIL"} ({last[:100]})', flush=True) + return proc.returncode == 0 + + +def main() -> int: + """Run the floor search, print actionable next steps, or rewrite pyproject.toml + uv.lock with --apply.""" + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('package', help='workspace package dir under packages/, e.g. genkit-openai') + parser.add_argument('dep', help='third-party dependency name, e.g. openai') + parser.add_argument('--python', help='interpreter for test envs (default: uv picks; CI uses 3.10)') + parser.add_argument( + '--apply', + action='store_true', + help='rewrite packages//pyproject.toml to the found floor and update uv.lock', + ) + args = parser.parse_args() + dep = args.dep.lower().replace('_', '-') + + floor = _declared_floor(args.package, dep) + locked = _locked_versions(dep) + if not locked: + sys.exit(f'{dep} is not in uv.lock') + ceiling = max(locked) + allow_pre = floor.is_prerelease or ceiling.is_prerelease + cands = [v for v in _releases(dep) if floor <= v <= ceiling and (allow_pre or not v.is_prerelease)] + if not cands: + sys.exit(f'no releases of {dep} between {floor} and {ceiling}') + + if not _passes(args.package, dep, cands[-1], args.python): + print( + f'\nERROR: {dep}=={cands[-1]} (current uv.lock version) also fails.\n' + f'Fix the broken test on locked deps first (`uv run pytest packages/{args.package}/tests`), ' + 'then re-run bin/find_min_dep_version.', + ) + return 1 + + lo, hi = 0, len(cands) - 1 + while lo < hi: + mid = (lo + hi) // 2 + if _passes(args.package, dep, cands[mid], args.python): + hi = mid + else: + lo = mid + 1 + + best = cands[lo] + toml_rel = f'packages/{args.package}/pyproject.toml' + print(f'\nRESULT: {args.package} requires {dep}>={best} (currently declared >={floor})') + + if best == floor: + print( + f'Floor {dep}>={floor} already passes in isolation. If `tests-minimum-deps` failed in CI, ' + f'another direct dependency of {args.package} (or core `genkit`) is the culprit—check ' + 'the downgraded package list in the CI log and run bin/find_min_dep_version on that dep.', + ) + return 0 + + if args.apply: + _apply_floor(args.package, dep, best) + print( + f'APPLIED: updated {toml_rel} to {dep}>={best} and refreshed uv.lock.\n' + 'Next: run `python3 scripts/check_consistency.py` and commit both files.', + ) + else: + print( + f'\nNext steps to turn `tests-minimum-deps` green:\n' + f' 1. Bump `{dep}>={floor}` -> `{dep}>={best}` in {toml_rel} (keep any `=1.60.0`, `uv.lock` has `1.90.0`, and your PR calls a field added in `1.68.0`—regular tests pass, `tests-minimum-deps` fails. Run `bin/find_min_dep_version` locally with `--apply` to find the exact cutoff, rewrite `pyproject.toml`, and refresh `uv.lock`: + + ```bash + bin/find_min_dep_version genkit-openai openai --apply + # => openai==1.64.0: FAIL (3 failed, 486 passed) + # openai==1.68.0: PASS (489 passed) + # RESULT: genkit-openai requires openai>=1.68.0 (currently declared >=1.60.0) + # APPLIED: updated packages/genkit-openai/pyproject.toml to openai>=1.68.0 and refreshed uv.lock. + ``` + +- **Shortcut when `find_min_dep_version` is slow** (e.g., `boto3` has hundreds of releases between the floor and `uv.lock`, or a big suite takes minutes per step): set the floor straight to the version already in `uv.lock` (`>=1.90.0`). Overshooting fails cleanly at `pip install` time if a user pins an older version, whereas leaving the floor too low lets incompatible versions install and crash at runtime. + +Don't bump floors just because a newer version is out. Only bump on purpose when: + +- **Dropping support:** do it in a Genkit minor release and note it in the release notes. +- **Reachable CVE:** our code path hits the vulnerable code. Comment the reason next to the floor. + +## Workspace-only deps + +- **Dev and lint groups (root `pyproject.toml`):** cap at the next major. They never ship; caps only bound `uv lock --upgrade`. +- **Tests and samples:** declare every package you import. Don't rely on transitive pulls. Samples are workspace members, so keep their lists minimal. + +## Lockfile updates + +Don't run `uv lock --upgrade` in feature PRs—it moves every uncapped dep at once and hides what broke. + +- **Weekly minor/patch PR (`py-minor-and-patch`):** one grouped Dependabot PR after a 7-day cooldown. CI enforces that this PR only touches `uv.lock` (never `packages/*/pyproject.toml`), so if checks are green you can merge immediately. If red, fix our code rather than adding a cap. +- **Security alerts:** Dependabot security PRs bypass cooldown and grouping. To clear a batch manually: + + ```bash + # 1. Audit locked packages + uv export --frozen --all-packages --all-groups --no-hashes --no-emit-workspace -o /tmp/req.txt + uvx pip-audit -r /tmp/req.txt --no-deps --disable-pip + + # 2. Upgrade only the flagged packages within current bounds + uv lock --upgrade-package urllib3 --upgrade-package cryptography + ``` + + If a package won't budge, find what holds it back with `uv tree --invert --package ` and upgrade that too. diff --git a/pyproject.toml b/pyproject.toml index dc549eef4..9070c6791 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,7 +44,8 @@ version = "0.1.0" [dependency-groups] # Dev and lint groups are never published, so they cap at the next major. # That keeps a blanket `uv lock --upgrade` from jumping a tool's major. -# Published package bounds are validated by scripts/check_consistency.py. +# Published packages under packages/ keep floor-only bounds; see +# docs/dependencies.md. dev = [ "nox-uv>=0.2.2,<1", "numpy>=2.0,<3", # generate_loop_test.py diff --git a/scripts/check_consistency.py b/scripts/check_consistency.py index 125707122..724050c9e 100755 --- a/scripts/check_consistency.py +++ b/scripts/check_consistency.py @@ -49,6 +49,7 @@ # (2) contract: users write code or files against it and hand them to genkit. # Everything else is an internal implementation detail and stays floor-only, so # users can take upstream fixes without waiting on a genkit release. +# See docs/dependencies.md. REQUIRED_CAPS: dict[str, str] = { # (1) Integration targets. 'anthropic': 'integration target: genkit-anthropic', From e49383e7b34376718fe12c648db73a9261d1628e Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 19 Nov 2026 10:51:39 -0600 Subject: [PATCH 2/4] docs(py): say published packages cap integration targets, not floor-only The root comment said published packages keep floor-only bounds, but check_consistency.py requires caps on REQUIRED_CAPS / SCOPED_CAPS deps. --- pyproject.toml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9070c6791..60df16232 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,8 +44,9 @@ version = "0.1.0" [dependency-groups] # Dev and lint groups are never published, so they cap at the next major. # That keeps a blanket `uv lock --upgrade` from jumping a tool's major. -# Published packages under packages/ keep floor-only bounds; see -# docs/dependencies.md. +# Published packages under packages/ cap only integration targets and +# contracts (REQUIRED_CAPS / SCOPED_CAPS in scripts/check_consistency.py); +# everything else is floor-only. See docs/dependencies.md. dev = [ "nox-uv>=0.2.2,<1", "numpy>=2.0,<3", # generate_loop_test.py From 0e4aef74cc57ca4b237d7de47bd572ce87876fb3 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 19 Nov 2026 12:44:17 -0600 Subject: [PATCH 3/4] fix(py): find_min_dep_version installs extras and moves otel api/sdk together Two bugs surfaced re-deriving #154's floors with this script: - Test envs skipped optional extras, so genkit-google-cloud's firestore tests failed even at uv.lock versions and the search aborted. - opentelemetry-sdk pins opentelemetry-api with ==, so bisecting api alone paired it with the locked sdk and returned 1.45.0 instead of 1.39.0. --- bin/find_min_dep_version | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/bin/find_min_dep_version b/bin/find_min_dep_version index 2a731ddf4..315b20bf2 100755 --- a/bin/find_min_dep_version +++ b/bin/find_min_dep_version @@ -48,6 +48,12 @@ from packaging.version import InvalidVersion, Version PY_DIR = Path(__file__).resolve().parents[1] +# Released together with exact `==` pins on each other; test them at the same version. +LOCKSTEP = { + 'opentelemetry-api': ('opentelemetry-sdk',), + 'opentelemetry-sdk': ('opentelemetry-api',), +} + def _toml_path(package: str) -> Path: path = PY_DIR / 'packages' / package / 'pyproject.toml' @@ -121,10 +127,11 @@ def _releases(dep: str) -> list[Version]: def _passes(package: str, dep: str, version: Version, python: str | None) -> bool: - cmd = ['uv', 'run', '-q', '--isolated', '--directory', str(PY_DIR), '--package', package] + cmd = ['uv', 'run', '-q', '--isolated', '--all-extras', '--directory', str(PY_DIR), '--package', package] if python: cmd += ['--python', python] - for extra in (f'{dep}=={version}', 'pytest', 'pytest-asyncio', 'pytest-mock', 'psutil'): + pins = [f'{d}=={version}' for d in (dep, *LOCKSTEP.get(dep, ()))] + for extra in (*pins, 'pytest', 'pytest-asyncio', 'pytest-mock', 'psutil'): cmd += ['--with', extra] cmd += ['pytest', '-q', '-p', 'no:cacheprovider', f'packages/{package}/tests'] env = {**os.environ, 'PYTEST_ADDOPTS': '-o addopts='} From 437eee07fd46cc9a17b5a175e54b0e3e232cc59b Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 30 Nov 2026 22:11:28 +0000 Subject: [PATCH 4/4] ci(py): drop find_min_dep_version; print self-contained failure prompt and add just test-min-deps --- .github/workflows/python.yml | 133 +++++++++++++++++---- bin/find_min_dep_version | 216 ----------------------------------- docs/dependencies.md | 24 ++-- justfile | 13 +++ 4 files changed, 134 insertions(+), 252 deletions(-) delete mode 100755 bin/find_min_dep_version diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index e54478561..d5746a4c6 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -217,10 +217,10 @@ jobs: # Floors in packages/*/pyproject.toml are what users resolve against, but the # tests job only runs uv.lock (newest). This job resolves every direct dep at - # its declared floor. If it fails, the PR started using a newer API: run - # `bin/find_min_dep_version ` and raise the floor in the same PR. + # its declared floor so a PR can't silently require an API newer than its + # declared '>=' bound. tests-minimum-deps: - name: Tests (minimum pyproject.toml versions, Python 3.10) + name: Tests (oldest supported deps, Python 3.10) runs-on: ubuntu-latest timeout-minutes: 20 permissions: @@ -243,6 +243,7 @@ jobs: - name: Resolve direct deps at their floors run: | + cp uv.lock /tmp/uv.lock.before uv lock --resolution lowest-direct echo "=== Direct deps downgraded from uv.lock -> declared floors ===" git diff -U1 uv.lock | grep -E '^[ +-](name|version) = ' || echo 'uv.lock already at floors' @@ -254,28 +255,112 @@ jobs: run: ./bin/generate_schema_typing --ci - name: Run tests - run: uv run --no-sync --python 3.10 pytest - - - name: Print self-triage guide on failure - if: failure() run: | - cat <<'EOF' | tee -a "$GITHUB_STEP_SUMMARY" - ### `tests-minimum-deps` failed — how to fix - - This job tests `packages/*/pyproject.toml` at their minimum `>=` versions (`uv lock --resolution lowest-direct`). If regular `tests` passed and this job failed, a package calls an API newer than its declared floor. - - 1. **Find the failing package & dep** from the pytest traceback above (e.g. `packages/genkit-openai/tests/...` -> package `genkit-openai`, dep `openai`; check the `Resolve direct deps` step above to see which deps moved down). - 2. **Auto-bump the exact minimum passing floor and refresh `uv.lock`:** - ```bash - bin/find_min_dep_version --apply - ``` - *(Shortcut if `find_min_dep_version` has too many releases to search: set the floor in `packages//pyproject.toml` straight to the version in `uv.lock`, then run `uv lock`.)* - 3. **Verify policy & commit** `packages//pyproject.toml` + `uv.lock` (keep existing `=' floor in packages/*/pyproject.toml is too old. Run 'bin/find_min_dep_version --apply' locally (see step log / summary for full steps and docs/dependencies.md)." + set +e + set -o pipefail + uv run --no-sync --python 3.10 pytest | tee /tmp/min-deps.log + status=$? + if [[ "$status" -ne 0 ]]; then + python3 - <<'PY' + import os, pathlib, re + + def parse_lock(path: pathlib.Path) -> dict[str, str]: + out: dict[str, str] = {} + for m in re.finditer(r'name = "([^"]+)"\nversion = "([^"]+)"', path.read_text()): + out[m.group(1).lower().replace('_', '-')] = m.group(2) + return out + + before = parse_lock(pathlib.Path('/tmp/uv.lock.before')) + after = parse_lock(pathlib.Path('uv.lock')) + downgraded = {k: (after[k], before[k]) for k in after if k in before and after[k] != before[k]} + + log_lines = pathlib.Path('/tmp/min-deps.log').read_text(errors='replace').splitlines() + failures = [ln.strip() for ln in log_lines if re.match(r'^(FAILED|ERROR)\s+\S+', ln.strip())] + failed_pkgs = sorted({m.group(1) for ln in failures if (m := re.search(r'packages/([^/]+)/', ln))}) + + def declared_deps(pkg: str) -> list[str]: + text = (pathlib.Path('packages') / pkg / 'pyproject.toml').read_text() + deps: list[str] = [] + for m in re.finditer(r'"([A-Za-z0-9][A-Za-z0-9._-]*)(?:\[[^\]]*\])?\s*(?:>=|==|~=)', text): + name = m.group(1).lower().replace('_', '-') + if not name.startswith('genkit') and name not in deps: + deps.append(name) + return deps + + dep_lines: list[str] = [] + target_pkgs = list(failed_pkgs) + if target_pkgs and 'genkit' not in target_pkgs: + target_pkgs.append('genkit') + for pkg in target_pkgs: + for dep in declared_deps(pkg): + if dep in downgraded: + lo, hi = downgraded[dep] + dep_lines.append(f'- packages/{pkg}/pyproject.toml: {dep} {lo} (tested) vs {hi} (uv.lock)') + if not dep_lines: + for pkg_toml in sorted(pathlib.Path('packages').glob('*/pyproject.toml')): + pkg = pkg_toml.parent.name + for dep in declared_deps(pkg): + if dep in downgraded: + lo, hi = downgraded[dep] + dep_lines.append(f'- packages/{pkg}/pyproject.toml: {dep} {lo} (tested) vs {hi} (uv.lock)') + + verify_targets = ' '.join(f'packages/{p}/tests' for p in failed_pkgs) or 'packages/' + shown_failures = [f'- {ln}' for ln in failures[:10]] + if len(failures) > 10: + shown_failures.append(f'- ... and {len(failures) - 10} more') + if not shown_failures: + shown_failures = ['- (see pytest output above)'] + + prompt = '\n'.join([ + 'Fix the `tests-minimum-deps` CI failure on this branch.', + '', + 'Regular tests pass on uv.lock, but tests failed when direct dependencies', + 'were resolved to their oldest declared `>=` versions in pyproject.toml.', + '', + 'Failing tests:', + *shown_failures, + '', + 'Downgraded dependencies in the failing package(s):', + *(dep_lines or ['- (no direct package deps changed; see uv.lock diff in the Resolve step)']), + '', + 'What to do:', + '1. Inspect the failing test(s) and traceback. First check whether a small', + ' backwards-compatible code change can keep the current minimum version', + ' working; prefer that over raising the minimum when it is clean.', + '2. If the newer API/behavior is genuinely required, find the lowest', + ' release that supports it:', + ' - Check the dependency\'s release notes/changelog for the missing API', + ' or fix (and probe candidate versions if the cutoff isn\'t clear).', + ' - Do NOT blindly jump to the uv.lock version for shared deps', + ' (pydantic, anyio, httpx, fastapi, opentelemetry-*). For leaf', + ' provider SDKs (openai, anthropic, google-genai, ollama), finding the', + ' exact cutoff is preferred, or bumping to uv.lock if unclear.', + '3. Update the `>=` minimum in the pyproject.toml above (keep any `<`', + ' upper bound intact; see docs/dependencies.md for bounds policy).', + '4. Verify locally and refresh the lockfile:', + f' just test-min-deps {verify_targets}', + ' uv lock && just check', + '5. Confirm uv.lock is not downgraded, then summarize what changed and why.', + ]) + + print('\n' + '=' * 72) + print('TESTS FAILED ON OLDEST SUPPORTED DEPENDENCIES') + print('Copy-paste everything between the lines below into your coding agent:') + print('-' * 72) + print(prompt) + print('-' * 72) + print('=' * 72) + + summary_path = os.environ.get('GITHUB_STEP_SUMMARY') + if summary_path: + with open(summary_path, 'a', encoding='utf-8') as f: + f.write('### `tests-minimum-deps` failed\n\nCopy-paste into your coding agent:\n\n```text\n') + f.write(prompt) + f.write('\n```\n') + PY + echo "::error title=tests-minimum-deps failed::Tests failed on oldest declared '>=' dependency versions. Copy-paste the prompt at the bottom of the Run tests log into your coding agent." + fi + exit "$status" build: name: Build Distributions diff --git a/bin/find_min_dep_version b/bin/find_min_dep_version deleted file mode 100755 index 315b20bf2..000000000 --- a/bin/find_min_dep_version +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env -S uv run --script -# /// script -# requires-python = ">=3.11" -# dependencies = ["certifi", "packaging"] -# /// -# Copyright 2026 Google LLC -# -# Licensed 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. -# -# SPDX-License-Identifier: Apache-2.0 -# ruff: noqa: T201, S603, S607 - -"""Find (and optionally apply) the lowest passing version of a dependency. - -Use when the `tests-minimum-deps` CI job fails on a PR: it binary-searches PyPI -releases between the declared floor in `packages//pyproject.toml` and -the version in `uv.lock`, running `packages//tests` in an isolated env -at each step. - - bin/find_min_dep_version genkit-openai openai --apply -""" - -from __future__ import annotations - -import argparse -import json -import os -import re -import ssl -import subprocess -import sys -import tomllib -import urllib.request -from pathlib import Path - -import certifi -from packaging.version import InvalidVersion, Version - -PY_DIR = Path(__file__).resolve().parents[1] - -# Released together with exact `==` pins on each other; test them at the same version. -LOCKSTEP = { - 'opentelemetry-api': ('opentelemetry-sdk',), - 'opentelemetry-sdk': ('opentelemetry-api',), -} - - -def _toml_path(package: str) -> Path: - path = PY_DIR / 'packages' / package / 'pyproject.toml' - if not path.exists(): - available = sorted(p.parent.name for p in (PY_DIR / 'packages').glob('*/pyproject.toml')) - sys.exit(f"unknown package '{package}'. Available: {', '.join(available)}") - return path - - -def _all_specs(data: dict) -> list[str]: - proj = data.get('project', {}) - specs = list(proj.get('dependencies', [])) - for extra_specs in proj.get('optional-dependencies', {}).values(): - specs.extend(extra_specs) - return specs - - -def _declared_floor(package: str, dep: str) -> Version: - data = tomllib.loads(_toml_path(package).read_text()) - found_deps: list[str] = [] - for spec in _all_specs(data): - m = re.match(r'([A-Za-z0-9._-]+)(?:\[[^\]]*\])?\s*([^;]*)', spec) - if not m: - continue - name = m.group(1).lower().replace('_', '-') - found_deps.append(name) - if name == dep: - floor = re.search(r'>=\s*([^,\s]+)', m.group(2)) - if floor: - return Version(floor.group(1)) - sys.exit(f"{package} has no '>=' floor for '{dep}'. Declared deps: {', '.join(sorted(set(found_deps)))}") - - -def _apply_floor(package: str, dep: str, new_floor: Version) -> None: - path = _toml_path(package) - original = path.read_text() - pattern = re.compile( - rf'("(?P[A-Za-z0-9._-]+)(?P\[[^\]]*\])?\s*>=\s*)(?P[^,",;\s]+)', - ) - - def _replace(match: re.Match[str]) -> str: - if match.group('name').lower().replace('_', '-') != dep: - return match.group(0) - return f'{match.group(1)}{new_floor}' - - updated = pattern.sub(_replace, original) - if updated == original: - sys.exit(f'failed to rewrite {dep} floor in {path}') - path.write_text(updated) - subprocess.run(['uv', 'lock'], cwd=PY_DIR, check=True) - - -def _locked_versions(dep: str) -> list[Version]: - text = (PY_DIR / 'uv.lock').read_text() - return [Version(v) for v in re.findall(rf'name = "{re.escape(dep)}"\nversion = "([^"]+)"', text)] - - -def _releases(dep: str) -> list[Version]: - ctx = ssl.create_default_context(cafile=certifi.where()) - with urllib.request.urlopen(f'https://pypi.org/pypi/{dep}/json', timeout=30, context=ctx) as r: - data = json.load(r) - out = [] - for v, files in data['releases'].items(): - try: - pv = Version(v) - except InvalidVersion: - continue - if files and not pv.is_devrelease and not any(f.get('yanked') for f in files): - out.append(pv) - return sorted(out) - - -def _passes(package: str, dep: str, version: Version, python: str | None) -> bool: - cmd = ['uv', 'run', '-q', '--isolated', '--all-extras', '--directory', str(PY_DIR), '--package', package] - if python: - cmd += ['--python', python] - pins = [f'{d}=={version}' for d in (dep, *LOCKSTEP.get(dep, ()))] - for extra in (*pins, 'pytest', 'pytest-asyncio', 'pytest-mock', 'psutil'): - cmd += ['--with', extra] - cmd += ['pytest', '-q', '-p', 'no:cacheprovider', f'packages/{package}/tests'] - env = {**os.environ, 'PYTEST_ADDOPTS': '-o addopts='} - proc = subprocess.run(cmd, capture_output=True, text=True, env=env, check=False) - last = (proc.stdout.strip().splitlines() or proc.stderr.strip().splitlines() or ['?'])[-1] - print(f'{dep}=={version}: {"PASS" if proc.returncode == 0 else "FAIL"} ({last[:100]})', flush=True) - return proc.returncode == 0 - - -def main() -> int: - """Run the floor search, print actionable next steps, or rewrite pyproject.toml + uv.lock with --apply.""" - parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('package', help='workspace package dir under packages/, e.g. genkit-openai') - parser.add_argument('dep', help='third-party dependency name, e.g. openai') - parser.add_argument('--python', help='interpreter for test envs (default: uv picks; CI uses 3.10)') - parser.add_argument( - '--apply', - action='store_true', - help='rewrite packages//pyproject.toml to the found floor and update uv.lock', - ) - args = parser.parse_args() - dep = args.dep.lower().replace('_', '-') - - floor = _declared_floor(args.package, dep) - locked = _locked_versions(dep) - if not locked: - sys.exit(f'{dep} is not in uv.lock') - ceiling = max(locked) - allow_pre = floor.is_prerelease or ceiling.is_prerelease - cands = [v for v in _releases(dep) if floor <= v <= ceiling and (allow_pre or not v.is_prerelease)] - if not cands: - sys.exit(f'no releases of {dep} between {floor} and {ceiling}') - - if not _passes(args.package, dep, cands[-1], args.python): - print( - f'\nERROR: {dep}=={cands[-1]} (current uv.lock version) also fails.\n' - f'Fix the broken test on locked deps first (`uv run pytest packages/{args.package}/tests`), ' - 'then re-run bin/find_min_dep_version.', - ) - return 1 - - lo, hi = 0, len(cands) - 1 - while lo < hi: - mid = (lo + hi) // 2 - if _passes(args.package, dep, cands[mid], args.python): - hi = mid - else: - lo = mid + 1 - - best = cands[lo] - toml_rel = f'packages/{args.package}/pyproject.toml' - print(f'\nRESULT: {args.package} requires {dep}>={best} (currently declared >={floor})') - - if best == floor: - print( - f'Floor {dep}>={floor} already passes in isolation. If `tests-minimum-deps` failed in CI, ' - f'another direct dependency of {args.package} (or core `genkit`) is the culprit—check ' - 'the downgraded package list in the CI log and run bin/find_min_dep_version on that dep.', - ) - return 0 - - if args.apply: - _apply_floor(args.package, dep, best) - print( - f'APPLIED: updated {toml_rel} to {dep}>={best} and refreshed uv.lock.\n' - 'Next: run `python3 scripts/check_consistency.py` and commit both files.', - ) - else: - print( - f'\nNext steps to turn `tests-minimum-deps` green:\n' - f' 1. Bump `{dep}>={floor}` -> `{dep}>={best}` in {toml_rel} (keep any `=1.60.0`, `uv.lock` has `1.90.0`, and your PR calls a field added in `1.68.0`—regular tests pass, `tests-minimum-deps` fails. Run `bin/find_min_dep_version` locally with `--apply` to find the exact cutoff, rewrite `pyproject.toml`, and refresh `uv.lock`: - - ```bash - bin/find_min_dep_version genkit-openai openai --apply - # => openai==1.64.0: FAIL (3 failed, 486 passed) - # openai==1.68.0: PASS (489 passed) - # RESULT: genkit-openai requires openai>=1.68.0 (currently declared >=1.60.0) - # APPLIED: updated packages/genkit-openai/pyproject.toml to openai>=1.68.0 and refreshed uv.lock. - ``` - -- **Shortcut when `find_min_dep_version` is slow** (e.g., `boto3` has hundreds of releases between the floor and `uv.lock`, or a big suite takes minutes per step): set the floor straight to the version already in `uv.lock` (`>=1.90.0`). Overshooting fails cleanly at `pip install` time if a user pins an older version, whereas leaving the floor too low lets incompatible versions install and crash at runtime. +- **CI gate:** `tests-minimum-deps` in `python.yml` resolves direct deps at their declared `>=` floors (`uv lock --resolution lowest-direct`) and runs tests on Python 3.10. It runs automatically on every PR. +- **When `tests-minimum-deps` fails on your PR:** regular `tests` passed on `uv.lock` (newest), so the PR relies on an API or fix newer than a declared `>=` floor. The failed CI log prints a self-contained prompt you can copy-paste straight into a coding agent, or follow the same steps by hand: + 1. **Check whether a small code tweak keeps the current floor working.** Prefer keeping compatibility over raising a floor when the fix is simple. + 2. **Otherwise, find the lowest passing release:** check the failing dependency's release notes/changelog for the missing API or fix (and probe candidate versions if the cutoff isn't obvious). + - **Shared deps** (`pydantic`, `anyio`, `httpx`, `fastapi`, `opentelemetry-*`): avoid jumping straight to `uv.lock`, since users often pin these in their apps. + - **Leaf provider SDKs** (`openai`, `anthropic`, `google-genai`, `ollama`): finding the exact cutoff is preferred, or bumping straight to the `uv.lock` version is fine if unclear (overshooting fails cleanly at `pip install` time instead of crashing at runtime). + 3. **Update `>=` in `packages//pyproject.toml`** (keep any `/tests # runs lowest-direct and restores uv.lock on exit + uv lock && just check + ``` Don't bump floors just because a newer version is out. Only bump on purpose when: diff --git a/justfile b/justfile index 0f4bd4aa0..485bd5abf 100644 --- a/justfile +++ b/justfile @@ -54,6 +54,19 @@ fmt: test: uv run --directory "{{ py_dir }}" pytest . +# Run tests at oldest declared pyproject.toml floors (restores uv.lock on exit). +test-min-deps *ARGS: + #!/usr/bin/env bash + set -euo pipefail + cd "{{ py_dir }}" + lock_backup="$(mktemp)" + cp uv.lock "$lock_backup" + restore() { mv "$lock_backup" uv.lock && uv sync --frozen --quiet; } + trap restore EXIT + uv lock --resolution lowest-direct + uv sync --frozen + uv run --no-sync pytest {{ ARGS }} + # Run tests across multiple Python versions (3.10–3.14) with nox. test-nox: uv run --directory "{{ py_dir }}" nox