pydantic-ai/.github/workflows/ci.yml

2775 lines
140 KiB
YAML

# description: Runs quality checks and the test matrix on pull requests, pushes to main and tags, and the merge queue, and publishes tagged releases to PyPI.
name: CI
on:
push:
branches:
- main
tags:
- "**"
# Moved by `clai2-bleeding.yml` for every CLAI change on `main`; not a release to build or publish.
- "!clai2-bleeding"
pull_request: {}
# The merge queue: a pull request reaches `main` only through a merge group that passed this
# workflow's full test matrix. A `pull_request` run skips the matrix legs that only repeat
# another leg's checks (see `pull_request` in the test jobs' matrices); every leg that
# collects coverage or carries a check no other leg runs stays on it, so coverage and the
# coverage gate come out identical under both events. `.github/scripts/test_ci_matrix.py`
# checks that.
merge_group:
types: [checks_requested]
env:
COLUMNS: 150
UV_PYTHON: 3.12
UV_FROZEN: "1"
# Ubuntu's system interpreters are older and slower than uv's optimized managed builds.
UV_PYTHON_PREFERENCE: only-managed
# Authenticate the Git fetches uv makes for Git-sourced dependencies. Anonymous HTTPS clones are
# capped per client IP, and runners that share an egress pool exhaust that budget as a matrix
# fans out, at which point GitHub answers with a credential challenge that surfaces as
# `could not read Username for 'https://github.com'` and fails the install before any test runs.
# `GIT_CONFIG_*` applies to every `uv sync` and implicit `uv run` sync without writing credentials
# into the checkout, so `actions/checkout`'s `persist-credentials: false` still holds.
GIT_CONFIG_COUNT: "1"
GIT_CONFIG_KEY_0: url.https://x-access-token:${{ github.token }}@github.com/.insteadOf
GIT_CONFIG_VALUE_0: https://github.com/
permissions:
contents: read
concurrency:
# PRs: one group per ref so newer pushes cancel superseded in-flight runs.
# push/tag/merge group: one group per run_id so main, tag and merge-queue runs never share a
# group (avoids GitHub's pending-run cancellation between distinct main commits, and never
# cancels a merge group the queue is waiting on).
group: ci-${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
warm-douwebot-tools:
name: warm douwebot fallback tools
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: ./.github/actions/setup-douwebot-tools
with:
save-cache: 'true'
classify:
name: classify changes
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
permissions:
contents: read
pull-requests: read
outputs:
content_only: ${{ steps.classify.outputs.content_only }}
docs_changed: ${{ steps.classify.outputs.docs_changed }}
clai2_only: ${{ steps.classify.outputs.clai2_only }}
clai2_changed: ${{ steps.classify.outputs.clai2_changed }}
clai2_web_changed: ${{ steps.classify.outputs.clai2_web_changed }}
harness_only: ${{ steps.classify.outputs.harness_only }}
pyright_changed: ${{ steps.classify.outputs.pyright_changed }}
steps:
- name: Classify pull request changes
id: classify
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
# Keep classification inline so this token-bearing job never executes PR-authored files.
run_all_checks() {
echo 'content_only=false' >> "$GITHUB_OUTPUT"
echo 'docs_changed=false' >> "$GITHUB_OUTPUT"
echo 'clai2_only=false' >> "$GITHUB_OUTPUT"
echo 'clai2_changed=true' >> "$GITHUB_OUTPUT"
echo 'clai2_web_changed=true' >> "$GITHUB_OUTPUT"
echo 'harness_only=false' >> "$GITHUB_OUTPUT"
echo 'pyright_changed=true' >> "$GITHUB_OUTPUT"
}
if [ "${{ github.event_name }}" != "pull_request" ]; then
run_all_checks
exit 0
fi
if ! total=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq '.changed_files'); then
echo '::warning::Could not read the PR changed-file count; running full CI.'
run_all_checks
exit 0
fi
if ! [[ "$total" =~ ^[0-9]+$ ]]; then
echo "::warning::PR changed-file count is not numeric ($total); running full CI."
run_all_checks
exit 0
fi
if [ "$total" -eq 0 ] || [ "$total" -ge 3000 ]; then
echo "::warning::PR changed-file count is $total; running full CI."
run_all_checks
exit 0
fi
if ! gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files" \
--jq '.[] | [.filename, (.previous_filename // "")] | @tsv' > "$RUNNER_TEMP/changed-files.txt"; then
echo '::warning::Could not list the PR changed files; running full CI.'
run_all_checks
exit 0
fi
mapfile -t changed_files < "$RUNNER_TEMP/changed-files.txt"
if [ "${#changed_files[@]}" -ne "$total" ]; then
echo "::warning::Expected $total changed files, received ${#changed_files[@]}; running full CI."
run_all_checks
exit 0
fi
needs_docs_checks() {
# `test_examples.py` also scans Markdown under the published package directories.
case "$1" in
README.md|clai/README.md|src/pydantic_ai_pax/README.md|src/pydantic_ai_harness/README.md) ;;
docs/*.md|docs/*.mdc|docs/*.png|docs/*.svg|docs/*.ico|docs/*.jpg|docs/*.jpeg|docs/*.gif|docs/*.webp|docs/*.avif) ;;
examples/*.md|pydantic_ai_slim/*.md|pydantic_graph/*.md|pydantic_evals/*.md) ;;
*) return 1 ;;
esac
}
is_non_test_content() {
case "$1" in
tests/*|.github/*|.macroscope/*) return 1 ;;
esac
if needs_docs_checks "$1"; then
return 0
fi
case "$1" in
.agents/*.md|.agents/*.tsv|.claude/*.md|agent_docs/*.md|*/AGENTS.md|*/CLAUDE.md) return 0 ;;
*.md) [[ "$1" != */* ]] ;;
*) return 1 ;;
esac
}
# Nothing outside `pydantic-ai-pax` imports it, so a change confined to these paths cannot
# break another package's suite: it runs only the `pydantic-ai-pax` test cells, and skips
# the jobs that exercise the rest of the workspace. Shared inputs (`pyproject.toml`,
# `uv.lock`, `tests/conftest.py`, ...) are outside them and still run everything.
is_clai2() {
case "$1" in
src/pydantic_ai_pax/*|src/pydantic_clai2/*|tests/pax/*) ;;
*) return 1 ;;
esac
}
# Outside its own suite, only `pydantic-ai-pax` and the gh-aw shim (tested in `quality`, which
# still runs) import `pydantic-ai-harness`; core and its tests merely probe whether it is
# installed. So a change confined to the two packages and content runs the harness and
# CLAI 2 suites -- on every install shape, resolution, and Temporal leg -- and skips the jobs
# that exercise only the rest of the workspace. That includes a `pydantic-ai-pax` change that
# also touches content. The harness `pyproject.toml` stays on the full path: its dependency
# bounds feed the environment every package is tested in.
is_harness() {
case "$1" in
src/pydantic_ai_harness/pyproject.toml) return 1 ;;
src/pydantic_ai_harness/*|tests/harness/*|docs/harness/*) ;;
*) return 1 ;;
esac
}
is_harness_tier() {
is_harness "$1" || is_clai2 "$1" || is_non_test_content "$1"
}
# `test-clai2-clipboard` runs on macOS and Windows runners, so only for a change that reaches
# `pydantic-ai-pax` or the job itself.
is_clai2_input() {
is_clai2 "$1" || [ "$1" = .github/workflows/ci.yml ]
}
# The Linux web job follows its reusable workflow, the action that builds the web UI, and the
# Python environment it syncs.
is_clai2_web_input() {
is_clai2_input "$1" || case "$1" in
.github/workflows/clai2-web.yml|.github/actions/build-clai2-web-ui/*|pyproject.toml|uv.lock) return 0 ;;
*) return 1 ;;
esac
}
is_pyright_input() {
# All Python/stub files conservatively cover Pyright's include and import graph;
# the remaining paths change its command, configuration, dependencies, or this gate.
case "$1" in
*.py|*.pyi|*/py.typed|py.typed|pyproject.toml|*/pyproject.toml|uv.lock|uv.toml|*/uv.toml|pyrightconfig*.json|*/pyrightconfig*.json|Makefile|.github/workflows/ci.yml) ;;
*) return 1 ;;
esac
}
content_only=true
docs_changed=false
clai2_only=true
clai2_changed=false
clai2_web_changed=false
harness_tier=true
pyright_changed=false
for changed_file in "${changed_files[@]}"; do
IFS=$'\t' read -r filename previous_filename <<< "$changed_file"
if ! is_non_test_content "$filename" || \
{ [ -n "$previous_filename" ] && ! is_non_test_content "$previous_filename"; }; then
content_only=false
fi
if needs_docs_checks "$filename" || \
{ [ -n "$previous_filename" ] && needs_docs_checks "$previous_filename"; }; then
docs_changed=true
fi
if ! is_clai2 "$filename" || \
{ [ -n "$previous_filename" ] && ! is_clai2 "$previous_filename"; }; then
clai2_only=false
fi
if is_clai2_input "$filename" || \
{ [ -n "$previous_filename" ] && is_clai2_input "$previous_filename"; }; then
clai2_changed=true
fi
if is_clai2_web_input "$filename" || \
{ [ -n "$previous_filename" ] && is_clai2_web_input "$previous_filename"; }; then
clai2_web_changed=true
fi
if ! is_harness_tier "$filename" || \
{ [ -n "$previous_filename" ] && ! is_harness_tier "$previous_filename"; }; then
harness_tier=false
fi
if is_pyright_input "$filename" || \
{ [ -n "$previous_filename" ] && is_pyright_input "$previous_filename"; }; then
pyright_changed=true
fi
done
echo "content_only=$content_only" >> "$GITHUB_OUTPUT"
echo "docs_changed=$docs_changed" >> "$GITHUB_OUTPUT"
echo "clai2_only=$clai2_only" >> "$GITHUB_OUTPUT"
echo "clai2_changed=$clai2_changed" >> "$GITHUB_OUTPUT"
echo "clai2_web_changed=$clai2_web_changed" >> "$GITHUB_OUTPUT"
# The narrower tiers take precedence, so at most one of the three `*_only` outputs is true.
harness_only=false
if [ "$harness_tier" = true ] && [ "$content_only" = false ] && [ "$clai2_only" = false ]; then
harness_only=true
fi
echo "harness_only=$harness_only" >> "$GITHUB_OUTPUT"
echo "pyright_changed=$pyright_changed" >> "$GITHUB_OUTPUT"
quality:
name: quality checks
needs: classify
if: needs.classify.outputs.content_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
# `pull-requests: read` is for the lock-regeneration guard's PR file listing. Reading
# it works today on `contents: read` alone only because this repo is public; declaring
# it keeps the step working on a private fork or mirror.
permissions:
contents: read
pull-requests: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.13"
enable-cache: true
cache-suffix: lint
- name: Install dependencies
id: install
run: uv sync --all-extras --all-packages --group lint
- name: Test GitHub agentic workflow policy
env:
UV_NO_SYNC: "1"
run: >-
uv run pytest
.github/scripts/test_pydantic_ai_runner.py
.github/scripts/test_workflow_agent.py
.github/scripts/test_review_lifecycle.py
.github/scripts/test_pre_agent_steps_tag_fetch.py
.github/scripts/test_agent_provider_health.py
.github/scripts/test_check_api_compatibility.py
.github/scripts/test_issue_pr_attention_monitor.py
.github/scripts/test_latest_versions_canary_report.py
.github/scripts/test_community_demand.py
.github/scripts/test_triage_telemetry.py
.github/scripts/test_feature_digest.py
.github/scripts/test_agentic_workflow_guard.py
.github/scripts/test_weekly_ce_audit.py
.github/scripts/test_agent_spend_report.py
.github/scripts/test_docs_navigation_workflow.py
.github/scripts/test_protect_github_dir.py
.github/scripts/test_pr_guard.py
.github/scripts/test_lint_exemptions.py
.github/scripts/test_pr_gates.py
.github/scripts/test_douwebot_config_approval.py
.github/scripts/test_douwebot_usage_limit.py
.github/scripts/test_douwebot_opencode_run.py
.github/scripts/test_douwebot_opencode_result.py
.github/scripts/test_pr_review_checks.py
.github/scripts/test_run_pr_review_check.py
.github/scripts/test_publish_pr_review_checks.py
.github/scripts/test_gh_aw_opencode_detect.py
.github/scripts/test_size_label.py
.github/scripts/test_ci_content_classifier.py
.github/scripts/test_gh_aw_engine_pin_bump.py
.github/scripts/test_clai2_web_bundle.py
.github/scripts/test_shard_durations.py
.github/scripts/test_ci_matrix.py
scripts/test_gather_pydantic_ai_review_context.py
- name: Test threat detector telemetry
run: node --test .github/scripts/test_detector_telemetry.cjs .github/scripts/test_workflow_telemetry.cjs
# `make typecheck-changed` narrows Pyright to the files a change reaches, so a wrong
# answer here silently stops type errors reaching a developer's terminal.
# It lives outside `testpaths`, in the job that installs Pyright, because one of its
# tests runs Pyright for real.
- name: Test the incremental typecheck script
env:
UV_NO_SYNC: "1"
run: uv run pytest scripts/test_typecheck_changed.py
# The `complexity` job runs these scripts with only the `lint` group installed, so their tests run here.
- name: Test the cognitive complexity and test waits checks
env:
UV_NO_SYNC: "1"
run: uv run pytest scripts/test_check_complexity.py scripts/test_check_test_waits.py
# `uv run --script` in the smoke test below silently re-locks a stale runner lock, so
# it can't catch one. A change to the runner's dependencies, `pydantic_ai_slim`'s
# included, must refresh it.
- name: Check the gh-aw runner's script lock is up to date
run: >-
uv lock --script .github/scripts/pydantic-ai-runner --check
|| { echo "::error file=.github/scripts/pydantic-ai-runner.lock::Stale gh-aw runner lock; run: uv lock --script .github/scripts/pydantic-ai-runner"; exit 1; }
# Runs the shim through the legacy `uv run --script` runner, which no workflow uses
# (#12796), with no argv, so it reaches the empty-prompt short-circuit without touching
# the network. This catches general shim breakage — a syntax error, a bad import, a
# module the runner lock doesn't carry. The runner installs this checkout's
# `pydantic-ai-slim` and harness, so a `pydantic_ai` symbol missing from the pinned
# engine runtime still imports here; "Import the gh-aw shim on the pinned engine
# runtime" at the end of this job catches that. The shim exits non-zero on an empty
# prompt, so the assertion is on its output, never its status: `|| true` holds
# whether or not the shell has `pipefail` (the default `run` shell here is
# `bash -e`, but `shell: bash` would add it).
- name: Smoke-test the gh-aw shim against the runner's own dependencies
run: |
uv run --script .github/scripts/pydantic-ai-runner 2>&1 | tee /tmp/shim-smoke.log || true
grep -q 'empty prompt' /tmp/shim-smoke.log
# Every check except lock freshness reads the tree alone, so run them on `main`
# too. Two independently-green PRs can still merge into a drifted `main` — the
# classic case being one that bumps the gh-aw compiler while another adds a lock
# at the old version — and without this the drift first surfaces as a red `quality checks`
# on whichever contributor next opens a PR, about workflows they never touched.
- name: Fetch gh-aw compatibility policy
run: >-
curl --fail --silent --show-error --location --retry 3 --retry-all-errors
https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/compat.json
--output /tmp/gh-aw-compat.json
- name: Check agentic workflow policy
env:
UV_NO_SYNC: "1"
run: >-
uv run python .github/scripts/agentic_workflow_guard.py check
--compatibility-file /tmp/gh-aw-compat.json
# Actions runs the `*.lock.yml`, never the `*.md`, so a source edited without
# its recompiled lock is a silent no-op. The checkout is shallow, so feed the
# guard the PR's file list rather than a `git diff` range.
- name: Check agentic workflow locks were regenerated
if: github.event_name == 'pull_request'
env:
UV_NO_SYNC: "1"
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
# `gh pr view --json files` truncates at 100 files, which would silently hide an
# un-recompiled lock on a large PR. Paginate the REST endpoint instead — and since
# that endpoint itself hard-caps at 3,000 files, fail closed when the list comes
# back short rather than let the guard pass on an incomplete changeset.
total=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq '.changed_files')
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files" \
--jq '.[] | {filename, previous_filename, status} | tojson' > /tmp/pr-files.jsonl
# One JSON object per changed file, so this is the count to compare against.
retrieved=$(wc -l < /tmp/pr-files.jsonl | tr -d '[:space:]')
# A renamed file reports only its new path in `filename`; the old path lives in
# `previous_filename`. Without it, renaming a source away from its lock leaves the
# lock orphaned and runnable, and the guard never sees the old source as gone.
jq -r '.filename, (select(.status == "renamed") | .previous_filename)' \
/tmp/pr-files.jsonl > /tmp/changed-files.txt
if [ "$retrieved" -lt "$total" ]; then
echo "::error::Retrieved only $retrieved of $total changed files (the PR files API caps at 3000)." \
"Lock freshness cannot be verified for this PR, so failing closed rather than passing blind."
exit 1
fi
uv run python .github/scripts/agentic_workflow_guard.py check --changed-file-list /tmp/changed-files.txt
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
with:
extra_args: --all-files --verbose
env:
# `complexity` and `test-waits` check only staged changes, and a checkout stages none; the `complexity`
# job runs them.
SKIP: no-commit-to-branch,complexity,test-waits
# pre-commit hooks shell out via `uv run`; without this they would re-sync the venv
# down to the root package and drop the `--all-packages` install above.
UV_NO_SYNC: "1"
# The full Pyright check runs here, not in pre-commit. With `CI` set, `make typecheck-changed`
# hands the whole project to `make typecheck-pyright`, under the `PYRIGHT_TIME_BUDGET` that only
# that script enforces. The check runs whenever the install succeeded, so a failing pre-commit
# hook or policy check does not hide type errors.
#
# A pull request checks with pyright-rs first: a Rust port of pyright's command-line check
# that prints pyright's output and exit code for the same command line and configuration, in
# about a fifth of the time (https://github.com/dsfaccini/pyright-rs). The release is pinned
# by tag and checksum, and used only when it ports the pyright version `uv.lock` installs, so a
# pyright bump is never checked by an older port. When the install or the pyright-rs check
# fails, pyright checks, and its result counts, so a pull request never fails on a pyright-rs
# mistake. A merge group checks with pyright alone, so a wrong pyright-rs pass never reaches
# `main`; a push to `main` checks with pyright too.
- name: Install pyright-rs
id: pyright-rs
if: ${{ !cancelled() && github.event_name == 'pull_request' && steps.install.outcome == 'success' && needs.classify.outputs.pyright_changed == 'true' }}
continue-on-error: true
env:
PYRIGHT_RS_RELEASE: v1.1.414-1
PYRIGHT_RS_SHA256: 8eacc246abfabff2bfc1d2735b756050047471b1468cb29a7ddcf42c56ae3cdc
PYRIGHT_PYTHON_IGNORE_WARNINGS: "1"
UV_NO_SYNC: "1"
run: |
trap 'echo "::warning title=pyright-rs::Installing pyright-rs failed, so pyright checks this run."' ERR
name="pyright-rs-$PYRIGHT_RS_RELEASE-x86_64-unknown-linux-gnu"
curl --fail --silent --show-error --location --retry 3 --retry-all-errors \
--output "$RUNNER_TEMP/$name.tar.gz" \
"https://github.com/dsfaccini/pyright-rs/releases/download/$PYRIGHT_RS_RELEASE/$name.tar.gz"
echo "$PYRIGHT_RS_SHA256 $RUNNER_TEMP/$name.tar.gz" | sha256sum --check --strict
tar -xzf "$RUNNER_TEMP/$name.tar.gz" -C "$RUNNER_TEMP"
ported=$("$RUNNER_TEMP/$name/pyright-rs" --version)
locked=$(uv run pyright --version)
if [ "$ported" != "$locked" ]; then
echo "::notice title=pyright-rs::pyright-rs ports $ported but uv.lock installs $locked, so pyright checks this run."
exit 0
fi
echo "path=$RUNNER_TEMP/$name/pyright-rs" >> "$GITHUB_OUTPUT"
- name: Type-check with pyright-rs
id: pyright-rs-check
if: ${{ !cancelled() && steps.pyright-rs.outputs.path != '' }}
continue-on-error: true
env:
PYRIGHT: ${{ steps.pyright-rs.outputs.path }}
# A failure here only hands the check to pyright and its own budget below, so a slowdown
# fails the pull request only when pyright shows it too. On 2026-11-12 eight runners each
# checked one pull request with both (https://github.com/pydantic/pydantic-ai/actions/runs/43321752660):
# pyright-rs took 35.3 to 47.6 s (median 40.0 s), and pyright 6.0 to 6.6 times as long. 55
# is pyright's 370 s budget divided by the highest of those ratios, so a pyright-rs run that
# points to a pyright run over that budget hands the check to pyright. It is about 1.15x the
# slowest of those pyright-rs runs, and a run 1.5x their median exceeds it.
PYRIGHT_TIME_BUDGET: "55"
UV_NO_SYNC: "1"
run: make typecheck-changed
- name: Type-check with Pyright
if: ${{ !cancelled() && steps.install.outcome == 'success' && needs.classify.outputs.pyright_changed == 'true' && steps.pyright-rs-check.outcome != 'success' }}
env:
# The `Makefile` leaves pyright single-process by default, for laptops where a worker
# per core swaps. A runner has the memory, and this step is the longest in the job, so
# CI opts back in. Each worker is its own Node process holding most of the project's
# types, and empties its whole type cache whenever its heap passes 90% of Node's default
# limit (about 4 GB here), then re-evaluates everything it still needs. Four workers at
# that limit emptied it 7 to 33 times a run by 2026-10-28; three workers with a 6 GB heap
# never do and still fit in the runner's 16 GB, which took 9 to 14% (18 to 32 s) off
# every one of six paired runs on the same runner (see #8182).
PYRIGHT_THREADS: "3"
NODE_OPTIONS: --max-old-space-size=6144
# Fail a passing pyright run that outlasts this many seconds, so a change that makes
# pyright itself slow fails its own PR instead of `main`. #8077 made pyright slow and
# nothing caught it (see #8177): pyright ran 328 to 490 s over the five `main` runs
# between those two. The budget was 110 (1.1x the p99 of 60 main runs, derived in
# https://github.com/pydantic/pydantic-ai/issues/8182#issuecomment-5575016259), but by
# 2026-09-23 pyright ran 66 to 111 s on the same day's main runs (runner variance alone
# spans about 30 s); the pyright 1.1.414 bump (#8690) and type-checking docs examples (#8646)
# probably lifted the baseline to about 105 to 111 s, and a 110.6 s passing run failed main;
# 150 leaves room for that variance while still failing a regression like #8077's 328 to
# 490 s. Type-checking `pydantic-ai-harness` and `pydantic-ai-pax` took a passing run to
# 156 s, so 200 kept the same headroom. By 2026-10-16 the step ran 117 to 206 s over 98 `main`
# runs (median 184 s, p90 197 s) and failed four of them; 260 is about 1.25x that maximum and
# still fails a regression like #8077's.
# Only pull requests enforce it: that is where a slowdown has to fail, and by 2026-10-26 runner
# variance alone spread 18 merge-queue and `main` runs over 149 to 279 s, so enforcing it there
# bounced queued PRs and reddened `main` without catching anything their PR had not.
# On 2026-10-27 the step ran 127 to 292 s over 375 pull request runs (median 236 s, p90 259 s),
# and 23 of them failed only on the budget, with zero type errors, on diffs as small as a
# docstring; 320 is about 1.1x that maximum and still fails a regression like #8077's.
# After #11806 set the worker count and heap above, 181 passing runs from 2026-10-29 to 30
# (146 pull request, 20 merge queue, 15 `main`) ran 145 to 288 s (median 231 s, p95 254 s,
# p99 274 s); 280 keeps about 10% above that p95, and 1 of the 146 pull request runs
# exceeded it.
# From 2026-11-09 to 12 the step ran 169 to 335 s over 100 `main` push runs (median 249 s,
# p95 300 s), and three pull request runs failed on the 280 s budget at 291 to 307 s with
# zero type errors. No change is known to explain the rise from the 2026-10-29 to 30 median
# of 231 s. 370 is about 1.1x the `main` maximum. Passing `main` runs now reach the 328 s of
# #8077's fastest regressed run, so the budget no longer fails that absolute range; #8077 took
# the median from 88.5 s to at least 3.7x that, and a run 1.5x today's median fails 370.
# A pull request reaches this step only when pyright-rs did not run or did not pass. The
# budget times this step alone, so a pyright-rs run before it never counts against it.
PYRIGHT_TIME_BUDGET: ${{ github.event_name == 'pull_request' && '370' || '' }}
UV_NO_SYNC: "1"
run: make typecheck-changed
# Run inside `quality checks`, which finishes several minutes before the test/coverage critical path.
- name: Check public API compatibility with the latest release
env:
GH_TOKEN: ${{ github.token }}
UV_NO_SYNC: "1"
run: |
# Exclude the tag being built: once its GitHub release exists, `gh release view`
# would otherwise compare the release to itself and make this gate a no-op.
# Take the highest version, not the newest: a V1 maintenance release can be published last.
release_tag=$(gh release list --repo pydantic/pydantic-ai --limit 20 \
--exclude-drafts --exclude-pre-releases --json tagName \
| jq -r --arg current "$GITHUB_REF_NAME" \
'map(select(.tagName != $current and (.tagName | test("^v[0-9]+\\.[0-9]+\\.[0-9]+$"))))
| max_by(.tagName | ltrimstr("v") | split(".") | map(tonumber)).tagName // empty')
if [ -z "$release_tag" ]; then
echo '::error::Could not find a prior stable release for the API compatibility baseline.'
exit 1
fi
git fetch --depth=1 origin tag "$release_tag"
uv run python .github/scripts/check_api_compatibility.py --against "$release_tag"
# `src/pydantic_ai_harness/gh-aw/pydantic.md` is the engine definition gh-aw consumers compile
# from the default branch, so nothing downstream re-checks it. `--published` refuses an
# `engine.version` PyPI does not serve.
- run: uv run --script src/pydantic_ai_harness/scripts/gh_aw_engine_version.py --published
- run: uv build --all-packages --no-sources
- run: uv run python .github/scripts/check_http_dependencies.py
- run: ls -lh dist/
- run: uvx twine check --strict dist/*
# The gh-aw workflows run the shim on the published engine runtime `shared/engine-zai.md`
# pins, not on this checkout's packages. A shim that imports a `pydantic_ai` symbol missing
# from that runtime passes every step above and fails every workflow at "Install
# repository workflow policy" (#11935, https://github.com/pydantic/pydantic-ai/actions/runs/44225247904).
# These steps set up that runtime as the compiled agent job does. They come last because
# `setup-python` changes `python3` and its environment for every later step. They need only
# the checkout, so they run after a failed step too.
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
if: ${{ !cancelled() }}
with:
python-version: "3.12"
- name: Import the gh-aw shim on the pinned engine runtime
if: ${{ !cancelled() }}
run: |
version=$(yq --front-matter=extract '.engine.version' .github/workflows/shared/engine-zai.md)
# Copied from the "Preinstall Pydantic AI coder agent" step of the engine definition revision
# `shared/engine-zai.md` imports, with the Logfire install that the workflows' OTLP endpoint
# turns on. Update it when that import changes.
python3 -P -m pip install --quiet --user --disable-pip-version-check \
"pydantic-ai-harness[coder]==$version" "pydantic-clai2==$version" \
"pydantic-ai-slim[anthropic,openai,mcp,spec]>=2.59.0" "cryptography>=48.0.1" "logfire>=4.39.0"
bash .github/scripts/stage-gh-aw-agent.sh
# The engine then imports the agent module `PAI_AGENT` names, with the environment
# `shared/engine-zai.md` gives it: `PAI_OTEL_EXPORT_PATH` makes the import instrument HTTPX and MCP.
PYTHONPATH=/tmp/gh-aw/workflow-python PAI_OTEL_EXPORT_PATH=/tmp/gh-aw/pydantic-ai-private-otel.jsonl \
python3 -P -c 'import pydantic_ai_gh_aw_shim.agent'
# Fails when a change makes a function's cognitive complexity exceed the limit, or grow while above it.
complexity:
name: cognitive complexity
needs: classify
if: needs.classify.outputs.content_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# The base is `HEAD^1`: on a pull request, the base branch tip its merge commit was made on;
# on a push or a merge group, the commit before it on the branch.
fetch-depth: 2
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
enable-cache: true
cache-suffix: complexity
- name: Check cognitive complexity against the base
run: uv run --only-group lint scripts/check_complexity.py --base HEAD^1 --format github
# Fails when a change adds a real-clock wait, a private readiness timeout or a probed port to a test.
- name: Check test waits against the base
if: ${{ !cancelled() }}
run: uv run --only-group lint scripts/check_test_waits.py --base HEAD^1 --format github
# mypy and quality checks are a bit slower than other jobs, so we run them separately
mypy:
needs: classify
if: >-
needs.classify.outputs.content_only != 'true'
&& needs.classify.outputs.clai2_only != 'true'
&& needs.classify.outputs.harness_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
enable-cache: true
cache-suffix: mypy
- name: Install dependencies
run: uv sync --no-dev --group lint
- run: make typecheck-mypy
# The unified-docs repository renders and validates published documentation.
# Keep this source-repository check for assets that live alongside Pydantic AI docs.
docs-assets:
needs: classify
if: needs.classify.outputs.content_only != 'true' || needs.classify.outputs.docs_changed == 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
enable-cache: true
cache-suffix: docs-assets
# Check all documentation images are tinified. You will need a Tinify API key to fix failures.
- run: uvx tinicly docs --check
# The pinned action's curl download reads this config; keep retries scoped to setup.
- name: Configure Lychee download retries
run: |
mkdir -p "$RUNNER_TEMP/lychee-curl"
cat > "$RUNNER_TEMP/lychee-curl/.curlrc" <<'EOF'
show-error
retry = 3
retry-max-time = 120
connect-timeout = 10
max-time = 60
EOF
# Check that links between doc pages resolve, including their `#anchor` fragments. Runs
# `--offline` so only local files are checked: external hosts are swept weekly by
# link-check.yml instead, where being down doesn't block a PR.
- name: Check doc links and heading anchors
uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0
env:
CURL_HOME: ${{ runner.temp }}/lychee-curl
with:
args: --no-progress --offline --include-fragments --config .github/workflows/lychee.toml './docs/**/*.md' './*.md' './examples/**/*.md'
fail: true
# Documentation examples are runtime-checked on one representative Python version. A
# version-specific miss is low-impact and easy to repair, while multiplying this job across
# the support matrix would recreate much of the CI cost this reduced path avoids.
# A harness-only change runs it too: its reduced `test-all-extras` cells skip the docs tests.
docs-only:
name: docs-only checks on Python 3.13
needs: classify
if: >-
(needs.classify.outputs.content_only == 'true' || needs.classify.outputs.harness_only == 'true')
&& needs.classify.outputs.docs_changed == 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 10
env:
CI: true
# Match the all-extras cells in the full matrix: optional SDKs make blocking-call
# detection noisy, while the dedicated 3.13 non-all-extras cells still cover it.
BLOCKBUSTER_ENABLED: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.13"
enable-cache: true
cache-suffix: docs-only
- name: Install documentation test dependencies
run: uv sync --all-extras --all-packages
- name: Check Markdown files
uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
with:
extra_args: --all-files --verbose
env:
SKIP: no-commit-to-branch,format,lint,check-cassettes
UV_NO_SYNC: "1"
- name: Test documentation snippets
run: >-
uv run --no-sync pytest
tests/test_examples.py
tests/harness/test_docs_installation.py
tests/test_docs_parity.py
tests/test_docs_navigation.py
tests/harness/test_docs_parity.py
tests/harness/test_doc_snippets.py
tests/harness/test_workspace_quickstarts.py
-n logical --dist=loadgroup
content-checks:
name: content checks
needs: classify
if: needs.classify.outputs.content_only == 'true' && needs.classify.outputs.docs_changed != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
with:
extra_args: --all-files --verbose
env:
SKIP: no-commit-to-branch,clai-help,format,lint,check-cassettes,complexity,test-waits
test:
name: test on ${{ matrix.python-version }} (${{ matrix.install.name }})
needs: classify
if: needs.classify.outputs.content_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
# `latest-versions-canary.yml` runs the endpoints of this list; update it alongside.
# Growing this or any other test matrix grows the tracked-job count that
# `REPORT_ROW_LIMIT` in `.github/scripts/ci_duration.py` must stay above, or the duration
# report truncates. That constant's comment enumerates all four.
# `all-extras` is the slowest install shape -- it runs sharded in `test-all-extras` instead.
python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
# A single-value dimension, so the `exclude` below can drop the legs a pull request skips:
# 3.14 collects coverage and 3.13 detects blocking calls, so both run every install; 3.11 and
# 3.15, the oldest and newest, run only `standard`; 3.12 goes. A `pydantic-ai-pax`-only change
# keeps its 3.11 leg too, which collects coverage there (see `COLLECT_COVERAGE`). The merge
# queue and `main` run every leg (see `merge_group` in `on:`). The value is the string
# `'true'`, not the boolean `==` yields: `exclude` doesn't match `"true"` to `true`.
pull_request: ["${{ github.event_name == 'pull_request' && 'true' || 'false' }}"]
install:
- name: pydantic-ai-slim
command: "--package pydantic-ai-slim"
- name: pydantic-evals
command: "--package pydantic-evals"
# Install CLAI 2 alongside the harness to exercise the gh-aw launcher, which runs it by its
# published name, the `pydantic-clai2` shim over `pydantic-ai-pax`.
- name: pydantic-ai-harness
command: "--no-sync"
sync_command: >-
--inexact --package pydantic-ai-harness --package pydantic-clai2
--extra code-mode --extra coder --extra logfire --extra render
# Its own suite: the rest of `tests/` is covered by the other cells.
paths: tests/harness
- name: pydantic-ai-pax
command: "--package pydantic-ai-pax"
paths: tests/pax
- name: standard
command: ""
# Single-value dimensions, so the `exclude` below can drop every cell but `pydantic-ai-pax`
# when `classify` found a change confined to it, and every cell but `pydantic-ai-harness`
# and `pydantic-ai-pax` for one confined to those two.
clai2_only: ["${{ needs.classify.outputs.clai2_only }}"]
harness_only: ["${{ needs.classify.outputs.harness_only }}"]
exclude:
- clai2_only: "true"
install: { name: pydantic-ai-slim }
- clai2_only: "true"
install: { name: pydantic-evals }
- clai2_only: "true"
install: { name: pydantic-ai-harness }
- clai2_only: "true"
install: { name: standard }
- harness_only: "true"
install: { name: pydantic-ai-slim }
- harness_only: "true"
install: { name: pydantic-evals }
- harness_only: "true"
install: { name: standard }
- pull_request: "true"
python-version: "3.12"
- pull_request: "true"
python-version: "3.11"
install: { name: pydantic-ai-slim }
- pull_request: "true"
python-version: "3.11"
install: { name: pydantic-evals }
- pull_request: "true"
python-version: "3.11"
install: { name: pydantic-ai-harness }
- pull_request: "true"
python-version: "3.11"
clai2_only: "false"
install: { name: pydantic-ai-pax }
- pull_request: "true"
python-version: "3.15"
install: { name: pydantic-ai-slim }
- pull_request: "true"
python-version: "3.15"
install: { name: pydantic-evals }
- pull_request: "true"
python-version: "3.15"
install: { name: pydantic-ai-harness }
- pull_request: "true"
python-version: "3.15"
install: { name: pydantic-ai-pax }
env:
CI: true
# Coverage adds roughly 50% to test execution before Python 3.14. Collect every install shape
# on 3.14, where coverage uses the faster sys.monitoring core; the other versions still run
# every applicable test without duplicate coverage. A `pydantic-ai-pax`-only change also
# collects it on 3.11: `tests/pax` has pre-3.14 lines and branches that `all-extras` covers otherwise.
COLLECT_COVERAGE: ${{ matrix.python-version == '3.14' || matrix.clai2_only == 'true' && matrix.python-version == '3.11' }}
BLOCKBUSTER_ENABLED: ${{ matrix.python-version == '3.13' }}
# A `pydantic-ai-pax`-only change skips `all-extras`, so its cells install every `pydantic-ai-pax`
# extra themselves: `tests/pax` gates tests on `typesafe` and on each `/sandbox` SDK, and only
# those tests run their fakes.
CLAI2_ALL_EXTRAS: ${{ matrix.clai2_only == 'true' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: ${{ matrix.python-version }}
enable-cache: true
cache-suffix: ${{ matrix.install.name }}
- run: mkdir .coverage
# Every test install includes the `dev` group, whose `mongomock-motor` pulls in PyMongo, so only
# this install catches a module that imports `pymongo` (the `mongodb` extra) eagerly instead of
# behind its lazy `__getattr__`. It runs before `uv sync --only-dev`, which removes it again.
- name: import pydantic-ai-harness without extras or dependency groups
if: matrix.install.name == 'pydantic-ai-harness'
run: |
uv sync --package pydantic-ai-harness --no-default-groups
# Fail if a base dependency pulls PyMongo back in, rather than pass while testing nothing.
uv run --no-sync python -c "
import importlib.util
assert importlib.util.find_spec('pymongo') is None, 'the base install must not include pymongo'
assert importlib.util.find_spec('json_repair') is None, 'json-repair belongs to the coder and repair-tool-arguments extras'
import pydantic_ai_harness, pydantic_ai_harness.media, pydantic_ai_harness.step_persistence
import pydantic_ai_harness.file_system, pydantic_ai_harness.shell
try:
import pydantic_ai_harness.coder
except ImportError as error:
assert 'pydantic-ai-harness[coder]' in str(error), error
else:
raise AssertionError('Coder imported without the coder extra')
"
- run: uv sync --only-dev
# A sync that selects two packages ignores root dependency groups, so `gh-aw-tracing` gets its own.
- name: install harness and CLAI 2 test dependencies
if: matrix.install.name == 'pydantic-ai-harness'
run: |
uv sync ${{ matrix.install.sync_command }}
uv sync --inexact --only-group gh-aw-tracing
# `-n logical`, not `-n auto`: when `psutil` is importable, xdist's `auto` counts
# *physical* cores while `logical` counts every vCPU, which is what hyperthreaded
# runners want. `psutil` is not in `uv.lock` and `UV_FROZEN` pins CI to it, so both
# spellings resolve to the same count today; the flag is here for when that stops
# being true.
# Everything under `tests/durable_exec` and every test marked `temporal` runs in
# `test-durable-exec` instead: those tests pin xdist groups around real local servers, so
# the chains they form would otherwise be the critical-path floor of the all-extras cells --
# the other install variants skip the suites at module level, for want of the engine packages.
# Its `lowest` leg proves the minimum `temporalio`/`dbos`/`prefect` bounds.
- name: run tests
shell: bash
run: |
extra=()
if [[ "$CLAI2_ALL_EXTRAS" == "true" ]]; then
extra=(--all-extras)
fi
if [[ "$COLLECT_COVERAGE" == "true" ]]; then
export COVERAGE_PROCESS_START="$PWD/pyproject.toml"
runner=(coverage run -m pytest)
else
unset COVERAGE_PROCESS_START
runner=(pytest)
fi
uv run ${{ matrix.install.command }} "${extra[@]}" "${runner[@]}" --durations=100 -n logical --dist=loadgroup \
--ignore=tests/durable_exec -m "not temporal" ${{ matrix.install.paths }}
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-${{ matrix.install.name }}
# Merge this job's per-worker/per-subprocess data files into one before upload: the
# combine work runs in parallel across the matrix instead of serially in the `coverage`
# job, which would otherwise merge hundreds of files on the critical path.
- name: combine coverage files
if: env.COLLECT_COVERAGE == 'true'
shell: bash
run: |
extra=()
if [[ "$CLAI2_ALL_EXTRAS" == "true" ]]; then
extra=(--all-extras)
fi
uv run ${{ matrix.install.command }} "${extra[@]}" coverage combine
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-${{ matrix.install.name }}
- name: store coverage files
if: env.COLLECT_COVERAGE == 'true'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: coverage-${{ matrix.python-version }}-${{ matrix.install.name }}
path: .coverage
include-hidden-files: true
# The sharded jobs below assign whole test modules to shards by the per-test durations their
# shards uploaded on the latest `main` run (see `.github/scripts/shard_durations.py`). Fetching
# that baseline once here means every shard of this run splits from the same file, so each module
# runs exactly once even if the API fails (the files are then empty and the split falls back to
# module size). The REST fetch costs about 20 calls from the repository's `GITHUB_TOKEN` budget,
# so only the first `main` push run of each UTC hour makes it, and caches the result; every other
# run restores the newest cached baseline, which costs no REST calls, and fetches only when there
# is none. Keep the shard counts in step with `SPLITS` in the jobs below. It runs alongside
# `classify`, not after it, to stay off the critical path, so it also runs (and its result goes
# unused) on content-only and clai2-only changes, where the sharded jobs are skipped. That costs a
# few API calls; don't add `needs: classify` to save them.
test-durations-baseline:
name: fetch test durations baseline
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 10
permissions:
contents: read
actions: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
sparse-checkout: .github/scripts
# `/rate_limit` costs no calls. With the headers `shard_durations.py fetch` prints, it shows
# which budget this token draws from.
- name: show the REST rate limit
env:
GH_TOKEN: ${{ github.token }}
run: gh api rate_limit --jq .resources.core || true
# The script's hash keeps a change to `fetch` from restoring what the old code fetched, so
# the pull request that makes it runs it.
- name: pick this hour's baseline cache key
id: key
env:
PREFIX: test-durations-baseline-${{ hashFiles('.github/scripts/shard_durations.py') }}-
run: |
echo "prefix=$PREFIX" >> "$GITHUB_OUTPUT"
echo "key=$PREFIX$(date -u +%Y%m%d%H)" >> "$GITHUB_OUTPUT"
# A cache that fails to restore is a miss, so the step below fetches instead.
- name: restore the cached test durations
id: restore
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: test-durations
key: ${{ steps.key.outputs.key }}
# A `main` push run takes only this hour's baseline, so it refreshes a stale one.
restore-keys: >-
${{ (github.event_name != 'push' || github.ref != 'refs/heads/main') && steps.key.outputs.prefix || '' }}
- name: fetch the latest main run's test durations
id: fetch
if: steps.restore.outputs.cache-matched-key == ''
env:
GH_TOKEN: ${{ github.token }}
run: |
mkdir -p test-durations
baselines=()
for python in 3.11 3.12 3.13 3.14 3.15; do
all_extras_shards=2
if [[ "$python" == 3.11 ]]; then all_extras_shards=3; fi
baselines+=(--prefix "test-durations-$python-all-extras-"
--shards "$all_extras_shards" --output "test-durations/$python-all-extras.json")
# No 3.15 lowest-versions shards exist to fetch: like `test-durable-exec`'s `lowest` leg, they
# would compile our declared minimums from source on 3.15.
if [[ "$python" != 3.15 ]]; then
baselines+=(--prefix "test-durations-$python-lowest-versions-"
--shards 2 --output "test-durations/$python-lowest-versions.json")
fi
done
python3 .github/scripts/shard_durations.py fetch "${baselines[@]}"
# Only a baseline no API failure emptied, so a failure never outlives the run that hit it. A
# re-run keeps its original `created_at`, so it would select, and cache, an older baseline.
- name: cache the test durations for later runs
if: >-
github.event_name == 'push' && github.ref == 'refs/heads/main' && github.run_attempt == '1'
&& steps.fetch.outputs.errors == '0'
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: test-durations
key: ${{ steps.key.outputs.key }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: test-durations-baseline
path: test-durations
if-no-files-found: error
retention-days: 7
# `all-extras` is the slowest install shape by a wide margin -- it alone pulls in every
# optional dependency -- so it gets its own job, split into shards, instead of sharing the
# `test` job's timeout budget with the three much lighter install shapes.
# A `pydantic-ai-harness`-only change runs just `tests/harness` and `tests/pax` here, keeping
# three shards on 3.11 for its legacy coverage tracer and one shard on every other version.
test-all-extras:
name: >-
test on ${{ matrix.python-version }} (all-extras, shard ${{ matrix.shard }}/${{
matrix.python-version == '3.11' && 3 || needs.classify.outputs.harness_only == 'true' && 1 || 2
}})
needs: [classify, test-durations-baseline]
if: needs.classify.outputs.content_only != 'true' && needs.classify.outputs.clai2_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-24.04' }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
shard: ${{ fromJSON(needs.classify.outputs.harness_only == 'true' && '[1]' || '[1, 2]') }}
# 3.11 and 3.14 collect coverage, 3.13 enforces the per-test budget and 3.15 is the newest,
# so a pull request skips only 3.12 (see the `test` job's matrix).
pull_request: ["${{ github.event_name == 'pull_request' && 'true' || 'false' }}"]
include: >-
${{ fromJSON(needs.classify.outputs.harness_only == 'true' && '[{"python-version": "3.11", "shard": 2}, {"python-version": "3.11", "shard": 3}]' || '[{"python-version": "3.11", "shard": 3}]') }}
exclude:
- pull_request: "true"
python-version: "3.12"
env:
CI: true
# Collect 3.14 for fast coverage and 3.11 for branches and extras unavailable on 3.14.
# The 3.11 legacy tracer needs a third shard to stay within the job timeout.
COLLECT_COVERAGE: ${{ matrix.python-version == '3.14' || matrix.python-version == '3.11' }}
# Computed from `classify`'s output, so passed to the shell through the environment.
SHARD: ${{ matrix.shard }}
SPLITS: ${{ matrix.python-version == '3.11' && 3 || needs.classify.outputs.harness_only == 'true' && 1 || 2 }}
TEST_PATHS: ${{ needs.classify.outputs.harness_only == 'true' && 'tests/harness tests/pax' || '' }}
DURATIONS_PREFIX: test-durations-${{ matrix.python-version }}-all-extras-
DURATIONS_BASELINE: test-durations-baseline/${{ matrix.python-version }}-all-extras.json
# Rebenchmark after https://github.com/cbornet/blockbuster/pull/61 is released in a
# compatible version; re-enable if a shard then stays comfortably within its timeout.
BLOCKBUSTER_ENABLED: false
# `tests/test_examples.py` type-checks the docs examples with pyright; once per run is enough.
TYPECHECK_EXAMPLES: ${{ matrix.python-version == '3.14' }}
# Per-test time budget enforced by `tests/cost_guards.py` (see "Test cost" in `tests/AGENTS.md`). The 3.13
# cells run nearly every test without coverage or blocking-call detection, so their timings carry the least
# instrumentation noise. 8s sits above the fresh-interpreter tests (4-6s on these runners) with headroom for runner
# jitter; the per-test report on the same cells surfaces anything new over 1s. List the tests over a budget from a
# run's `--durations` with `scripts/list_over_budget_tests.py`.
PYTEST_TEST_BUDGET_SECONDS: ${{ matrix.python-version == '3.13' && '8' || '' }}
# Per-module collection budget, also enforced by `tests/cost_guards.py`. With it set, the guard imports the
# dependencies in its `SHARED_DEPENDENCIES` before collection, so each module is charged only for its own
# imports, not for being the first in its shard to import a shared one. 8s leaves headroom for runner jitter,
# and sits well below the 11-16s a module paid for importing `torch` at collection.
PYTEST_COLLECT_BUDGET_SECONDS: ${{ matrix.python-version == '3.13' && '8' || '' }}
# `tests/harness/absurd` runs on Absurd's schema; an unreachable server fails rather than skips.
ABSURD_REQUIRE_LIVE: "1"
ABSURD_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/postgres
# `tests/harness/pgtask` runs on pgtask's schema in the same server.
PGTASK_REQUIRE_LIVE: "1"
PGTASK_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/postgres
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# Ubuntu 24.04 includes PostgreSQL 16. Create a separate cluster with the Docker
# database's locale; the runner's pre-created cluster defaults to C.UTF-8.
- name: start PostgreSQL 16
id: postgres
env:
PGHOST: 127.0.0.1
PGPORT: "5432"
PGUSER: postgres
PGDATABASE: postgres
PGPASSWORD: postgres
PGCONNECT_TIMEOUT: "5"
run: |
sudo pg_createcluster --port=5432 --locale=en_US.utf8 --start-conf=manual --pgoption=timezone=Etc/UTC 16 ci \
-- --auth-local=peer --auth-host=scram-sha-256
sudo -u postgres pg_ctlcluster 16 ci start -- -w -t 60
sudo -u postgres psql -X -h /var/run/postgresql -p 5432 -U postgres -d postgres -v ON_ERROR_STOP=1 -c "ALTER ROLE postgres PASSWORD 'postgres'"
psql -X -v ON_ERROR_STOP=1 <<'SQL'
SELECT version(), datcollate, datctype, current_setting('server_encoding')
FROM pg_database WHERE datname = current_database();
DO $verify$
BEGIN
ASSERT current_setting('server_version_num')::int / 10000 = 16;
ASSERT current_setting('server_encoding') = 'UTF8';
ASSERT current_setting('TimeZone') = 'Etc/UTC';
ASSERT (SELECT datcollate = 'en_US.utf8' AND datctype = 'en_US.utf8'
FROM pg_database WHERE datname = current_database());
ASSERT (SELECT array_agg(v ORDER BY v) FROM
(VALUES ('a'), ('A'), ('z'), ('Z'), ('é'), ('😀')) AS sample(v))
= ARRAY['😀', 'a', 'A', 'é', 'z', 'Z'];
END
$verify$;
SQL
if PGPASSWORD=deliberately-wrong psql -X -c 'SELECT 1'; then
echo '::error::PostgreSQL accepted an incorrect password'
exit 1
fi
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: ${{ matrix.python-version }}
enable-cache: true
cache-suffix: all-extras
- run: mkdir .coverage
- run: uv sync --only-dev
# Cache only the immutable model used by `TestSentenceTransformers`. The old
# shared HF cache could be populated first by a matrix job that never downloaded
# this model, permanently turning an exact cache hit into a cold model cache.
# The `sentence-transformers` extra only installs below Python 3.14 (its marker in
# `pydantic_ai_slim/pyproject.toml`), so 3.14 and 3.15 skip these three steps: there,
# the download would fail its import and spend its retries before giving up.
- name: restore sentence-transformers test model
id: sentence-transformers-cache
if: matrix.python-version != '3.14' && matrix.python-version != '3.15'
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/huggingface/hub/models--sentence-transformers-testing--stsb-bert-tiny-safetensors
key: hf-${{ runner.os }}-stsb-bert-tiny-safetensors-f3cb857cba53019a20df283396bcca179cf051a4
# Warm the HF cache out-of-band (retried, non-fatal) so the sentence-transformers
# test model is on disk when the ST tests load it: the pinned revision is then
# served from cache without revalidating against the Hub (see the
# `stsb_bert_tiny_model` fixture). On a cache miss, fetch the full pinned
# snapshot — this job and `test-lowest-versions` share the cache key, so the
# cached snapshot must not depend on which resolution flavor warmed it — then
# construct the model once to prove it is usable before saving. On a sustained
# HF outage the real-model smoke tests skip; deterministic adapter tests still
# preserve coverage. Both shards race to warm/save this key; the loser's save is a
# harmless no-op against the already-populated cache.
- name: pre-download sentence-transformers test model
id: sentence-transformers-download
if: >-
matrix.python-version != '3.14' && matrix.python-version != '3.15'
&& steps.sentence-transformers-cache.outputs.cache-hit != 'true'
continue-on-error: true
run: |
for i in 1 2 3; do
if uv run --all-extras python -c "from huggingface_hub import snapshot_download; from sentence_transformers import SentenceTransformer; snapshot_download('sentence-transformers-testing/stsb-bert-tiny-safetensors', revision='f3cb857cba53019a20df283396bcca179cf051a4'); SentenceTransformer('sentence-transformers-testing/stsb-bert-tiny-safetensors', revision='f3cb857cba53019a20df283396bcca179cf051a4')"; then
exit 0
fi
echo "HF model download attempt $i failed; retrying in 15s..."
sleep 15
done
echo "sentence-transformers test model unavailable after retries; ST tests will skip"
exit 1
# A failed non-fatal download must not become an immutable exact cache hit.
- name: save sentence-transformers test model
if: >-
matrix.python-version != '3.14' && matrix.python-version != '3.15'
&& steps.sentence-transformers-cache.outputs.cache-hit != 'true'
&& steps.sentence-transformers-download.outcome == 'success'
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/huggingface/hub/models--sentence-transformers-testing--stsb-bert-tiny-safetensors
key: ${{ steps.sentence-transformers-cache.outputs.cache-primary-key }}
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: test-durations-baseline
path: ${{ runner.temp }}/test-durations-baseline
# `-n logical` (see note on the `test` job). Split into `SPLITS` shards so this, the slowest
# install shape, keeps pace with the rest of the matrix. `shard_durations.py select` assigns
# whole test modules to shards by the `test-durations-baseline` durations and `--ignore`s the
# other shards' modules, so a shard's workers never collect them (`pytest-split` would have
# every worker collect the whole suite, then deselect most of it). The 3.11 cells use three
# shards; every test module runs in exactly one shard per version.
# Everything under `tests/durable_exec` and every test marked `temporal` runs in
# `test-durable-exec` instead: those tests pin xdist groups around real local servers, so
# the chains they form would otherwise be this job's critical-path floor.
- name: run tests
shell: bash
run: |
if [[ "$COLLECT_COVERAGE" == "true" ]]; then
export COVERAGE_PROCESS_START="$PWD/pyproject.toml"
runner=(coverage run -m pytest)
else
unset COVERAGE_PROCESS_START
runner=(pytest)
fi
# `--all-packages` so the extras of every workspace member are installed, not just the
# root package's: that is where `pydantic-ai-harness`'s optional integrations get tested.
uv run --no-project python .github/scripts/shard_durations.py select --durations "$RUNNER_TEMP/$DURATIONS_BASELINE" \
--shards "$SPLITS" --shard "$SHARD" --exclude tests/durable_exec > "$RUNNER_TEMP/shard-args.txt"
mapfile -t shard_args < "$RUNNER_TEMP/shard-args.txt"
read -ra test_paths <<< "$TEST_PATHS"
# `--store-durations` (from `pytest-split`) records this shard's durations for the next run.
uv run --all-packages --all-extras "${runner[@]}" --durations=100 -n logical --dist=loadgroup \
--ignore=tests/durable_exec -m "not temporal" "${shard_args[@]}" "${test_paths[@]}" \
--store-durations --clean-durations --durations-path "$RUNNER_TEMP/test-durations.json"
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-all-extras-${{ matrix.shard }}
- name: stop PostgreSQL 16
if: ${{ always() && steps.postgres.outcome != 'skipped' }}
run: |
sudo -u postgres pg_ctlcluster --mode fast 16 ci stop -- -w -t 30
status=0
pg_isready -h 127.0.0.1 -p 5432 -t 5 || status=$?
test "$status" -eq 2
# Only `main` push runs are ever read back as the baseline (`shard_durations.py fetch`).
- name: store test durations
if: ${{ !cancelled() && github.event_name == 'push' }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ${{ env.DURATIONS_PREFIX }}${{ matrix.shard }}
path: ${{ runner.temp }}/test-durations.json
if-no-files-found: ignore
retention-days: 30
# Show authors what their change costs: new tests over a second and tests that got at least
# twice as slow as on `main`, in the job summary. One coverage-free version is enough, and it must be one a pull
# request runs.
- name: report new and slower tests
if: ${{ !cancelled() && matrix.python-version == '3.13' }}
run: >-
uv run --no-project python .github/scripts/shard_durations.py report
--baseline "$RUNNER_TEMP/$DURATIONS_BASELINE" --current "$RUNNER_TEMP/test-durations.json"
--title "all-extras on ${{ matrix.python-version }}, shard $SHARD"
- name: cover Absurd and pgtask without a database URL
if: matrix.python-version == '3.14' && matrix.shard == 1
run: >-
env -u ABSURD_TEST_DATABASE_URL -u PGTASK_TEST_DATABASE_URL
uv run --all-packages --all-extras
coverage run -m pytest
tests/harness/absurd/test_absurd.py::TestDurability::test_replay_serves_cached_model_response
tests/harness/pgtask/test_pgtask.py::TestReplay::test_model_response_served_from_checkpoint
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-all-extras-${{ matrix.shard }}
# See the matching step in the `test` job.
- name: combine coverage files
if: env.COLLECT_COVERAGE == 'true'
run: uv run --all-packages --all-extras coverage combine
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-all-extras-${{ matrix.shard }}
- name: store coverage files
if: env.COLLECT_COVERAGE == 'true'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: coverage-${{ matrix.python-version }}-all-extras-${{ matrix.shard }}
path: .coverage
include-hidden-files: true
# The durable-execution suites pin their tests to xdist groups sharing a real local server --
# one group per core Temporal test module, one shared harness Temporal group, one for DBOS, and
# one for Prefect -- so inside the main matrix those groups dominate its critical path. Running
# them in their own job takes them off that path entirely; `--dist=loadgroup` still spreads the
# groups across this job's workers, and only the tests within one group run in sequence.
# New durable-exec tests land anywhere under `tests/durable_exec` and are picked up
# automatically. Harness tests that start or connect to a Temporal dev server use the
# registered `temporal` marker. Both sets run only in this job, which sets
# `BLOCKBUSTER_ENABLED: false`. A test that needs blocking detection belongs elsewhere under
# `tests/`, where the `test` job turns it on for the 3.13 cells (`test-all-extras` leaves it off).
# The `lowest` resolution leg is the only place the declared minimum bounds
# (`temporalio`, `dbos`, `prefect`) are proven: `test-lowest-versions` skips this directory.
test-durable-exec:
name: test durable-exec on ${{ matrix.python-version }} (${{ matrix.resolution }})
needs: classify
if: needs.classify.outputs.content_only != 'true' && needs.classify.outputs.clai2_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12", "3.13", "3.14"]
resolution: [locked, lowest]
# A pull request runs only the legs that collect coverage (see `COLLECT_COVERAGE`), which
# include one `lowest` leg (see the `test` job's matrix), the 3.13 `locked` leg that runs the
# Render local runtime tests (see `RENDER_LOCAL_RUNTIME`), and the 3.15 `locked` leg below,
# the newest Python, which runs the manifest freshness test of a `pydantic-ai-harness`-only
# change (see `DURABLE_EXEC_MANIFEST_FRESHNESS`).
pull_request: ["${{ github.event_name == 'pull_request' && 'true' || 'false' }}"]
exclude:
- pull_request: "true"
python-version: "3.11"
resolution: lowest
- pull_request: "true"
python-version: "3.13"
resolution: lowest
- pull_request: "true"
python-version: "3.14"
resolution: lowest
# 3.15 runs the `locked` leg only: `lowest` installs our declared minimums, and 13 of them
# have no 3.15 wheel (pydantic-core 2.41, numpy 2.3, tiktoken 0.12, ...), so the leg would
# compile them from source past this job's timeout.
include:
- python-version: "3.15"
resolution: locked
env:
CI: true
# Python 3.11 and 3.14 cover version endpoints; both 3.12 resolutions cover Temporal dependency branches.
COLLECT_COVERAGE: >-
${{
matrix.python-version == '3.12'
|| ((matrix.python-version == '3.11' || matrix.python-version == '3.14') && matrix.resolution == 'locked')
}}
# Blocking detection already runs in the Python 3.13 slim, evals, and standard jobs.
BLOCKBUSTER_ENABLED: false
# The one leg that runs the Render local runtime tests (see that step).
RENDER_LOCAL_RUNTIME: ${{ matrix.python-version == '3.13' && matrix.resolution == 'locked' }}
# The one leg that runs the contract manifest freshness test of a `pydantic-ai-harness`-only
# change (see the run tests step). On the full path, every leg runs it within
# `tests/durable_exec`.
DURABLE_EXEC_MANIFEST_FRESHNESS: ${{ matrix.python-version == '3.15' && matrix.resolution == 'locked' }}
# Puts every Temporal worker in debug mode, which disables the workflow deadlock detector
# (temporalio sets the per-activation budget to `None` instead of 2s). That budget is
# wall-clock, so it measures runner contention as readily as a blocking call, and a
# descheduled workflow thread trips it as `TMPRL1101`. The cost: a genuine in-workflow
# blocking call now hangs to the job timeout instead of failing in 2s. Since `temporalio`
# 1.29, debug mode also runs every workflow activation inline on the worker's event loop
# instead of in the executor thread a production worker uses, so on the `locked` legs only a
# test that unsets this variable runs workflow code on that thread.
TEMPORAL_DEBUG: '1'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: ${{ matrix.python-version }}
enable-cache: true
cache-suffix: durable-exec-${{ matrix.resolution }}
- run: mkdir .coverage
# The Temporal tests download the dev-server binary on first use, to the directory that
# `temporal_dev_server_cache_dir` in tests/temporal_utils.py returns; cache it so a CDN
# hiccup can't fail the suite at setup (#5399).
# Separate key per resolution: the lowest leg may resolve a different temporalio version
# wanting a different binary. A stale restored dir is safe because the SDK names the
# binary by its own version and re-downloads on a miss.
- name: cache Temporal dev-server binary
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/temporal-dev-server
key: temporal-cli-${{ runner.os }}-${{ runner.arch }}-${{ matrix.resolution }}-${{ hashFiles('**/uv.lock') }}
restore-keys: |
temporal-cli-${{ runner.os }}-${{ runner.arch }}-${{ matrix.resolution }}-
- name: install lowest resolution
if: matrix.resolution == 'lowest'
run: uv sync --all-packages --all-extras --no-extra sentence-transformers --resolution lowest-direct
env:
UV_FROZEN: "0"
# `--all-extras` matches the all-extras matrix cell these tests used to run in, so
# the module-level `try_import` skip-gating (logfire, mcp, openai, anthropic, ...)
# behaves identically and coverage combination stays complete. The lowest leg was
# synced above, so `--no-sync` there keeps its resolution.
# `sentence-transformers` is the exception: it brings torch and the CUDA wheels, about
# 2.6 GB of a 3.2 GB install, and no test here imports it. A slow download of them has
# run this job past `timeout-minutes` (#12625). Keep every `uv` call in this job on the
# same extras, so none of them syncs it back in.
- name: run tests
shell: bash
run: |
if [[ "$COLLECT_COVERAGE" == "true" ]]; then
export COVERAGE_PROCESS_START="$PWD/pyproject.toml"
runner=(coverage run -m pytest)
else
unset COVERAGE_PROCESS_START
runner=(pytest)
fi
# A `pydantic-ai-harness`-only change runs the harness `temporal` tests and, of
# `tests/durable_exec`, only the contract manifest freshness test, on the leg that sets
# `DURABLE_EXEC_MANIFEST_FRESHNESS`: the manifest also walks the Harness engines, so a
# harness change can leave it stale.
if [[ "$HARNESS_ONLY" != "true" ]]; then
uv run ${{ matrix.resolution == 'lowest' && '--no-sync' || '--all-packages --all-extras --no-extra sentence-transformers' }} \
"${runner[@]}" --durations=20 -n logical --dist=loadgroup tests/durable_exec
elif [[ "$DURABLE_EXEC_MANIFEST_FRESHNESS" == "true" ]]; then
uv run ${{ matrix.resolution == 'lowest' && '--no-sync' || '--all-packages --all-extras --no-extra sentence-transformers' }} \
"${runner[@]}" tests/durable_exec/test_durable_exec_contract_manifest.py
fi
# Only modules that mention Temporal can hold `temporal` tests (`tests/harness/conftest.py` enforces it), so the
# workers don't spend over a minute collecting the rest of `tests/harness` just to deselect it.
mapfile -t temporal_modules < <(git grep -liE 'temporal' -- 'tests/harness/**/test_*.py' 'tests/harness/test_*.py')
(( ${#temporal_modules[@]} )) || { echo '::error::No harness module mentions Temporal.'; exit 1; }
uv run ${{ matrix.resolution == 'lowest' && '--no-sync' || '--all-packages --all-extras --no-extra sentence-transformers' }} \
"${runner[@]}" --durations=20 -n logical --dist=loadgroup -m temporal "${temporal_modules[@]}"
env:
HARNESS_ONLY: ${{ needs.classify.outputs.harness_only }}
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-durable-exec-${{ matrix.resolution }}
# The Render Workflows integration runs nested agents in separate worker processes on the
# keyless local runtime from the Render CLI. It adds about a minute, so one leg runs it; the
# live files are omitted from coverage.
- name: run Render local runtime tests
if: env.RENDER_LOCAL_RUNTIME == 'true'
shell: bash
run: |
curl -fsSL -o "$RUNNER_TEMP/render-cli.zip" \
"https://github.com/render-oss/cli/releases/download/v${RENDER_CLI_VERSION}/cli_${RENDER_CLI_VERSION}_linux_amd64.zip"
echo "${RENDER_CLI_SHA256} $RUNNER_TEMP/render-cli.zip" | sha256sum --check --quiet
unzip -q "$RUNNER_TEMP/render-cli.zip" "cli_v${RENDER_CLI_VERSION}" -d "$RUNNER_TEMP/render-cli"
mv "$RUNNER_TEMP/render-cli/cli_v${RENDER_CLI_VERSION}" "$RUNNER_TEMP/render-cli/render"
chmod +x "$RUNNER_TEMP/render-cli/render"
export PATH="$RUNNER_TEMP/render-cli:$PATH"
uv run --all-packages --all-extras --no-extra sentence-transformers \
pytest --durations=5 tests/harness/render/test_local_runtime_live.py
env:
RENDER_CLI_VERSION: 2.28.0
RENDER_CLI_SHA256: 00d1ca6f3c31b1f4bc7316837b8ee24acbeb11cf372b7593c7d2c3106a1987b4
PYDANTIC_AI_HARNESS_RENDER_LOCAL_RUNTIME: '1'
# See the matching step in the `test` job.
- name: combine coverage files
if: env.COLLECT_COVERAGE == 'true'
run: >-
uv run ${{ matrix.resolution == 'lowest' && '--no-sync' || '--all-packages --all-extras --no-extra sentence-transformers' }}
coverage combine
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-durable-exec-${{ matrix.resolution }}
- name: store coverage files
if: env.COLLECT_COVERAGE == 'true'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: coverage-${{ matrix.python-version }}-durable-exec-${{ matrix.resolution }}
path: .coverage
include-hidden-files: true
# The harness declares minimum bounds for its own dependencies, so a `pydantic-ai-harness`-only
# change still proves them here, running just `tests/harness` and `tests/pax` in one shard.
test-lowest-versions:
name: >-
test on ${{ matrix.python-version }} (lowest-versions, shard ${{ matrix.shard }}/${{
needs.classify.outputs.harness_only == 'true' && 1 || 2
}})
needs: [classify, test-durations-baseline]
if: needs.classify.outputs.content_only != 'true' && needs.classify.outputs.clai2_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
# No 3.15: our declared minimums (pydantic-core 2.41, numpy 2.3, tiktoken 0.12, ...) have no 3.15 wheels.
python-version: ["3.11", "3.12", "3.13", "3.14"]
shard: ${{ fromJSON(needs.classify.outputs.harness_only == 'true' && '[1]' || '[1, 2]') }}
# A pull request runs only 3.14, the version that collects coverage (see the `test` job's
# matrix).
pull_request: ["${{ github.event_name == 'pull_request' && 'true' || 'false' }}"]
exclude:
- pull_request: "true"
python-version: "3.11"
- pull_request: "true"
python-version: "3.12"
- pull_request: "true"
python-version: "3.13"
env:
CI: true
# Python 3.14's sys.monitoring coverage core is substantially cheaper than the legacy tracer.
COLLECT_COVERAGE: ${{ matrix.python-version == '3.14' }}
# Blocking detection already runs in the Python 3.13 slim, evals, and standard jobs;
# repeating its stack-inspection overhead here pushes lowest-version jobs past the CI budget.
BLOCKBUSTER_ENABLED: false
# The docs examples are type-checked in the Python 3.14 all-extras jobs.
TYPECHECK_EXAMPLES: false
DURATIONS_PREFIX: test-durations-${{ matrix.python-version }}-lowest-versions-
DURATIONS_BASELINE: test-durations-baseline/${{ matrix.python-version }}-lowest-versions.json
# Computed from `classify`'s output, so passed to the shell through the environment.
SHARD: ${{ matrix.shard }}
SPLITS: ${{ needs.classify.outputs.harness_only == 'true' && 1 || 2 }}
TEST_PATHS: ${{ needs.classify.outputs.harness_only == 'true' && 'tests/harness tests/pax' || '' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: ${{ matrix.python-version }}
enable-cache: true
cache-suffix: lowest-versions
- run: mkdir .coverage
- name: restore sentence-transformers test model
id: sentence-transformers-cache
if: matrix.python-version != '3.14'
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/huggingface/hub/models--sentence-transformers-testing--stsb-bert-tiny-safetensors
key: hf-${{ runner.os }}-stsb-bert-tiny-safetensors-f3cb857cba53019a20df283396bcca179cf051a4
- run: uv sync --all-packages --all-extras --resolution lowest-direct
env:
UV_FROZEN: "0"
# Warm the HF cache out-of-band: full pinned snapshot, then a validation
# construct (see the matching step in the `test` job for the full rationale).
- name: pre-download sentence-transformers test model
id: sentence-transformers-download
if: >-
matrix.python-version != '3.14'
&& steps.sentence-transformers-cache.outputs.cache-hit != 'true'
continue-on-error: true
run: |
for i in 1 2 3; do
if uv run --no-sync python -c "from huggingface_hub import snapshot_download; from sentence_transformers import SentenceTransformer; snapshot_download('sentence-transformers-testing/stsb-bert-tiny-safetensors', revision='f3cb857cba53019a20df283396bcca179cf051a4'); SentenceTransformer('sentence-transformers-testing/stsb-bert-tiny-safetensors', revision='f3cb857cba53019a20df283396bcca179cf051a4')"; then
exit 0
fi
echo "HF model download attempt $i failed; retrying in 15s..."
sleep 15
done
echo "sentence-transformers test model unavailable after retries; ST tests will skip"
exit 1
- name: save sentence-transformers test model
if: >-
matrix.python-version != '3.14'
&& steps.sentence-transformers-cache.outputs.cache-hit != 'true'
&& steps.sentence-transformers-download.outcome == 'success'
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/huggingface/hub/models--sentence-transformers-testing--stsb-bert-tiny-safetensors
key: ${{ steps.sentence-transformers-cache.outputs.cache-primary-key }}
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: test-durations-baseline
path: ${{ runner.temp }}/test-durations-baseline
# `-n logical` (see note on the `test` job). Split into 2 shards by test module (see the
# matching note in `test-all-extras` for why and how).
# The durable-execution suites and harness `temporal` tests run in `test-durable-exec`
# (its `lowest` leg covers this resolution), keeping their grouped xdist chains off this
# job's critical path.
- name: run tests
shell: bash
run: |
if [[ "$COLLECT_COVERAGE" == "true" ]]; then
export COVERAGE_PROCESS_START="$PWD/pyproject.toml"
runner=(coverage run -m pytest)
else
unset COVERAGE_PROCESS_START
runner=(pytest)
fi
uv run --no-project python .github/scripts/shard_durations.py select --durations "$RUNNER_TEMP/$DURATIONS_BASELINE" \
--shards "$SPLITS" --shard "$SHARD" --exclude tests/durable_exec > "$RUNNER_TEMP/shard-args.txt"
mapfile -t shard_args < "$RUNNER_TEMP/shard-args.txt"
read -ra test_paths <<< "$TEST_PATHS"
uv run --no-sync "${runner[@]}" --durations=100 -n logical --dist=loadgroup \
--ignore=tests/durable_exec -m "not temporal" "${shard_args[@]}" "${test_paths[@]}" \
--store-durations --clean-durations --durations-path "$RUNNER_TEMP/test-durations.json"
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-lowest-versions-${{ matrix.shard }}
# Only `main` push runs are ever read back as the baseline (`shard_durations.py fetch`).
- name: store test durations
if: ${{ !cancelled() && github.event_name == 'push' }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ${{ env.DURATIONS_PREFIX }}${{ matrix.shard }}
path: ${{ runner.temp }}/test-durations.json
if-no-files-found: ignore
retention-days: 30
# See the matching step in the `test` job.
- name: combine coverage files
if: env.COLLECT_COVERAGE == 'true'
run: uv run --no-sync coverage combine
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.${{ matrix.python-version }}-lowest-versions-${{ matrix.shard }}
- name: store coverage files
if: env.COLLECT_COVERAGE == 'true'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: coverage-${{ matrix.python-version }}-lowest-versions-${{ matrix.shard }}
path: .coverage
include-hidden-files: true
test-temporal-latest:
name: test Temporal latest on Python 3.11
needs: classify
if: >-
needs.classify.outputs.content_only != 'true'
&& needs.classify.outputs.clai2_only != 'true'
&& needs.classify.outputs.harness_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.11"
enable-cache: true
cache-suffix: temporal-latest
- run: uv sync --extra temporal --upgrade-package temporalio
env:
UV_FROZEN: "0"
- run: >-
uv run --no-sync pytest
tests/durable_exec/temporal/test_durability.py::test_durability_rejects_unknown_activity_config_keys
tests/durable_exec/temporal/test_durability.py::test_durability_coerces_activity_config_values
test-examples:
name: test examples on ${{ matrix.python-version }}
needs: classify
if: >-
needs.classify.outputs.content_only != 'true'
&& needs.classify.outputs.clai2_only != 'true'
&& needs.classify.outputs.harness_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
# No 3.15: the examples need duckdb and datasets, which are skipped there (see `examples/pyproject.toml`).
python-version: ["3.11", "3.12", "3.13", "3.14"]
# A pull request imports the examples on the oldest and newest versions only (see the
# `test` job's matrix).
pull_request: ["${{ github.event_name == 'pull_request' && 'true' || 'false' }}"]
exclude:
- pull_request: "true"
python-version: "3.12"
- pull_request: "true"
python-version: "3.13"
env:
CI: true
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: ${{ matrix.python-version }}
enable-cache: true
cache-suffix: examples
- run: uv run --all-extras python tests/import_examples.py
# `browser-use` pins every one of its dependencies exactly, so the workspace lock excludes it
# (`exclude-dependencies` in pyproject.toml) and no other job installs it. This one installs it on
# top of the locked environment, getting the versions `pydantic-ai-harness[browser-use]` users get,
# and runs and type-checks `BrowserUse` there.
test-harness-browser-use:
name: test harness browser-use
needs: classify
if: needs.classify.outputs.content_only != 'true' && needs.classify.outputs.clai2_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 10
env:
CI: true
# No other job installs `browser-use`, so the `coverage` job sees `BrowserUse` only from here.
COVERAGE_PROCESS_START: ${{ github.workspace }}/pyproject.toml
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.harness-browser-use
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.13"
enable-cache: true
cache-suffix: harness-browser-use
- run: mkdir .coverage
- run: uv sync --all-packages --all-extras --group lint
# `--no-config`: the project's `exclude-dependencies` would otherwise drop the package too.
- run: uv pip install --no-config "browser-use>=0.13.6,<0.14"
- run: uv run --no-sync coverage run -m pytest tests/harness/browser_use
# The capability contracts skip `BrowserUse` on every other job.
- run: uv run --no-sync coverage run -m pytest tests/harness/test_capability_contracts.py -k BrowserUse
- run: uv run --no-sync pyright -p tests/harness/browser_use
env:
PYRIGHT_PYTHON_IGNORE_WARNINGS: 1
# See the matching step in the `test` job.
- name: combine coverage files
run: uv run --no-sync coverage combine
- name: store coverage files
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: coverage-harness-browser-use
path: .coverage
include-hidden-files: true
# CLAI2 pastes images through Pillow's native macOS and Windows clipboard readers and through
# `xclip` on Linux. Every other job runs on Linux and skips the opt-in native clipboard test, which
# replaces the system clipboard: safe here, where each runner's clipboard belongs to this job alone.
# Skipped on tags: a clipboard regression is caught on its PR and on `main`, and must not hold a release.
test-clai2-clipboard:
name: test clai2 clipboard on ${{ matrix.os }}
needs: classify
if: >-
github.ref_type != 'tag'
&& needs.classify.outputs.content_only != 'true'
&& needs.classify.outputs.clai2_changed == 'true'
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.CI_LINUX_RUNNER || matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
env:
CI: true
CLAI_TEST_CLIPBOARD: "1"
# Drop the workflow-level `GIT_CONFIG_*` rewrite that puts the token in GitHub URLs: with it,
# `actions/checkout`'s fetch hung on macOS runners until the job timed out. This job installs
# no Git-sourced dependency, which is all the rewrite is for.
GIT_CONFIG_COUNT: "0"
GIT_CONFIG_KEY_0: ""
GIT_CONFIG_VALUE_0: ""
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.13"
enable-cache: true
cache-suffix: clai2-clipboard
- run: uv sync --only-dev
- if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y xclip xvfb
- name: run tests
shell: bash
run: |
tests=(tests/pax/test_image_input.py tests/pax/test_image_clipboard_native.py)
if [[ "$RUNNER_OS" == Linux ]]; then
xvfb-run -a uv run --package pydantic-ai-pax pytest "${tests[@]}"
else
uv run --package pydantic-ai-pax pytest "${tests[@]}"
fi
# `WindowsWorkspaceBackend` and the PowerShell side of the harness's file and shell tools run only on
# Windows, and every other test job runs on Linux. Their coverage joins the rest in the `coverage` job.
test-windows-workspace:
name: test Windows workspace
needs: classify
if: needs.classify.outputs.content_only != 'true' && needs.classify.outputs.clai2_only != 'true'
runs-on: windows-latest
timeout-minutes: 20
env:
CI: true
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.windows-workspace
# See `test-clai2-clipboard`: no Git-sourced dependency is installed here.
GIT_CONFIG_COUNT: "0"
GIT_CONFIG_KEY_0: ""
GIT_CONFIG_VALUE_0: ""
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.13"
enable-cache: true
cache-suffix: windows-workspace
- run: mkdir .coverage
# `grep` and `list_files` run `rg`; the tests cover both its presence and its absence.
- run: choco install ripgrep --no-progress -y
- run: uv sync --only-dev
- name: run tests
run: uv run --package pydantic-ai-pax coverage run -m pytest tests/test_windows_workspace.py tests/harness/coder/test_windows.py
# The remote-sandbox fakes run commands as POSIX processes on the host, so their suites must skip here.
- name: run sandbox backend tests
run: >-
uv run --package pydantic-ai-harness --group dev
--extra coder --extra render --extra modal --extra e2b --extra sprites --extra boxd --extra opensandbox --extra daytona
coverage run -m pytest
tests/harness/boxd_sandbox tests/harness/daytona_sandbox tests/harness/e2b_sandbox tests/harness/modal_sandbox
tests/harness/opensandbox_sandbox tests/harness/render_sandbox tests/harness/sprites_sandbox
# See the matching step in the `test` job.
- name: combine coverage files
run: uv run --package pydantic-ai-pax coverage combine
- name: store coverage files
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: coverage-windows-workspace
path: .coverage
include-hidden-files: true
test-clai2-web:
name: test clai2 web UI
needs: classify
if: >-
needs.classify.outputs.content_only != 'true'
&& needs.classify.outputs.clai2_web_changed == 'true'
uses: ./.github/workflows/clai2-web.yml
with:
# `release-build` ships the bundle this builds on a tag.
npm-cache: ${{ github.ref_type == 'tag' && 'false' || 'true' }}
# The workspace locks FastMCP 4 / MCP SDK v2; `[mcp]` still allows FastMCP 3 (MCP SDK v1), so the
# tests whose behavior depends on the generation run here on its floor and on its newest release.
test-fastmcp-3:
name: test FastMCP 3 compatibility (${{ matrix.fastmcp.name }})
needs: classify
if: needs.classify.outputs.content_only != 'true' && needs.classify.outputs.clai2_only != 'true'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
fastmcp:
# The `[mcp]` extra's floor. `pydantic-ai-pax` requires FastMCP 3.4.0 or later.
- name: "3.3.0"
spec: "==3.3.0"
skip: tests/pax/
- name: latest
spec: ">=3,<4"
skip: ""
env:
CI: true
COVERAGE_PROCESS_START: ${{ github.workspace }}/pyproject.toml
# See `test-durable-exec`: the Temporal workflow deadlock detector flakes under `-n logical`.
TEMPORAL_DEBUG: "1"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.13"
enable-cache: true
cache-suffix: fastmcp-3
# The same cache `test-durable-exec`'s locked legs use; see that step.
- name: cache Temporal dev-server binary
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/temporal-dev-server
key: temporal-cli-${{ runner.os }}-${{ runner.arch }}-locked-${{ hashFiles('**/uv.lock') }}
restore-keys: |
temporal-cli-${{ runner.os }}-${{ runner.arch }}-locked-
- run: mkdir .coverage
# `--with` layers FastMCP 3 and the MCP SDK v1 it pins over the locked environment without
# mutating it. `--no-extra mcp-tasks`: that extra is FastMCP 4's tasks extension, which FastMCP 3
# doesn't use (it serves task-augmented tools itself).
# The modules are every test module that imports FastMCP or the MCP SDK, or a test server or
# helper whose behavior depends on the generation, so a new MCP test runs here without editing
# this job. A `conftest.py` match stands for its directory. A `pydantic-ai-harness`-only change
# runs only the harness modules. `tests/harness/test_history_append_only.py` is left out: it
# builds every harness capability, and under the overlay the non-MCP ones can't find their
# binaries and data files; each hosted MCP capability's own module runs here. `tests/durable_exec` runs with `BLOCKBUSTER_ENABLED=false`, as in
# `test-durable-exec`: Prefect writes its result cache from inside the event loop.
# `tests/test_conftest.py` tests BlockBuster itself, which skips in lanes that turn it off; this
# is the only BlockBuster-on lane that uploads coverage. `tests/test_history_append_only.py`
# builds the core `MCP` case, whose FastMCP import lives in `tests/capability_cases.py`, where
# the pattern doesn't look.
# `--no-extra sentence-transformers`: no MCP test module imports it, and its torch and CUDA
# wheels are about 2.6 GB of the 3.2 GB this step downloads on a uv cache miss. A slow download
# of them has run this job past `timeout-minutes` (#13931), as in `test-durable-exec`. The
# combine step drops it too, so it doesn't sync it back in.
- name: run tests
shell: bash
run: |
run=(
uv run --all-extras --no-extra mcp-tasks --no-extra sentence-transformers --all-packages
--with "fastmcp${{ matrix.fastmcp.spec }}"
--with "fastmcp-slim${{ matrix.fastmcp.spec }}"
coverage run -m pytest -n logical --dist=loadgroup
)
pattern='^[[:space:]]*(from|import) (fastmcp|mcp)([.[:space:]]|$)|MCP_SDK_V2|_mcp_server import|mcp_task_server|counting_mcp|drop_fastmcp_client_spans|tests\.mcp_server|mcp\.server\.(mcpserver|fastmcp)'
mapfile -t modules < <({
git grep -lE "$pattern" -- 'tests/**/test_*.py' 'tests/test_*.py'
git grep -lE "$pattern" -- 'tests/**/conftest.py' | sed 's|/conftest\.py$||'
echo tests/test_conftest.py
echo tests/test_history_append_only.py
} | sort -u)
durable=() other=()
for module in "${modules[@]}"; do
if [[ "$HARNESS_ONLY" == true && "$module" != tests/harness/* ]]; then continue; fi
if [[ -n "$SKIP" && "$module" == "$SKIP"* ]]; then continue; fi
if [[ "$module" == tests/harness/test_history_append_only.py ]]; then continue; fi
if [[ "$module" == tests/durable_exec/* ]]; then durable+=("$module"); else other+=("$module"); fi
done
(( ${#other[@]} )) || { echo '::error::No MCP test module matched.'; exit 1; }
printf '%s\n' "${other[@]}" "${durable[@]}"
"${run[@]}" "${other[@]}"
if (( ${#durable[@]} )); then BLOCKBUSTER_ENABLED=false "${run[@]}" "${durable[@]}"; fi
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.fastmcp-3-${{ matrix.fastmcp.name }}
HARNESS_ONLY: ${{ needs.classify.outputs.harness_only }}
SKIP: ${{ matrix.fastmcp.skip }}
# See the matching step in the `test` job. No `--with`: combining is
# environment-independent, so the FastMCP 3 overlay isn't needed.
- name: combine coverage files
run: uv run --all-extras --no-extra sentence-transformers --all-packages coverage combine
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage.fastmcp-3-${{ matrix.fastmcp.name }}
- name: store coverage files
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: coverage-fastmcp-3-${{ matrix.fastmcp.name }}
path: .coverage
include-hidden-files: true
# Live-service suites for the harness storage and AWS backends, outside `tests/` because they need
# a real server. Each runs when its capability, the dependencies, or this workflow change, and
# always on tags.
harness-integration-changes:
name: classify harness integration changes
if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || github.ref_type == 'branch'
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
outputs:
localstack: ${{ steps.detect.outputs.localstack }}
mongodb: ${{ steps.detect.outputs.mongodb }}
postgres: ${{ steps.detect.outputs.postgres }}
redis: ${{ steps.detect.outputs.redis }}
azure_durable_task: ${{ steps.detect.outputs.azure_durable_task }}
kubernetes: ${{ steps.detect.outputs.kubernetes }}
bubblewrap: ${{ steps.detect.outputs.bubblewrap }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- id: detect
env:
# A merge group has no `before`: diff it against the `main` commit it was built on.
BASE_SHA: >-
${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha
|| github.event_name == 'merge_group' && github.event.merge_group.base_sha
|| github.event.before }}
HEAD_SHA: ${{ github.sha }}
run: |
H=src/pydantic_ai_harness
# `Makefile` because the jobs below run its `integration-*` targets.
shared=(pyproject.toml uv.lock Makefile "$H/pyproject.toml" .github/workflows/ci.yml)
detect() {
local name=$1; shift
if git diff --quiet "$BASE_SHA" "$HEAD_SHA" -- "$@" "${shared[@]}"; then
echo "$name=false" >> "$GITHUB_OUTPUT"
else
status=$?
[ "$status" -eq 1 ] || exit "$status"
echo "$name=true" >> "$GITHUB_OUTPUT"
fi
}
detect localstack "$H/pydantic_ai_harness/localstack" tests/harness/localstack "$H/integration_tests/localstack"
detect mongodb "$H/pydantic_ai_harness/step_persistence" "$H/pydantic_ai_harness/media" \
tests/harness/step_persistence tests/harness/media "$H/integration_tests/mongodb"
detect postgres "$H/pydantic_ai_harness/step_persistence" "$H/pydantic_ai_harness/media" \
"$H/pydantic_ai_harness/spend_limits" tests/harness/step_persistence tests/harness/media tests/harness/spend_limits \
tests/harness/_postgres_sqlite.py "$H/integration_tests/postgres"
detect redis "$H/pydantic_ai_harness/spend_limits" tests/harness/spend_limits "$H/integration_tests/redis"
detect azure_durable_task "$H/pydantic_ai_harness/azure_durable_task" tests/harness/azure_durable_task \
"$H/integration_tests/azure_durable_task"
detect kubernetes "$H/pydantic_ai_harness/kubernetes_sandbox" tests/harness/kubernetes_sandbox \
"$H/pydantic_ai_harness/_workspace_provider.py" "$H/pydantic_ai_harness/_workspace.py" \
"$H/integration_tests/kubernetes" pydantic_ai_slim/pydantic_ai/workspaces
detect bubblewrap "$H/pydantic_ai_harness/bubblewrap_sandbox" tests/harness/bubblewrap_sandbox \
tests/harness/_fake_remote_tools.py .github/actions/install-subprocess-isolation-deps
harness-localstack-integration:
name: harness LocalStack integration tests
needs: [harness-integration-changes]
# Also skipped where `LOCALSTACK_AUTH_TOKEN` is unreadable (fork and Dependabot pull requests):
# `LOCALSTACK_REQUIRE_AUTH_TOKEN` turns a missing token into a failure, not a skip.
# Disabled until the secret is set: https://github.com/pydantic/pydantic-ai/issues/8824
if: >-
${{ false
&& always()
&& (github.ref_type == 'tag' || needs.harness-integration-changes.outputs.localstack == 'true')
&& (github.event_name != 'pull_request'
|| (github.event.pull_request.head.repo.full_name == github.repository
&& github.actor != 'dependabot[bot]')) }}
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 20
env:
LOCALSTACK_REQUIRE_AUTH_TOKEN: "1"
LOCALSTACK_AWS_CLI: aws
LOCALSTACK_IMAGE: localstack/localstack
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.14"
enable-cache: true
cache-suffix: harness-localstack
- uses: LocalStack/setup-localstack@7c8a0cb3405bc58be4c8f763f812aa000bc46303 # v0.3.2
with:
install-awslocal: "true"
skip-startup: "true"
- run: make integration-localstack
env:
# The job executes the full PR checkout, so path detection is not a security boundary.
LOCALSTACK_AUTH_TOKEN: ${{ secrets.LOCALSTACK_AUTH_TOKEN }} # zizmor: ignore[secrets-outside-env]
harness-mongodb-integration:
name: harness MongoDB integration tests
needs: [harness-integration-changes]
# No fork clause: the service below reads no secret.
if: >-
${{ always()
&& (github.ref_type == 'tag' || needs.harness-integration-changes.outputs.mongodb == 'true') }}
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 15
services:
mongodb:
# MongoDB's published image on Quay avoids Docker Hub and public ECR pull limits.
# 9.0.4+, not 8.3: older 8.x builds refuse to start on the runner's Ubuntu `7.0.0-*-azure`
# kernel (https://jira.mongodb.org/browse/SERVER-131779).
image: quay.io/mongodb/mongodb-community-server:9.0-ubuntu2204
ports:
- 27017:27017
options: >-
--health-cmd "mongosh --quiet --eval 'db.adminCommand({ping:1})'"
--health-interval 10s
--health-timeout 5s
--health-retries 10
env:
# An unreachable server is a skip locally and must be a failure here.
MONGODB_REQUIRE_LIVE: "1"
MONGODB_TEST_URL: mongodb://127.0.0.1:27017
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.14"
enable-cache: true
cache-suffix: harness-mongodb
- run: make integration-mongodb
harness-postgres-integration:
name: harness Postgres integration tests
needs: [harness-integration-changes]
# No fork clause: the service below reads no secret.
if: >-
${{ always()
&& (github.ref_type == 'tag' || needs.harness-integration-changes.outputs.postgres == 'true') }}
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 15
services:
postgres:
# Public Docker Hub pulls from GitHub-hosted runners are exempt from its pull rate limit.
image: postgres:17
ports:
- 5432:5432
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
# An unreachable server is a skip locally and must be a failure here.
POSTGRES_REQUIRE_LIVE: "1"
POSTGRES_TEST_URL: postgresql://postgres:postgres@127.0.0.1:5432/postgres
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.14"
enable-cache: true
cache-suffix: harness-postgres
- run: make integration-postgres
harness-redis-integration:
name: harness Redis integration tests
needs: [harness-integration-changes]
if: >-
${{ always()
&& (github.ref_type == 'tag' || needs.harness-integration-changes.outputs.redis == 'true') }}
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 15
services:
redis:
# Public Docker Hub pulls from GitHub-hosted runners are exempt from its pull rate limit.
image: redis:8
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 10
env:
REDIS_REQUIRE_LIVE: "1"
REDIS_TEST_URL: redis://127.0.0.1:6379
REDIS_CLUSTER_TEST_URL: redis://127.0.0.1:6380
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.14"
enable-cache: true
cache-suffix: harness-redis
# One node in cluster mode that owns every slot: enough for the server to refuse a script
# whose keys span slots with `CROSSSLOT`, which the standalone service above never does. A
# step rather than a service because a service cannot pass `redis-server` its arguments or
# assign the slots once it is up.
- name: Start a single-node Redis Cluster
timeout-minutes: 2
run: |
docker run -d --name redis-cluster -p 6380:6380 redis:8 \
redis-server --port 6380 --cluster-enabled yes --cluster-announce-ip 127.0.0.1
until docker exec redis-cluster redis-cli -p 6380 ping; do sleep 1; done
docker exec redis-cluster redis-cli -p 6380 cluster addslotsrange 0 16383
until docker exec redis-cluster redis-cli -p 6380 cluster info | grep -q cluster_state:ok; do sleep 1; done
- run: make integration-redis
harness-azure-durable-task-integration:
name: harness Azure Durable Task integration tests
needs: [harness-integration-changes]
if: >-
${{ always()
&& (github.ref_type == 'tag' || needs.harness-integration-changes.outputs.azure_durable_task == 'true') }}
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
timeout-minutes: 15
services:
dts-emulator:
# Pinned by digest: newer emulator builds have changed name validation before.
image: mcr.microsoft.com/dts/dts-emulator:v0.0.9@sha256:e883ec67fa5adec9400f7389d44c851ad5353b686b69a66139770b1f908c0f35
ports:
- 8080:8080
env:
AZURE_DURABLE_TASK_REQUIRE_LIVE: "1"
AZURE_DURABLE_TASK_TEST_ENDPOINT: 127.0.0.1:8080
AZURE_DURABLE_TASK_TEST_TASKHUB: default
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.14"
enable-cache: true
cache-suffix: harness-azure-durable-task
- run: make integration-azure-durable-task
# The unit suite runs the backend against a Python stand-in for sandboxd; this runs the same
# conformance rules against the real daemon, built from an agent-sandbox release tag. No cluster.
harness-kubernetes-integration:
name: harness Kubernetes sandbox integration tests
needs: [harness-integration-changes]
if: >-
${{ always()
&& (github.ref_type == 'tag' || needs.harness-integration-changes.outputs.kubernetes == 'true') }}
runs-on: ubuntu-latest
timeout-minutes: 15
env:
SANDBOXD_REQUIRE_LIVE: "1"
SANDBOXD_BIN: ${{ github.workspace }}/.bin/sandboxd
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: stable
cache: false
# The oldest release the docs support; the nightly live job runs the newest. `GOTOOLCHAIN=auto`
# fetches the Go version its module requires.
- run: go install sigs.k8s.io/agent-sandbox/packages/sandboxd/cmd/sandboxd@v1.0.7
env:
GOBIN: ${{ github.workspace }}/.bin
GOTOOLCHAIN: auto
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.14"
enable-cache: true
cache-suffix: harness-kubernetes
- run: make integration-kubernetes
# The `BubblewrapWorkspace` sandbox tests with a real `bwrap`: the `test` job has none, so it skips
# the tests that need one. Reproduce a failure with `BWRAP_REQUIRE_LIVE=1 make integration-bubblewrap`.
harness-bubblewrap-integration:
name: harness Bubblewrap integration tests
needs: [harness-integration-changes]
if: >-
${{ always()
&& (github.ref_type == 'tag' || needs.harness-integration-changes.outputs.bubblewrap == 'true') }}
# The pinned bubblewrap package is a noble build.
runs-on: ubuntu-24.04
timeout-minutes: 15
env:
# A `bwrap` that does not work is a skip locally and must be a failure here.
BWRAP_REQUIRE_LIVE: "1"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install bubblewrap and socat
uses: ./.github/actions/install-subprocess-isolation-deps
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.14"
enable-cache: true
cache-suffix: harness-bubblewrap
# The runner image restricts unprivileged user namespaces through AppArmor, and `bwrap` needs one.
- run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
# Shows `bwrap`'s own error, which the tests only report as a failed requirement.
- run: bwrap --ro-bind / / --unshare-all true
- run: make integration-bubblewrap
# Advisory release check: resolve the workspace at the top of the ranges this tag declares and
# run the suite there, so a release shows whether its own dependency ranges already admit an
# SDK we cannot drive (the `anthropic` 1.0.0 case). Tag refs only. No job needs it, so a
# failure turns the tag run red without delaying or stopping `check`, `deploy-docs` or the
# release jobs.
latest-versions-canary:
name: latest versions canary
if: startsWith(github.ref, 'refs/tags/')
uses: ./.github/workflows/latest-versions-canary.yml
coverage:
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
needs:
[
classify,
test,
test-all-extras,
test-durable-exec,
test-lowest-versions,
test-fastmcp-3,
test-harness-browser-use,
test-windows-workspace,
]
# A `pydantic-ai-pax`-only change skips every test job but `test`, and a skipped need would
# otherwise skip this job too. A test job
# cancelled by its own `timeout-minutes` uploads no coverage, and neither `failure()` nor `cancelled()`
# sees it, so without the `needs` check this job would report that job's lines as missing.
if: >-
${{
!failure() && !cancelled() && !contains(needs.*.result, 'cancelled')
&& needs.classify.outputs.content_only != 'true'
}}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: get coverage files
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: coverage-*
merge-multiple: true
path: .coverage
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
enable-cache: true
cache-suffix: dev
- run: uv sync --group dev --group coverage
- run: uv run --no-sync coverage combine
# Only the `pydantic-ai-pax` cells ran for a change confined to it, so they can only vouch
# for its own tests; a `pydantic-ai-harness`-only change ran the harness and CLAI 2 suites,
# which vouch for those and the harness source. The rest of the workspace is covered on the
# full path. (`pydantic-ai-pax`'s source is not measured: see `[tool.coverage.run]`.)
- name: coverage report
env:
CLAI2_ONLY: ${{ needs.classify.outputs.clai2_only }}
HARNESS_ONLY: ${{ needs.classify.outputs.harness_only }}
run: |
if [ "$CLAI2_ONLY" = true ]; then
uv run --no-sync coverage report --include='tests/pax/*'
elif [ "$HARNESS_ONLY" = true ]; then
uv run --no-sync coverage report --include='src/pydantic_ai_harness/*,tests/harness/*,tests/pax/*'
else
uv run --no-sync coverage report
fi
- run: uv run --no-sync strict-no-cover
env:
COVERAGE_FILE: ${{ github.workspace }}/.coverage/.coverage
# https://github.com/marketplace/actions/alls-green#why used for branch protection checks
check:
if: always()
needs:
- classify
- quality
- complexity
- mypy
- docs-assets
- docs-only
- content-checks
- test
- test-all-extras
- test-durable-exec
- test-lowest-versions
- test-temporal-latest
- test-examples
- test-fastmcp-3
- test-harness-browser-use
- test-clai2-clipboard
- test-windows-workspace
- test-clai2-web
- harness-integration-changes
- harness-localstack-integration
- harness-mongodb-integration
- harness-postgres-integration
- harness-redis-integration
- harness-azure-durable-task-integration
- harness-kubernetes-integration
- harness-bubblewrap-integration
- coverage
runs-on: ${{ vars.CI_LINUX_RUNNER || 'ubuntu-latest' }}
steps:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
with:
# `docs-only` covers published docs and assets; `content-checks` covers other
# non-test content. Workflow and configuration changes keep the full test matrix.
# Each reduced path must run its selected checks.
# The harness integration jobs run only when their paths change (always on tags), and
# LocalStack also skips where its secret is unreadable. `test-clai2-clipboard` runs only when
# a change reaches `pydantic-ai-pax` (always on pushes to `main`), and never on tags.
# `test-clai2-web` also follows its workflow, `pyproject.toml`, and `uv.lock`; it runs on tags.
# A `pydantic-ai-harness`-only change runs `docs-only` exactly when it changes documentation.
allowed-skips: >-
${{
needs.classify.outputs.content_only == 'true'
&& needs.classify.outputs.docs_changed == 'true'
&& 'quality,complexity,mypy,test,test-all-extras,test-durable-exec,test-lowest-versions,test-temporal-latest,test-examples,test-fastmcp-3,test-harness-browser-use,test-clai2-clipboard,test-windows-workspace,test-clai2-web,harness-integration-changes,harness-localstack-integration,harness-mongodb-integration,harness-postgres-integration,harness-redis-integration,harness-azure-durable-task-integration,harness-kubernetes-integration,harness-bubblewrap-integration,coverage,content-checks'
|| needs.classify.outputs.content_only == 'true'
&& needs.classify.outputs.docs_changed != 'true'
&& 'quality,complexity,mypy,test,test-all-extras,test-durable-exec,test-lowest-versions,test-temporal-latest,test-examples,test-fastmcp-3,test-harness-browser-use,test-clai2-clipboard,test-windows-workspace,test-clai2-web,harness-integration-changes,harness-localstack-integration,harness-mongodb-integration,harness-postgres-integration,harness-redis-integration,harness-azure-durable-task-integration,harness-kubernetes-integration,harness-bubblewrap-integration,coverage,docs-only,docs-assets'
|| needs.classify.outputs.clai2_only == 'true'
&& 'docs-only,content-checks,mypy,test-all-extras,test-durable-exec,test-lowest-versions,test-temporal-latest,test-examples,test-fastmcp-3,test-harness-browser-use,test-windows-workspace,harness-integration-changes,harness-localstack-integration,harness-mongodb-integration,harness-postgres-integration,harness-redis-integration,harness-azure-durable-task-integration,harness-kubernetes-integration,harness-bubblewrap-integration'
|| needs.classify.outputs.harness_only == 'true'
&& needs.classify.outputs.docs_changed == 'true'
&& 'content-checks,mypy,test-temporal-latest,test-examples,test-clai2-clipboard,test-clai2-web,harness-integration-changes,harness-localstack-integration,harness-mongodb-integration,harness-postgres-integration,harness-redis-integration,harness-azure-durable-task-integration,harness-kubernetes-integration,harness-bubblewrap-integration'
|| needs.classify.outputs.harness_only == 'true'
&& 'docs-only,content-checks,mypy,test-temporal-latest,test-examples,test-clai2-clipboard,test-clai2-web,harness-integration-changes,harness-localstack-integration,harness-mongodb-integration,harness-postgres-integration,harness-redis-integration,harness-azure-durable-task-integration,harness-kubernetes-integration,harness-bubblewrap-integration'
|| github.ref_type == 'tag'
&& 'docs-only,content-checks,test-clai2-clipboard,harness-integration-changes,harness-localstack-integration'
|| 'docs-only,content-checks,test-clai2-clipboard,test-clai2-web,harness-integration-changes,harness-localstack-integration,harness-mongodb-integration,harness-postgres-integration,harness-redis-integration,harness-azure-durable-task-integration,harness-kubernetes-integration,harness-bubblewrap-integration'
}}
jobs: ${{ toJSON(needs) }}
# `check` may succeed with intentionally skipped ancestors, so downstream jobs must override
# GitHub's default success check and inspect the result of their direct dependency.
# Only pydantic/pydantic-ai deploys docs and publishes releases; a copy of the repository skips
# these jobs and the post-release jobs that need them.
# Note: this should match the `deploy-docs-manual` job in manually-deploy-docs.yml
deploy-docs:
needs: [check]
if: ${{ !cancelled() && github.repository == 'pydantic/pydantic-ai' && github.ref_type == 'tag' && needs.check.result == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Generate app token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
id: app-token
with:
client-id: ${{ vars.DOCS_CLIENT_ID }}
private-key: ${{ secrets.DOCS_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: unified-docs
- name: Trigger unified-docs deployment
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
run: |
gh api repos/pydantic/unified-docs/dispatches \
--method POST \
-f event_type=docs-update \
-f "client_payload[source]=pydantic/pydantic-ai@${{ github.sha }}"
# Build wheels in an isolated job with no publish credentials. If anything in
# `uv build` (build backend, transitive build deps, restored cache) is
# compromised, the OIDC token for PyPI is in a separate job that only runs
# `pypi-publish` against the already-built artifacts.
release-build:
name: build release artifacts
needs: [check]
if: ${{ !cancelled() && github.repository == 'pydantic/pydantic-ai' && github.ref_type == 'tag' && needs.check.result == 'success' }}
runs-on: ubuntu-latest
outputs:
package-version: ${{ steps.inspect_package.outputs.version }}
harness-version: ${{ steps.inspect_package.outputs.harness-version }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
enable-cache: false
# The committed bundle lags a web UI change until `clai2-web-bundle.yml` lands its rebuild, so
# ship the bundle `test-clai2-web` built and tested from this commit. Building it here would run
# the web UI's npm dependencies in the job that builds every wheel. Replaced rather than
# overlaid, so a file the build no longer writes goes too.
- run: rm -rf src/pydantic_ai_pax/pydantic_ai_pax/builtin_plugins/web/static
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: clai2-web-static
path: src/pydantic_ai_pax/pydantic_ai_pax/builtin_plugins/web/static
- run: uv build --all-packages --no-sources
- name: Smoke-test release wheels outside the workspace
run: |
smoke_dir=$(mktemp -d)
uv venv "$smoke_dir"
uv pip install --python "$smoke_dir/bin/python" dist/*.whl
"$smoke_dir/bin/python" -I -c "import clai, pydantic_ai, pydantic_evals, pydantic_graph, pydantic_ai_harness, pydantic_ai_pax"
"$smoke_dir/bin/pai" --help
"$smoke_dir/bin/clai" --help
"$smoke_dir/bin/pax" --help
"$smoke_dir/bin/clai2" --help
"$smoke_dir/bin/python" -I src/pydantic_ai_pax/scripts/check_web_assets.py src/pydantic_ai_pax/pydantic_ai_pax/builtin_plugins/web/static
- name: Inspect package version
id: inspect_package
run: |
uv tool install --with uv-dynamic-versioning hatchling
version=$(uvx hatchling version)
echo "version=$version" >> "$GITHUB_OUTPUT"
harness_version=$(cd src/pydantic_ai_harness && uvx hatchling version)
echo "harness-version=$harness_version" >> "$GITHUB_OUTPUT"
- name: Upload distribution artifacts
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-dist
path: dist/
release:
name: publish to PyPI
needs: [release-build]
if: ${{ !cancelled() && github.repository == 'pydantic/pydantic-ai' && github.ref_type == 'tag' && needs.release-build.result == 'success' }}
runs-on: ubuntu-latest
environment:
name: release
url: https://pypi.org/project/pydantic-ai/${{ needs.release-build.outputs.package-version }}
permissions:
id-token: write
outputs:
package-version: ${{ needs.release-build.outputs.package-version }}
steps:
- name: Download distribution artifacts
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: release-dist
path: dist/
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1
with:
skip-existing: true
gh-aw-engine-pin:
name: gh-aw engine / read pin
needs: [release]
if: ${{ !cancelled() && needs.release.result == 'success' }}
runs-on: ubuntu-latest
timeout-minutes: 10
# `uv run --script` resolves the guard script's dependencies from PyPI without a lockfile, so it
# runs in its own job, on its own runner, with no write token: a step can extend `GITHUB_PATH`
# for the steps after it, so a separate step would not keep a dependency away from the token.
permissions:
contents: read
# The workflow-level `GIT_CONFIG_*` would otherwise carry the token here. Nothing here installs
# from git.
env:
GIT_CONFIG_COUNT: '0'
GIT_CONFIG_KEY_0: ''
GIT_CONFIG_VALUE_0: ''
steps:
# Consumers compile the definition from the default branch, which may have moved past the tag.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
enable-cache: false
- id: engine
run: |
version=$(uv run --script src/pydantic_ai_harness/scripts/gh_aw_engine_version.py)
# `src/pydantic_ai_harness/gh-aw/pydantic.md` pins the `pydantic-ai-harness` release a generated
# gh-aw workflow installs, and consumers compile the definition straight from the default branch.
# Shipping a bump is therefore an ordinary pull request against that file, and this job publishes
# nothing: when the harness release just cut is not the release the definition names, it opens
# that pull request for a maintainer to merge when the released version is newer than the pin,
# and closes the pin bumps it opened for earlier releases.
#
# The writes use a `pydantic-docs` App installation token, not GITHUB_TOKEN: GitHub starts no
# workflow runs for a pull request opened with GITHUB_TOKEN, so the pull request would arrive
# without this repository's required checks, including the `--published` lint that confirms
# PyPI serves the new pin.
gh-aw-engine-pin-bump:
name: gh-aw engine / pin bump
needs: [release-build, gh-aw-engine-pin]
if: ${{ !cancelled() && needs.gh-aw-engine-pin.result == 'success' }}
runs-on: ubuntu-latest
timeout-minutes: 10
permissions: {}
env:
# The harness releases as `0.<minor>.<patch>` with every tag, so the tag name is not
# the version the engine installs.
RELEASED: ${{ needs.release-build.outputs.harness-version }}
steps:
- name: Check whether the release moved past the definition
id: guard
run: |
# The harness version carries no pre-release stage, so the tag is what tells a final
# release apart, and a pre-release is not a pin consumers should move to.
if ! [[ "$GITHUB_REF_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "${GITHUB_REF_NAME} is not a final release."
exit 0
fi
echo "bump=true" >> "$GITHUB_OUTPUT"
- name: Generate app token
if: steps.guard.outputs.bump == 'true'
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
id: app-token
with:
client-id: ${{ vars.DOCS_CLIENT_ID }}
private-key: ${{ secrets.DOCS_APP_PRIVATE_KEY }}
owner: pydantic
repositories: pydantic-ai
permission-contents: write
permission-pull-requests: write
- name: Open the pin bump pull request
if: steps.guard.outputs.bump == 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
GH_REPO: ${{ github.repository }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
run: |
definition=src/pydantic_ai_harness/gh-aw/pydantic.md
branch="gh-aw-engine-pin-${RELEASED}"
title="Bump the gh-aw engine pin to \`${RELEASED}\`"
# `--search` matches words rather than the phrase, so it narrows the
# listing and the exact title is compared here.
existing_titles=$(gh pr list --state open --search "gh-aw engine pin ${RELEASED} in:title" \
--json title --jq '.[].title')
if grep -qxF "${title}" <<< "$existing_titles"; then
echo "An open pull request already bumps the pin: ${title}"
exit 0
fi
base_sha=$(gh api "repos/${GH_REPO}/git/ref/heads/${DEFAULT_BRANCH}" --jq .object.sha)
current="${RUNNER_TEMP}/pydantic.md"
bumped="${RUNNER_TEMP}/pydantic.bumped.md"
gh api "repos/${GH_REPO}/contents/${definition}?ref=${base_sha}" \
-H 'Accept: application/vnd.github.raw' > "$current"
# Only the frontmatter's `engine.version`: `runtimes.python.version` is another
# `version:` key, and the body's usage example opens a second `engine:` block.
if ! PINNED=$(awk '
NR == 1 { frontmatter = ($0 == "---") }
NR > 1 && frontmatter && $0 == "---" { frontmatter = 0 }
frontmatter && /^[^ #]/ { engine = ($0 == "engine:") }
frontmatter && engine && /^ version:/ {
value = $0
sub(/^ version:[[:space:]]*/, "", value)
if (value ~ /^['\''"]/) {
quote = substr(value, 1, 1)
if (substr(value, length(value), 1) != quote) exit 1
value = substr(value, 2, length(value) - 2)
}
print value
found = 1
exit
}
END { if (!found) exit 1 }
' "$current"); then
echo "::error::${definition} on ${DEFAULT_BRANCH} has no readable engine.version line in its frontmatter."
exit 1
fi
if ! [[ "$PINNED" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ && "$RELEASED" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::error::Cannot compare gh-aw engine versions: expected numeric major.minor.patch values, got '${PINNED}' and '${RELEASED}'."
exit 1
fi
if ! awk -v pinned="$PINNED" -v released="$RELEASED" 'BEGIN {
split(pinned, p, "[.]")
split(released, r, "[.]")
for (i = 1; i <= 3; i++) {
if (r[i] + 0 > p[i] + 0) exit 0
if (r[i] + 0 < p[i] + 0) exit 1
}
exit 1
}'; then
echo "${definition} on ${DEFAULT_BRANCH} already pins ${PINNED} or a newer version."
exit 0
fi
if ! awk -v released="$RELEASED" '
NR == 1 { frontmatter = ($0 == "---") }
NR > 1 && frontmatter && $0 == "---" { frontmatter = 0 }
frontmatter && /^[^ #]/ { engine = ($0 == "engine:") }
frontmatter && engine && /^ version:/ { $0 = " version: \"" released "\""; found = 1 }
{ print }
END { exit !found }
' "$current" > "$bumped"; then
echo "::error::${definition} on ${DEFAULT_BRANCH} has no engine.version line in its frontmatter."
exit 1
fi
if cmp -s "$current" "$bumped"; then
echo "${definition} on ${DEFAULT_BRANCH} already pins ${RELEASED}."
exit 0
fi
# A rerun after a failure further down finds the branch an earlier attempt created,
# and finishes the pull request from it instead of stopping.
if ! gh api "repos/${GH_REPO}/git/ref/heads/${branch}" --silent 2>/dev/null; then
gh api "repos/${GH_REPO}/git/refs" -f ref="refs/heads/${branch}" -f sha="${base_sha}" --silent
fi
on_branch="${RUNNER_TEMP}/pydantic.branch.md"
gh api "repos/${GH_REPO}/contents/${definition}?ref=${branch}" \
-H 'Accept: application/vnd.github.raw' > "$on_branch"
if ! cmp -s "$on_branch" "$bumped"; then
file_sha=$(gh api "repos/${GH_REPO}/contents/${definition}?ref=${branch}" --jq .sha)
gh api -X PUT "repos/${GH_REPO}/contents/${definition}" \
-f branch="${branch}" \
-f sha="${file_sha}" \
-f message="chore: bump the gh-aw engine pin to ${RELEASED}" \
-f content="$(base64 -w0 "$bumped")" \
--silent
fi
# A heredoc rather than an inline `--body`: the body is Markdown with
# blank lines and backticks, and only the variables are meant to expand.
cat > "${RUNNER_TEMP}/pin-bump.md" <<EOF
\`engine.version\` in \`${definition}\` is the \`pydantic-ai-harness\` release that generated gh-aw workflows install. This bumps it from \`${PINNED}\` to \`${RELEASED}\`, which the [\`${GITHUB_REF_NAME}\` release run](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}) that opened this pull request just published.
Consumers compile the definition from the default branch, so merging this ships the new pin on their next recompile. CI's \`gh_aw_engine_version.py --published\` check confirms PyPI serves \`${RELEASED}\`.
EOF
gh pr create --head "${branch}" --base "${DEFAULT_BRANCH}" --title "${title}" \
--label chore --label pkg:harness --body-file "${RUNNER_TEMP}/pin-bump.md"
# A step of its own so that a rerun still reaches it: the step above stops once the pull
# request it would open exists.
- name: Close the superseded pin bump pull requests
if: steps.guard.outputs.bump == 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
GH_REPO: ${{ github.repository }}
run: |
# The author and the branch name together pick out the pull requests this job opened:
# the App opens other pull requests too, and people can name a branch anything.
# `--head` reads the pull request list, while `--app` goes through search, whose index
# can lag behind the pull request the step above opened seconds ago.
current=$(gh pr list --state open --head "gh-aw-engine-pin-${RELEASED}" --json number,author \
--jq '.[] | select(.author.login == "app/pydantic-docs") | .number')
if [[ -z "$current" ]]; then
echo "No open pull request bumps the gh-aw engine pin to ${RELEASED}."
exit 0
fi
# Earlier release runs opened the pull requests this closes, so search has indexed them.
pin_prs=$(gh pr list --state open --app pydantic-docs --limit 100 \
--json number,headRefName --jq '.[] | [.number, .headRefName] | @tsv')
# Only lower versions: a patch release for an older minor can follow a newer release.
superseded=$(awk -F '\t' -v released="$RELEASED" '
BEGIN { split(released, r, "[.]") }
$2 ~ /^gh-aw-engine-pin-[0-9]+\.[0-9]+\.[0-9]+$/ {
version = $2
sub(/^gh-aw-engine-pin-/, "", version)
split(version, p, "[.]")
for (i = 1; i <= 3; i++) {
if (r[i] + 0 > p[i] + 0) { print $1; next }
if (r[i] + 0 < p[i] + 0) next
}
}
' <<< "$pin_prs")
for number in $superseded; do
gh pr close "$number" --comment "Superseded by #${current}, which bumps the pin to \`${RELEASED}\`."
done