diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 44c8a0d7..0aed325f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -18,12 +18,10 @@ version: 2 # Policy notes: # 1. Cooldowns satisfy zizmor (`dependabot-cooldown` >= 7d). -# 2. The `uv` group scopes weekly PRs to `minor` + `patch` and suppresses routine -# `version-update:semver-major` PRs via `ignore` (so breaking major jumps that -# require code migrations are handled intentionally rather than turning the -# weekly PR red). Security/CVE updates bypass both `cooldown` and `ignore`, -# opening standalone PRs (including major bumps when required) outside the -# weekly group. +# 2. The `uv` workspace batches `minor` + `patch` into one weekly PR. Majors aren't +# ignored and aren't grouped: each gets its own PR, because each needs its own +# review (cap diff, changelog, contract or not) and one red major shouldn't +# block the others. Security/CVE updates bypass `cooldown` and open standalone PRs. updates: # Maintain dependencies for GitHub Actions - package-ecosystem: "github-actions" @@ -38,6 +36,8 @@ updates: - "*" # Maintain dependencies for Python (uv workspace) + # Majors open one PR per dep instead of being ignored: a green one widens the + # cap, a red one is the migration ticket. See docs/dependencies.md. - package-ecosystem: "uv" directory: "/" schedule: @@ -51,7 +51,16 @@ updates: update-types: - "minor" - "patch" - ignore: - - dependency-name: "*" + # Majors open one PR per dep, except families that release in lockstep: + # splitting those would leave each PR unresolvable (sdk 2 needs api 2). + opentelemetry-major: + patterns: + - "opentelemetry-*" + update-types: + - "major" + aws-major: + patterns: + - "boto3" + - "botocore" update-types: - - "version-update:semver-major" + - "major" diff --git a/.github/workflows/python-deps-canary.yml b/.github/workflows/python-deps-canary.yml new file mode 100644 index 00000000..6d312fa6 --- /dev/null +++ b/.github/workflows/python-deps-canary.yml @@ -0,0 +1,131 @@ +# 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 + +# Tests what a fresh `pip install genkit` resolves today: every dep at the +# newest version our bounds allow, not what uv.lock pins. Catches minor-version +# breaks (pydantic 2.14, google-genai 2.34) and uncapped majors before users +# report them. Floors are checked on every PR by the `lowest-deps` job in +# python.yml. Scheduled and manual only, never a PR gate: failures come from +# upstream releases, not from the PR. See docs/dependencies.md. +# +# Scheduled runs on the default branch keep one open `py-deps-canary` issue: +# opened on the first failure, commented on while it stays red, closed on green. +name: Python Dependency Canary + +on: + schedule: + - cron: "0 14 * * *" # Daily 14:00 UTC. + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: true + +jobs: + canary: + name: Tests (newest allowed deps, Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + permissions: + contents: read + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.14"] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Install uv and setup Python + uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5 + with: + enable-cache: false + python-version: ${{ matrix.python-version }} + + - name: Re-resolve to the newest allowed versions + run: | + uv lock --upgrade + # List every package whose version moved past uv.lock. + git diff -U1 uv.lock | grep -E '^[ +-](name|version) = ' || echo 'uv.lock already at newest' + + - name: Install dependencies + env: + PY_VER: ${{ matrix.python-version }} + run: uv sync --frozen --python "$PY_VER" + + - name: Generate schema typing + run: ./bin/generate_schema_typing --ci + + - name: Run tests + env: + PY_VER: ${{ matrix.python-version }} + run: uv run --no-sync --python "$PY_VER" pytest + + # Runs once per workflow run, after the whole matrix, so two failing Python + # versions still produce one issue update. + report: + name: Update tracking issue + needs: canary + if: >- + ${{ !cancelled() && github.event_name == 'schedule' && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - name: Open, comment on, or close the py-deps-canary issue + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RESULT: ${{ needs.canary.result }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + label=py-deps-canary + issue=$(gh issue list --label "$label" --state open --limit 1 --json number --jq '.[0].number // empty') + + if [[ "$RESULT" == "success" ]]; then + if [[ -n "$issue" ]]; then + gh issue close "$issue" --comment "Green again on the newest allowed deps: $RUN_URL" + fi + exit 0 + fi + if [[ "$RESULT" != "failure" ]]; then + exit 0 + fi + + if [[ -n "$issue" ]]; then + gh issue comment "$issue" --body "Still failing: $RUN_URL" + exit 0 + fi + + gh label create "$label" --force --color D93F0B \ + --description "Python tests fail on the newest deps our bounds allow" + gh issue create --label "$label" \ + --title "Python dependency canary: tests fail on newest allowed deps" \ + --body-file - < ` and raise the floor in the same PR. + lowest-deps: + name: Tests (lowest declared deps, 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 + + - 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 + build: name: Build Distributions runs-on: ubuntu-latest @@ -206,7 +244,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, lowest-deps] steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: @@ -263,16 +301,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, lowest-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.lowest-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 b85247c7..37bf01bb 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_floor b/bin/find_floor new file mode 100755 index 00000000..867f50c1 --- /dev/null +++ b/bin/find_floor @@ -0,0 +1,136 @@ +#!/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 the lowest version of a dependency that passes a package's tests. + +Use it when the `lowest-deps` CI job fails: it binary-searches PyPI releases +between the declared floor and the version in uv.lock, running the package's +tests in an isolated env at each step. + + bin/find_floor genkit-openai openai + # => openai==1.64.0: FAIL (3 failed, 486 passed) + # openai==1.68.0: PASS (489 passed) + # genkit-openai: openai lowest passing 1.68.0 (declared floor 1.60.0) + +Assumes pass/fail is monotonic across versions, which holds for "we started +using a newer API". Re-run the lowest-deps job after bumping the floor. +""" + +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 _declared_floor(package: str, dep: str) -> Version: + data = tomllib.loads((PY_DIR / 'packages' / package / 'pyproject.toml').read_text()) + for spec in data['project'].get('dependencies', []): + m = re.match(r'([A-Za-z0-9._-]+)(?:\[[^\]]*\])?\s*([^;]*)', spec) + if m and m.group(1).lower().replace('_', '-') == 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}') + + +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 and print the lowest passing version.""" + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('package', help='workspace package, e.g. genkit-openai') + parser.add_argument('dep', help='third-party dependency, e.g. openai') + parser.add_argument('--python', help='interpreter for test envs (default: uv picks)') + 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'{dep}=={cands[-1]} (locked) fails too; fix the tests before searching for a floor') + 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 + print(f'{args.package}: {dep} lowest passing {cands[lo]} (declared floor {floor})') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/docs/dependencies.md b/docs/dependencies.md new file mode 100644 index 00000000..851f4a7f --- /dev/null +++ b/docs/dependencies.md @@ -0,0 +1,68 @@ +# Python Dependency Policy + +CI installs from `uv.lock` (`uv sync --frozen`). Users don't get the lockfile; they resolve the ranges in `packages/*/pyproject.toml`. This page covers both. + +## Upper bounds (caps) + +Cap a published dependency at the next major (` openai==1.64.0: FAIL (3 failed, 486 passed) + # openai==1.68.0: PASS (489 passed) + # genkit-openai: openai lowest passing 1.68.0 (declared floor 1.60.0) + ``` + + If that's too slow, use the locked version. A high floor fails loudly at install time; a low floor fails 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 & CI + +Don't run `uv lock --upgrade` in feature PRs—it moves every uncapped dep at once and hides what broke. + +- **Weekly minor/patch PR:** one grouped Dependabot PR after a 7-day cooldown. Merge if green. If red, fix our code rather than adding a cap. +- **Weekly major PRs:** one PR per dep so a broken major doesn't block the rest. Lockstep families (`opentelemetry-*`, `boto3` + `botocore`) stay grouped so they can resolve. + - **Floor-only dep:** users already resolve the new major. Green: merge same day. Red: users are already broken—fix immediately. + - **Capped dep:** widens the cap (`<3` -> `<4`). Check `packages/*/pyproject.toml`, skim the changelog for behavior mocked tests miss (exceptions, transport, defaults), merge, and release so users get the wider range. + - **Contract dep (`pydantic`, `dotpromptz`):** widening affects user code. Merge deliberately with a release note. + - **Red capped PR:** leave it open as the migration ticket; the cap protects users meanwhile. +- **Daily canary (`python-deps-canary.yml`):** tests the newest versions our bounds allow—what `pip install` gets today. Not a PR gate since upstream releases trigger it. Opens/updates one `py-deps-canary` issue while red and closes it when green; fix the code or add `!=x.y.z`, and cut a patch release if users are hit. +- **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 dc549eef..9070c679 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 12570712..724050c9 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',