diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index fb173a98..d5746a4c 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,153 @@ 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 so a PR can't silently require an API newer than its + # declared '>=' bound. + tests-minimum-deps: + name: Tests (oldest supported 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: | + 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' + + - name: Install dependencies + run: uv sync --frozen --python 3.10 + + - name: Generate schema typing + run: ./bin/generate_schema_typing --ci + + - name: Run tests + run: | + 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 runs-on: ubuntu-latest @@ -206,7 +369,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 +426,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 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/docs/dependencies.md b/docs/dependencies.md new file mode 100644 index 00000000..a04cb1d7 --- /dev/null +++ b/docs/dependencies.md @@ -0,0 +1,63 @@ +# 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 (`=` 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: + +- **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/justfile b/justfile index 0f4bd4aa..485bd5ab 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 diff --git a/pyproject.toml b/pyproject.toml index dc549eef..60df1623 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,7 +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 package bounds are validated by scripts/check_consistency.py. +# 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 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',