diff --git a/.bazelignore b/.bazelignore index e69de29bb..30648d6aa 100644 --- a/.bazelignore +++ b/.bazelignore @@ -0,0 +1,2 @@ +.local +.gocache diff --git a/.gitignore b/.gitignore index 3718e7ab6..7be0b3f95 100644 --- a/.gitignore +++ b/.gitignore @@ -17,4 +17,8 @@ /output/ # ignore user bazelrc .bazelrc.user -*.log \ No newline at end of file +*.log +.gocache/ +/.gotmp + +/python/Dockerfile diff --git a/BUILD b/BUILD index 9063b4f90..ff87f5d1e 100644 --- a/BUILD +++ b/BUILD @@ -4,11 +4,17 @@ load("//java:config.bzl", "JAVA_ARCHITECTURES", "JAVA_DISTROS", "JAVA_MAJOR_VERS load("//nodejs:config.bzl", "NODEJS_ARCHITECTURES", "NODEJS_DISTROS", "NODEJS_MAJOR_VERSIONS") load("//private/oci:defs.bzl", "sign_and_push_all") load("//private/tools/lifecycle:defs.bzl", "attach_lifecycle_tags") +load("//python:config.bzl", PBS_PYTHON_ARCHITECTURES = "PYTHON_ARCHITECTURES", PBS_PYTHON_DISTROS = "PYTHON_DISTROS", PBS_PYTHON_MAJOR_VERSIONS = "PYTHON_MAJOR_VERSIONS") load("//python3:config.bzl", "PYTHON_ARCHITECTURES", "PYTHON_DISTROS") load("//static:config.bzl", "STATIC_ARCHITECTURES", "STATIC_DISTROS") package(default_visibility = ["//visibility:public"]) +exports_files([ + "MODULE.bazel", + "knife", +]) + DEFAULT_DISTRO = "debian13" VARIANTS = [ @@ -196,6 +202,37 @@ NODEJS |= { for (tag_base, debug_mode, user) in VARIANTS } +############### +# PYTHON (PBS) # +############### +PYTHON = { + "{REGISTRY}/{PROJECT_ID}/python" + version + "-" + distro + ":" + tag_base + "-" + arch: "//python:python" + version.replace(".", "") + debug_mode + "_" + user + "_" + arch + "_" + distro + for version in PBS_PYTHON_MAJOR_VERSIONS + for distro in PBS_PYTHON_DISTROS + for arch in PBS_PYTHON_ARCHITECTURES[distro][version] + for (tag_base, debug_mode, user) in VARIANTS +} + +PYTHON |= { + "{REGISTRY}/{PROJECT_ID}/python" + version + "-" + distro + ":" + tag_base: "//python:python" + version.replace(".", "") + debug_mode + "_" + user + "_" + distro + for version in PBS_PYTHON_MAJOR_VERSIONS + for distro in PBS_PYTHON_DISTROS + for (tag_base, debug_mode, user) in VARIANTS +} + +PYTHON |= { + "{REGISTRY}/{PROJECT_ID}/python" + version + ":" + tag_base + "-" + arch: "//python:python" + version.replace(".", "") + debug_mode + "_" + user + "_" + arch + "_" + DEFAULT_DISTRO + for version in PBS_PYTHON_MAJOR_VERSIONS + for arch in PBS_PYTHON_ARCHITECTURES[DEFAULT_DISTRO][version] + for (tag_base, debug_mode, user) in VARIANTS +} + +PYTHON |= { + "{REGISTRY}/{PROJECT_ID}/python" + version + ":" + tag_base: "//python:python" + version.replace(".", "") + debug_mode + "_" + user + "_" + DEFAULT_DISTRO + for version in PBS_PYTHON_MAJOR_VERSIONS + for (tag_base, debug_mode, user) in VARIANTS +} + ############### # JAVA_BASE # ############### @@ -270,6 +307,8 @@ ALL |= PYTHON3 ALL |= NODEJS +ALL |= PYTHON + ALL |= JAVA_BASE ALL |= JAVA diff --git a/MODULE.bazel b/MODULE.bazel index 4954f049b..bdbc9ccde 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -55,5 +55,10 @@ node = use_extension("//private/extensions:node.bzl", "node") node.archive() use_repo(node, "node_versions", "nodejs22_amd64", "nodejs22_arm", "nodejs22_arm64", "nodejs22_ppc64le", "nodejs22_s390x", "nodejs24_amd64", "nodejs24_arm64", "nodejs24_ppc64le", "nodejs24_s390x", "nodejs26_amd64", "nodejs26_arm64", "nodejs26_ppc64le", "nodejs26_s390x") +### PYTHON ### +py = use_extension("//private/extensions:python.bzl", "python") +py.archive() +use_repo(py, "python314_amd64", "python314_arm64", "python314_riscv64", "python314_s390x", "python315_amd64", "python315_arm64", "python315_riscv64", "python315_s390x", "python_versions") + ### DEBIAN ### include("//private/repos/deb:deb.MODULE.bazel") diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 792ef1bd0..bfbe110f3 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -645,6 +645,153 @@ "recordedRepoMappingEntries": [] } }, + "//private/extensions:python.bzl%python": { + "general": { + "bzlTransitiveDigest": "1IHZsLz+alD2SaG3I6UuDQ64bZjD1w3Km5Zx3arLqPA=", + "usagesDigest": "c4TzkyPW7cDJnkOuzqF5JKto51Qz2U++tuhW9H+H22w=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "python314_amd64": { + "repoRuleId": "@@//private/extensions:python.bzl%python_archive", + "attributes": { + "sha256": "c2ff2e97422f5d3896a16e0317fd212ba977bbf2688d93a6f7a03d817506bd30", + "strip_prefix": "python/", + "urls": [ + "https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.14.10+20261110-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz" + ], + "version": "3.14.10+20261110", + "python_version": "3.14", + "architecture": "amd64" + } + }, + "python314_arm64": { + "repoRuleId": "@@//private/extensions:python.bzl%python_archive", + "attributes": { + "sha256": "38fd50f07170adc29d481913d1c30b17ecb538fbe290315fe1f83d84fdd5b694", + "strip_prefix": "python/", + "urls": [ + "https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.14.10+20261110-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz" + ], + "version": "3.14.10+20261110", + "python_version": "3.14", + "architecture": "arm64" + } + }, + "python314_s390x": { + "repoRuleId": "@@//private/extensions:python.bzl%python_archive", + "attributes": { + "sha256": "e70f5f99dba26665dad0e43b521b44d080a33790bf5805872c676736462c2bb0", + "strip_prefix": "python/", + "urls": [ + "https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.14.10+20261110-s390x-unknown-linux-gnu-install_only_stripped.tar.gz" + ], + "version": "3.14.10+20261110", + "python_version": "3.14", + "architecture": "s390x" + } + }, + "python314_riscv64": { + "repoRuleId": "@@//private/extensions:python.bzl%python_archive", + "attributes": { + "sha256": "e7225b7b4c2d61ca4e241423fe7ee8784cd40313c62169595eebafb8a553fed8", + "strip_prefix": "python/", + "urls": [ + "https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.14.10+20261110-riscv64-unknown-linux-gnu-install_only_stripped.tar.gz" + ], + "version": "3.14.10+20261110", + "python_version": "3.14", + "architecture": "riscv64" + } + }, + "python315_amd64": { + "repoRuleId": "@@//private/extensions:python.bzl%python_archive", + "attributes": { + "sha256": "ad23d1b73fac26440b0306ae06911031344c49a90ec19716c8362e7fa40cae43", + "strip_prefix": "python/", + "urls": [ + "https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.15.2+20261110-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz" + ], + "version": "3.15.2+20261110", + "python_version": "3.15", + "architecture": "amd64" + } + }, + "python315_arm64": { + "repoRuleId": "@@//private/extensions:python.bzl%python_archive", + "attributes": { + "sha256": "d1367a6c3cd86a9e35712072841f1376859f3b47a2a54e224421a0f9fd169047", + "strip_prefix": "python/", + "urls": [ + "https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.15.2+20261110-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz" + ], + "version": "3.15.2+20261110", + "python_version": "3.15", + "architecture": "arm64" + } + }, + "python315_s390x": { + "repoRuleId": "@@//private/extensions:python.bzl%python_archive", + "attributes": { + "sha256": "87228faf46bedc27fd6b8a7bcdc7ff520c86ca1b7c59eee9f14a4cf12b9d0d86", + "strip_prefix": "python/", + "urls": [ + "https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.15.2+20261110-s390x-unknown-linux-gnu-install_only_stripped.tar.gz" + ], + "version": "3.15.2+20261110", + "python_version": "3.15", + "architecture": "s390x" + } + }, + "python315_riscv64": { + "repoRuleId": "@@//private/extensions:python.bzl%python_archive", + "attributes": { + "sha256": "b05b96b52b0833443c8340800e957406dbfb5db2fe2f4af6e546db9b2ae1056a", + "strip_prefix": "python/", + "urls": [ + "https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.15.2+20261110-riscv64-unknown-linux-gnu-install_only_stripped.tar.gz" + ], + "version": "3.15.2+20261110", + "python_version": "3.15", + "architecture": "riscv64" + } + }, + "python_versions": { + "repoRuleId": "@@//private/extensions:python.bzl%python_versions_repo", + "attributes": { + "versions": { + "3.14_amd64": "3.14.10", + "3.14_arm64": "3.14.10", + "3.14_s390x": "3.14.10", + "3.14_riscv64": "3.14.10", + "3.15_amd64": "3.15.2", + "3.15_arm64": "3.15.2", + "3.15_s390x": "3.15.2", + "3.15_riscv64": "3.15.2" + } + } + } + }, + "moduleExtensionMetadata": { + "explicitRootModuleDirectDeps": [ + "python_versions", + "python314_amd64", + "python314_arm64", + "python314_s390x", + "python314_riscv64", + "python315_amd64", + "python315_arm64", + "python315_s390x", + "python315_riscv64" + ], + "explicitRootModuleDirectDevDeps": [], + "useAllRepos": "NO", + "reproducible": false + }, + "recordedRepoMappingEntries": [] + } + }, "//private/extensions:version.bzl%version": { "general": { "bzlTransitiveDigest": "a4FYxHYUQ822kcAcKD5tzEjksar43fkO3cC2oeyx6zA=", diff --git a/knife b/knife index e7e2a1ab0..7f90f0900 100755 --- a/knife +++ b/knife @@ -175,6 +175,65 @@ function cmd_lint () { buildifier -mode=$mode $(find . -type f \( -name 'BUILD*' -o -name 'WORKSPACE*' -o -name '*.bzl' \)) } +function cmd_update_python_archives () { + if ! which jq > /dev/null; then + echo "🧱 No jq executable was found" + exit 1 + fi + if ! which curl > /dev/null; then + echo "🧱 No curl executable was found" + exit 1 + fi + + VERBOSE=0 + DRY_RUN=0 + for arg in "$@"; do + case "$arg" in + --verbose) + VERBOSE=1 + ;; + --dry-run) + DRY_RUN=1 + ;; + *) + echo "unknown option: $arg" + exit 1 + ;; + esac + done + export VERBOSE DRY_RUN + + source knife.d/update_python_archives.sh + # A separate shell keeps errexit active inside the updater despite this condition. + if ! out=$(bash -c 'source knife.d/update_python_archives.sh; generate_python_archives'); then + case "$out" in + *MUTATED_PARTIAL*) + echo "update failed mid-mutation; files may be partially updated." >&2 + echo "Restore the affected files from version control before retrying." >&2 + ;; + *) + echo "update failed; no files were mutated (pre-flight validation)." >&2 + ;; + esac + return 1 + fi + if [ "$DRY_RUN" = 0 ] && ! bash -c 'source knife.d/update_python_archives.sh; update_test_versions_python'; then + echo "Python version testdata update failed. Fix the error and rerun the updater." >&2 + return 1 + fi + if [ "$out" = "NO_CHANGE" ]; then + echo "python archives are up to date" + return 0 + fi + if [ "$DRY_RUN" = 1 ]; then + echo "dry-run: no files written" + return 0 + fi + echo "updated python archives to release $out" + # The extension changed; refresh the lockfile before building. + echo "Refresh the lockfile before building." >&2 +} + function cmd_update_node_archives () { if ! which jq > /dev/null; then echo "🧱 No jq executable was found" @@ -305,8 +364,11 @@ update-node-archives) update-node-keys) cmd_update_node_keys ;; +update-python-archives) + cmd_update_python_archives "${@:2}" + ;; ~~nocmd) # no command provided - echo "provide a command: lock, update-snapshots, github-update-snapshots, update-non-snapshots, test, deb-versions, update-node-archives, update-node-keys" + echo "provide a command: lock, update-snapshots, github-update-snapshots, update-non-snapshots, test, deb-versions, update-node-archives, update-node-keys, update-python-archives" exit 1 ;; *) # unknown command diff --git a/knife.d/BUILD.bazel b/knife.d/BUILD.bazel new file mode 100644 index 000000000..d3b284dd7 --- /dev/null +++ b/knife.d/BUILD.bazel @@ -0,0 +1,4 @@ +exports_files([ + "update_java_versions.sh", + "update_python_archives.sh", +]) diff --git a/knife.d/update_python_archives.sh b/knife.d/update_python_archives.sh new file mode 100644 index 000000000..52558228c --- /dev/null +++ b/knife.d/update_python_archives.sh @@ -0,0 +1,418 @@ +set -o pipefail -o errexit -o nounset + +# Copyright 2026 Google Inc. All rights reserved. + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Functions used by knife to update python-build-standalone archives. +# +# Reads the Python matrix and pinned versions, queries the latest PBS release, +# then rewrites archive and version data when needed. +# +# An update is triggered when the CPython patch moves or the PBS release tag +# changes under an unchanged patch, indicating rebuilt native libraries. + +PYTHON_TRIPLES=( + "amd64=x86_64-unknown-linux-gnu" + "arm64=aarch64-unknown-linux-gnu" + "s390x=s390x-unknown-linux-gnu" + "riscv64=riscv64-unknown-linux-gnu" +) + +# Use a temporary file for portable in-place editing on BSD and GNU sed. +sed_inplace() { # $1 = sed expression, $2 = file + local tmp mode + tmp="${2}.tmp.$$" + sed -e "$1" "$2" > "$tmp" || { rm -f "$tmp"; return 1; } + if cmp -s "$2" "$tmp"; then + rm -f "$tmp" + return 0 + fi + mode=$(stat -c %a "$2" 2>/dev/null || stat -f %Lp "$2") + chmod "$mode" "$tmp" + mv "$tmp" "$2" +} + +# Print "_ " for each matrix entry. +function get_python_versions() { + sed -n '/python_versions_repo(/,/^ )$/p' private/extensions/python.bzl \ + | grep -oE '"[0-9]+\.[0-9]+_[a-z0-9]+": "[0-9]+\.[0-9]+\.[0-9]+(b[0-9]+|rc[0-9]+)?"' \ + | sed -E 's/"([^"]+)": "([^"]+)"/\1 \2/' +} + +# Print the matrix's minor versions, one per line. +function get_python_minors() { + python3 -c 'import ast, re, sys +try: + minors = ast.literal_eval(sys.argv[1]) + if not isinstance(minors, list) or not minors or any(not isinstance(v, str) or not re.fullmatch(r"3\.[0-9]+", v) for v in minors): + raise ValueError() +except (SyntaxError, ValueError): + sys.exit("invalid PYTHON_MAJOR_VERSIONS in python/config.bzl; expected a list of 3.x minors") +print("\n".join(minors))' "$(sed -n 's/^PYTHON_MAJOR_VERSIONS = //p' python/config.bzl)" +} + +# Print the architectures for a minor, one per line. +function get_python_archs() { + local minor="$1" value + # A missing minor returns no architectures; the caller reuses the previous + # minor's list for a newly detected minor. + value=$(grep -F "\"${minor}\": [" python/config.bzl | sed 's/^[^[]*//; s/,[[:space:]]*$//' || true) + [ -n "$value" ] || return 0 + python3 -c 'import ast, sys +try: + archs = ast.literal_eval(sys.argv[1]) + if not isinstance(archs, list) or not archs or any(not isinstance(v, str) or not v for v in archs) or len(set(archs)) != len(archs): + raise ValueError() +except (SyntaxError, ValueError): + sys.exit("invalid architectures for " + sys.argv[2] + " in python/config.bzl") +print("\n".join(archs))' "$value" "$minor" +} + +function triple_for_arch() { + local entry + for entry in "${PYTHON_TRIPLES[@]}"; do + [[ "$entry" == "$1="* ]] && echo "${entry#*=}" && return 0 + done + return 1 +} + +# Print the current version for a minor, optionally for a specific architecture. +function current_version() { + get_python_versions | awk -v minor="$1" -v arch="${2:-}" ' + arch != "" && $1 == minor "_" arch { print $2 } + arch == "" && index($1, minor "_") == 1 && !found { print $2; found = 1 } + ' +} + +# Print the full pinned version (patch + PBS release tag) for a minor and +# architecture, if any. +# A tag-only bump (same patch, rebuilt native libs) must trigger an update. +function pinned_version() { + local minor="$1" arch="$2" short + short=$(echo "$minor" | tr -d '.') + awk -v name="python${short}_${arch}" -v field="${3:-version}" ' + $0 ~ ("name = \"" name "\"") { found = 1 } + found && /^[[:space:]]*\)$/ { exit } + found && $0 ~ ("^[[:space:]]*" field " = ") { + sub(/.*= "/, ""); sub(/".*/, ""); print; exit + } + ' private/extensions/python.bzl +} + +# Python finals sort after their beta/RC builds, unlike sort -V. +function latest_python_version() { + python3 -c 'import re, sys +def key(version): + major, minor, patch, stage, number = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)(?:(b|rc)(\d+))?", version).groups() + return (int(major), int(minor), int(patch), {"b": 0, "rc": 1, None: 2}[stage], int(number or 0)) +versions = sys.stdin.read().split() +print(max(versions, key=key) if versions else "")' +} + +# Rewrite archives, versions, metadata, and repository visibility. Print the +# new release tag on success or "NO_CHANGE" when current. +function generate_python_archives() { + local latest_release sha256sums + local minors minor arch triple version sha python_short arch_anchor matrix_min published latest_minor + local version_re minor_re minor_version current_sha pinned_patch + local -a archive_blocks versions_entries metadata_deps changes repos + local changed=0 verbose=${VERBOSE:-0} dry_run=${DRY_RUN:-0} current + local module_tmp="" repos_sorted module_line current_module_line module_changed=0 + + # Tests can supply release data through PBS_RELEASE_FILE and + # PBS_SHA256SUMS_FILE; otherwise use the live release files. + if [ -n "${PBS_RELEASE_FILE:-}" ] && [ -n "${PBS_SHA256SUMS_FILE:-}" ]; then + latest_release=$(jq -er '.tag' "$PBS_RELEASE_FILE") || return 1 + sha256sums=$(cat "$PBS_SHA256SUMS_FILE") || return 1 + else + # Prefer PBS's machine-readable release file; fall back to the API if it is unavailable. + if ! latest_release=$(curl -fsSL https://raw.githubusercontent.com/astral-sh/python-build-standalone/latest-release/latest-release.json 2>/dev/null | jq -er '.tag'); then + latest_release=$(curl -fsSL https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest | jq -er '.tag_name') || return 1 + fi + sha256sums=$(curl -fsSL "https://github.com/astral-sh/python-build-standalone/releases/download/${latest_release}/SHA256SUMS") || return 1 + fi + [[ "$latest_release" =~ ^[0-9]{8}$ ]] || { echo "invalid PBS release tag: ${latest_release}" >&2; return 1; } + [ -n "$sha256sums" ] || { echo "no SHA256SUMS for ${latest_release}" >&2; exit 1; } + + local -a minors + minors=() + local minors_tmp archs original_minors + minors_tmp=$(mktemp) + get_python_minors > "$minors_tmp" + while IFS= read -r minor; do minors+=("$minor"); done < "$minors_tmp" + rm -f "$minors_tmp" + [ ${#minors[@]} -gt 0 ] || { echo "no minors parsed from python/config.bzl" >&2; exit 1; } + + # Sort and deduplicate to avoid depending on matrix order. + original_minors=${minors[*]} + read -r -a minors <<< "$(printf '%s\n' "${minors[@]}" | sort -uV | paste -sd ' ' -)" + if [ "$original_minors" != "${minors[*]}" ]; then + changed=1 + changes+=("normalize Python minor matrix") + fi + arch_anchor=${minors[${#minors[@]} - 1]} + matrix_min=${minors[0]} + + # Find stable PBS minors from amd64 assets. Prereleases are excluded by + # requiring 3.X.Y. The matrix is a contiguous support window; fill published + # minors above its oldest entry. + published=$(echo "$sha256sums" \ + | { grep -oE "cpython-3\\.[0-9]+\\.[0-9]+\\+${latest_release}-x86_64-unknown-linux-gnu-install_only_stripped\\.tar\\.gz$" || true; } \ + | sed -E 's/cpython-(3\.[0-9]+)\.[0-9]+.*/\1/' | sort -uV) + local fill fill_m + fill=() + for fill_m in $published; do + if [ "$fill_m" != "$matrix_min" ] \ + && [ "$(printf '%s\n' "$matrix_min" "$fill_m" | sort -V | tail -1)" = "$fill_m" ] \ + && [[ " ${minors[*]} " != *" $fill_m "* ]]; then + fill+=("$fill_m") + fi + done + if [ ${#fill[@]} -gt 0 ]; then + echo "new stable minor(s) detected: ${fill[*]}" >&2 + for fill_m in "${fill[@]}"; do + minors+=("$fill_m") + changes+=("add minor ${fill_m}") + done + read -r -a minors <<< "$(printf '%s\n' "${minors[@]}" | sort -uV | paste -sd ' ' -)" + # A missing matrix entry is a change even if version data already exists. + changed=1 + fi + latest_minor=$arch_anchor + + for minor in "${minors[@]}"; do + minor_re=${minor//./\\.} + minor_version="" + python_short=$(echo "$minor" | tr -d '.') + archs=$(get_python_archs "$minor") + version_re='[0-9]+(b[0-9]+|rc[0-9]+)?' + if [ ${#fill[@]} -gt 0 ] && [[ " ${fill[*]} " == *" $minor "* ]]; then + version_re='[0-9]+' + if [ -z "$archs" ]; then + archs=$(get_python_archs "$latest_minor") + fi + elif [[ "$(current_version "$minor")" =~ ^3\.[0-9]+\.[0-9]+$ ]]; then + version_re='[0-9]+' + fi + [ -n "$archs" ] || { echo "no archs for ${minor} in python/config.bzl" >&2; exit 1; } + while IFS= read -r arch; do + triple=$(triple_for_arch "$arch") || { echo "no triple for ${arch}" >&2; exit 1; } + version=$(echo "$sha256sums" \ + | { grep -oE "cpython-${minor_re}\\.${version_re}\\+${latest_release}-${triple}-install_only_stripped\\.tar\\.gz$" || true; } \ + | sed -E "s/cpython-(${minor_re}\\.${version_re})\\+.*/\\1/" | latest_python_version) + [ -n "$version" ] || { echo "required matrix entry ${minor} ${arch} has no install_only_stripped PBS asset in ${latest_release}" >&2; exit 1; } + [ -z "$minor_version" ] || [ "$minor_version" = "$version" ] || { echo "inconsistent Python versions for ${minor}: ${minor_version} and ${version} (${arch})" >&2; return 1; } + minor_version=$version + sha=$(echo "$sha256sums" | awk -v asset="cpython-${version}+${latest_release}-${triple}-install_only_stripped.tar.gz" '$2 == asset || $2 == "*" asset { print $1 }') + [[ "$sha" =~ ^[0-9a-f]{64}$ ]] || { echo "missing, duplicate or invalid sha256 for ${version} ${triple}" >&2; return 1; } + + current=$(current_version "$minor" "$arch") + pinned=$(pinned_version "$minor" "$arch") + current_sha=$(pinned_version "$minor" "$arch" sha256) + new_full="${version}+${latest_release}" + if [[ "$pinned" =~ ^3\.[0-9]+\.[0-9]+(b[0-9]+|rc[0-9]+)?\+[0-9]{8}$ ]]; then + pinned_patch=${pinned%+*} + if [[ "${pinned##*+}" > "$latest_release" ]] || + { [ "$pinned_patch" != "$version" ] && + [ "$(printf '%s\n' "$pinned_patch" "$version" | latest_python_version)" = "$pinned_patch" ]; }; then + echo "refusing to downgrade Python ${minor} ${arch}: ${pinned} -> ${new_full}" >&2 + return 1 + fi + fi + if [ "$verbose" = 1 ]; then + if [ "$current" = "$version" ] && [ "$pinned" = "$new_full" ] && [ "$current_sha" = "$sha" ]; then + echo " ${minor} ${arch}: ${pinned} (unchanged)" >&2 + else + echo " ${minor} ${arch}: ${pinned:-} -> ${new_full} (update)" >&2 + fi + fi + # Update when the patch or PBS release tag moves. + if [ "$current" != "$version" ] || [ "$pinned" != "$new_full" ] || [ "$current_sha" != "$sha" ]; then + changed=1 + changes+=("update ${minor} ${arch}: ${pinned:-} -> ${new_full}") + fi + + archive_blocks+=(" python_archive( + name = \"python${python_short}_${arch}\", + sha256 = \"${sha}\", + strip_prefix = \"python/\", + urls = [\"https://github.com/astral-sh/python-build-standalone/releases/download/${latest_release}/cpython-${version}+${latest_release}-${triple}-install_only_stripped.tar.gz\"], + version = \"${version}+${latest_release}\", + python_version = \"${minor}\", + architecture = \"${arch}\", + )") + versions_entries+=(" \"${minor}_${arch}\": \"${version}\",") + metadata_deps+=(" \"python${python_short}_${arch}\",") + repos+=("python${python_short}_${arch}") + done <<< "$archs" + done + + # Keep root-module repository visibility aligned with the selected matrix. + repos_sorted=$(printf '%s\n' "${repos[@]}" | sort | sed 's/^/"/; s/$/"/' | paste -sd, - | sed 's/,/, /g') + module_line="use_repo(py, ${repos_sorted}, \"python_versions\")" + current_module_line=$(grep '^use_repo(py,' MODULE.bazel || true) + if [ "$current_module_line" != "$module_line" ]; then + module_changed=1 + changes+=("sync MODULE.bazel repositories") + changed=1 + fi + + if [ "$dry_run" = 1 ]; then + if [ "$changed" = 0 ]; then + echo "NO_CHANGE" + else + printf 'would %s\n' "${changes[@]}" >&2 + echo "DRY_RUN" + fi + return 0 + fi + + if [ "$changed" = 0 ]; then + echo "NO_CHANGE" + return 0 + fi + + printf '%s\n' "${changes[@]}" >&2 + + local start end section tmp + start=$(grep -n '# Python from python-build-standalone' private/extensions/python.bzl | head -1 | cut -d: -f1) + end=$(grep -n '^_archive = tag_class' private/extensions/python.bzl | head -1 | cut -d: -f1) + local minors_list + minors_list=${minors[*]} + minors_list=${minors_list// /, } + section=" # Python from python-build-standalone (https://github.com/astral-sh/python-build-standalone) + # Release ${latest_release}. Linux targets only (distroless images). + # Versions ${minors_list}. New stable minors are added by the updater. +$(printf '%s\n\n' "${archive_blocks[@]}") + + python_versions_repo( + name = \"python_versions\", + versions = { +$(printf '%s\n' "${versions_entries[@]}") + }, + ) + + return module_ctx.extension_metadata( + root_module_direct_deps = [ + \"python_versions\", +$(printf '%s\n' "${metadata_deps[@]}") + ], + root_module_direct_dev_deps = [], + ) + +" + tmp=$(mktemp) + head -n $((start - 1)) private/extensions/python.bzl > "$tmp" + printf '%s' "$section" >> "$tmp" + tail -n +"$end" private/extensions/python.bzl >> "$tmp" + # Verify the generated extension before replacing the committed file. + if which buildifier >/dev/null 2>&1; then + if ! buildifier -type=bzl -mode=fix "$tmp"; then + echo "generated extension failed buildifier; aborting without changes" >&2 + rm -f "$tmp" + return 1 + fi + fi + # Apply and verify matrix changes in a temporary file before replacing the file. + local config_tmp="" + config_tmp=$(mktemp) + cp python/config.bzl "$config_tmp" + local minors_quoted + minors_quoted=$(printf '\"%s\", ' "${minors[@]}" | sed 's/, $//') + sed_inplace "s/^PYTHON_MAJOR_VERSIONS = .*/PYTHON_MAJOR_VERSIONS = [${minors_quoted}]/" "$config_tmp" + if [ ${#fill[@]} -gt 0 ]; then + local arch_list fill_entries fill_m2 + grep -q '^PYTHON_MAJOR_VERSIONS = ' python/config.bzl \ + || { echo "PYTHON_MAJOR_VERSIONS line not found in python/config.bzl" >&2; rm -f "$tmp"; return 1; } + grep -q "\"${latest_minor}\": \[" python/config.bzl \ + || { echo "arch map for ${latest_minor} not found in python/config.bzl" >&2; rm -f "$tmp"; return 1; } + arch_list=$(get_python_archs "$latest_minor" | sed 's/^/"/; s/$/"/' | paste -sd, - | sed 's/,/, /g') + fill_entries="" + for fill_m2 in "${fill[@]}"; do + if grep -Fq "\"${fill_m2}\": [" "$config_tmp"; then + continue + fi + fill_entries="${fill_entries}\n \"${fill_m2}\": [${arch_list}]," + done + if [ -n "$fill_entries" ]; then + sed_inplace "s|\"${latest_minor}\": \[[^]]*\],|\"${latest_minor}\": [${arch_list}],${fill_entries}|" "$config_tmp" + fi + for fill_m2 in "${fill[@]}"; do + grep -qE "PYTHON_MAJOR_VERSIONS = .*\"${fill_m2}\"" "$config_tmp" \ + || { echo "config.bzl update for ${fill_m2} did not land (format drift?)" >&2; rm -f "$config_tmp" "$tmp"; return 1; } + grep -q "\"${fill_m2}\": \[" "$config_tmp" \ + || { echo "config.bzl arch map for ${fill_m2} did not land" >&2; rm -f "$config_tmp" "$tmp"; return 1; } + done + fi + + if [ "$module_changed" = 1 ]; then + module_tmp=$(mktemp) + cp MODULE.bazel "$module_tmp" + sed_inplace "s/^use_repo(py, .*/${module_line}/" "$module_tmp" + grep -Fxq "$module_line" "$module_tmp" \ + || { echo "MODULE.bazel use_repo update did not land" >&2; rm -f "$module_tmp"; rm -f "$config_tmp" "$tmp"; return 1; } + fi + if command -v buildifier >/dev/null 2>&1; then + if ! buildifier -type=bzl -mode=fix "$config_tmp"; then + echo "generated config failed buildifier; aborting without changes" >&2 + rm -f "$config_tmp" "$module_tmp" "$tmp" + return 1 + fi + fi + # All generated content is verified; apply it. + chmod 644 "$tmp" "$config_tmp" + [ -z "$module_tmp" ] || chmod 644 "$module_tmp" + mv "$tmp" private/extensions/python.bzl || { echo "extension update failed" >&2; echo "MUTATED_PARTIAL"; return 1; } + if [ -n "$config_tmp" ]; then + mv "$config_tmp" python/config.bzl || { echo "config.bzl update failed" >&2; echo "MUTATED_PARTIAL"; return 1; } + fi + if [ -n "$module_tmp" ]; then + mv "$module_tmp" MODULE.bazel || { echo "MODULE.bazel update failed" >&2; echo "MUTATED_PARTIAL"; return 1; } + fi + + echo "$latest_release" +} + +# Update version-specific testdata and create files for new minors. +function update_test_versions_python() { + local minor file new expected + # Keep the smoke test's expected minors in sync with the matrix. + expected=$(get_python_minors | tr '\n' ' ') + sed_inplace "s/\"\$minors\" = \"[^\"]*\"/\"\$minors\" = \"${expected}\"/" python/update_python_archives_test.sh + for minor in $(get_python_minors); do + file="python/testdata/python3.$(echo "$minor" | cut -d. -f2).yaml" + new=$(current_version "$minor") + if [ ! -f "$file" ]; then + [ -n "$new" ] || continue + cat > "$file" <&2; return 1; } + fi + done +} diff --git a/private/extensions/BUILD.bazel b/private/extensions/BUILD.bazel index e69de29bb..648b61304 100644 --- a/private/extensions/BUILD.bazel +++ b/private/extensions/BUILD.bazel @@ -0,0 +1 @@ +exports_files(["python.bzl"]) diff --git a/private/extensions/python.bzl b/private/extensions/python.bzl new file mode 100644 index 000000000..633ffd423 --- /dev/null +++ b/private/extensions/python.bzl @@ -0,0 +1,240 @@ +"python" + +BUILD_TMPL = """\ +# GENERATED FILE; DO NOT EDIT. +load("@distroless//private/pkg:package_spdx.bzl", "package_spdx") +load("@distroless//private/util:merge_providers.bzl", "merge_providers") +load("@distroless//private/util:tar.bzl", "tar") + +tar( + name = "data", + extension = "tar.gz", + srcs = glob( + [ + "output/bin/python{pyver}", + "output/lib/python{pyver}/**", + ], + exclude = [ + "output/lib/python{pyver}/ensurepip/**", + "output/lib/python{pyver}/idlelib/**", + "output/lib/python{pyver}/tkinter/**", + "output/lib/python{pyver}/turtle.py", + "output/lib/python{pyver}/turtledemo/**", + "output/lib/python{pyver}/lib-dynload/_tkinter*", + "output/lib/python{pyver}/config-{pyver}-*/**", + "output/lib/python{pyver}/site-packages/pip/**", + "output/lib/python{pyver}/site-packages/pip-*.dist-info/**", + ], + ), + symlinks = {{ + "/python/bin/python": "python{pyver}", + "/python/bin/python3": "python{pyver}", + }}, + package_dir = "/python", + strip_prefix = "external/{canonical_name}/output" +) + +package_spdx( + name = "spdx", + package_name = "{package_name}", + version = "{version}", + spdx_id = "{spdx_id}", + sha256 = "{sha256}", + urls = [{urls}], + copyright = "output/lib/python{pyver}/LICENSE.txt", + homepage = "https://www.python.org/", + supplier = "Organization: Astral ", + description = "Standalone CPython runtime built by python-build-standalone", +) + +merge_providers( + name = "{name}", + srcs = [":data", ":spdx"], + visibility = ["//visibility:public"], +) +""" + +def _impl(rctx): + rctx.report_progress("Fetching {}".format(rctx.attr.package_name)) + rctx.download_and_extract( + url = rctx.attr.urls, + sha256 = rctx.attr.sha256, + type = rctx.attr.type, + stripPrefix = rctx.attr.strip_prefix, + output = "output", + ) + rctx.file( + "BUILD.bazel", + content = BUILD_TMPL.format( + canonical_name = rctx.attr.name, + name = rctx.attr.name.split("+")[-1], + package_name = rctx.attr.package_name, + version = rctx.attr.version, + spdx_id = rctx.attr.name, + pyver = rctx.attr.python_version, + urls = ",".join(['"%s"' % url for url in rctx.attr.urls]), + sha256 = rctx.attr.sha256, + ), + ) + +python_archive = repository_rule( + implementation = _impl, + attrs = { + "urls": attr.string_list(mandatory = True), + "sha256": attr.string(mandatory = True), + "type": attr.string(default = ".tar.gz"), + "strip_prefix": attr.string(), + "package_name": attr.string(default = "python"), + "version": attr.string(mandatory = True), + # The x.y version used for binary and library paths, such as "3.14". + "python_version": attr.string(mandatory = True), + "architecture": attr.string(mandatory = True), + }, +) + +_PYTHON_VERSIONS_TMPL = """\ +"python versions" + +# AUTO GENERATED. DO NOT EDIT. +PYTHON_VERSIONS = {versions} +""" + +def _python_versions_repo_impl(rctx): + rctx.file("versions.bzl", _PYTHON_VERSIONS_TMPL.format(versions = str(rctx.attr.versions))) + rctx.file("BUILD.bazel", 'exports_files(["versions.bzl"])') + +python_versions_repo = repository_rule( + implementation = _python_versions_repo_impl, + attrs = { + "versions": attr.string_dict(), + }, +) + +def _python_impl(module_ctx): + mod = module_ctx.modules[0] + + if len(module_ctx.modules) > 1: + fail("python.archive should be called only once") + if not mod.is_root: + fail("python.archive should be called from root module only.") + + # Python from python-build-standalone (https://github.com/astral-sh/python-build-standalone) + # Release 20261110. Linux targets only (distroless images). + # Versions 3.14, 3.15. New stable minors are added by the updater. + python_archive( + name = "python314_amd64", + sha256 = "c2ff2e97422f5d3896a16e0317fd212ba977bbf2688d93a6f7a03d817506bd30", + strip_prefix = "python/", + urls = ["https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.14.10+20261110-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"], + version = "3.14.10+20261110", + python_version = "3.14", + architecture = "amd64", + ) + + python_archive( + name = "python314_arm64", + sha256 = "38fd50f07170adc29d481913d1c30b17ecb538fbe290315fe1f83d84fdd5b694", + strip_prefix = "python/", + urls = ["https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.14.10+20261110-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"], + version = "3.14.10+20261110", + python_version = "3.14", + architecture = "arm64", + ) + + python_archive( + name = "python314_s390x", + sha256 = "e70f5f99dba26665dad0e43b521b44d080a33790bf5805872c676736462c2bb0", + strip_prefix = "python/", + urls = ["https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.14.10+20261110-s390x-unknown-linux-gnu-install_only_stripped.tar.gz"], + version = "3.14.10+20261110", + python_version = "3.14", + architecture = "s390x", + ) + + python_archive( + name = "python314_riscv64", + sha256 = "e7225b7b4c2d61ca4e241423fe7ee8784cd40313c62169595eebafb8a553fed8", + strip_prefix = "python/", + urls = ["https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.14.10+20261110-riscv64-unknown-linux-gnu-install_only_stripped.tar.gz"], + version = "3.14.10+20261110", + python_version = "3.14", + architecture = "riscv64", + ) + + python_archive( + name = "python315_amd64", + sha256 = "ad23d1b73fac26440b0306ae06911031344c49a90ec19716c8362e7fa40cae43", + strip_prefix = "python/", + urls = ["https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.15.2+20261110-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"], + version = "3.15.2+20261110", + python_version = "3.15", + architecture = "amd64", + ) + + python_archive( + name = "python315_arm64", + sha256 = "d1367a6c3cd86a9e35712072841f1376859f3b47a2a54e224421a0f9fd169047", + strip_prefix = "python/", + urls = ["https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.15.2+20261110-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"], + version = "3.15.2+20261110", + python_version = "3.15", + architecture = "arm64", + ) + + python_archive( + name = "python315_s390x", + sha256 = "87228faf46bedc27fd6b8a7bcdc7ff520c86ca1b7c59eee9f14a4cf12b9d0d86", + strip_prefix = "python/", + urls = ["https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.15.2+20261110-s390x-unknown-linux-gnu-install_only_stripped.tar.gz"], + version = "3.15.2+20261110", + python_version = "3.15", + architecture = "s390x", + ) + + python_archive( + name = "python315_riscv64", + sha256 = "b05b96b52b0833443c8340800e957406dbfb5db2fe2f4af6e546db9b2ae1056a", + strip_prefix = "python/", + urls = ["https://github.com/astral-sh/python-build-standalone/releases/download/20261110/cpython-3.15.2+20261110-riscv64-unknown-linux-gnu-install_only_stripped.tar.gz"], + version = "3.15.2+20261110", + python_version = "3.15", + architecture = "riscv64", + ) + + python_versions_repo( + name = "python_versions", + versions = { + "3.14_amd64": "3.14.10", + "3.14_arm64": "3.14.10", + "3.14_s390x": "3.14.10", + "3.14_riscv64": "3.14.10", + "3.15_amd64": "3.15.2", + "3.15_arm64": "3.15.2", + "3.15_s390x": "3.15.2", + "3.15_riscv64": "3.15.2", + }, + ) + + return module_ctx.extension_metadata( + root_module_direct_deps = [ + "python_versions", + "python314_amd64", + "python314_arm64", + "python314_s390x", + "python314_riscv64", + "python315_amd64", + "python315_arm64", + "python315_s390x", + "python315_riscv64", + ], + root_module_direct_dev_deps = [], + ) + +_archive = tag_class(attrs = {}) + +python = module_extension( + implementation = _python_impl, + tag_classes = { + "archive": _archive, + }, +) diff --git a/python/BUILD b/python/BUILD new file mode 100644 index 000000000..14480c6af --- /dev/null +++ b/python/BUILD @@ -0,0 +1,52 @@ +load(":config.bzl", "PYTHON_ARCHITECTURES", "PYTHON_DISTROS", "PYTHON_MAJOR_VERSIONS", "PYTHON_PACKAGES") +load(":python.bzl", "python_image", "python_image_index") + +package(default_visibility = ["//visibility:public"]) + +sh_test( + name = "update_python_archives_test", + srcs = ["update_python_archives_test.sh"], + data = [ + ":config.bzl", + "//:MODULE.bazel", + "//knife.d:update_python_archives.sh", + "//private/extensions:python.bzl", + ], +) + +# Offline contract test for a complete PBS release update. +sh_test( + name = "update_python_archives_contract_test", + srcs = ["update_python_archives_contract_test.sh"], + data = [ + ":config.bzl", + ":update_python_archives_test.sh", + "//:MODULE.bazel", + "//:knife", + "//knife.d:update_java_versions.sh", + "//knife.d:update_python_archives.sh", + "//private/extensions:python.bzl", + ], +) + +[ + python_image( + arch = arch, + distro = distro, + major_version = major_version, + packages = PYTHON_PACKAGES[distro], + ) + for distro in PYTHON_DISTROS + for major_version in PYTHON_MAJOR_VERSIONS + for arch in PYTHON_ARCHITECTURES[distro][major_version] +] + +[ + python_image_index( + architectures = PYTHON_ARCHITECTURES[distro][major_version], + distro = distro, + major_version = major_version, + ) + for distro in PYTHON_DISTROS + for major_version in PYTHON_MAJOR_VERSIONS +] diff --git a/python/README.md b/python/README.md new file mode 100644 index 000000000..b57f2d212 --- /dev/null +++ b/python/README.md @@ -0,0 +1,95 @@ +# Documentation for `python/` (python-build-standalone) + +## Image Contents + +These images contain a minimal Linux, Python-based runtime built from a +[python-build-standalone](https://github.com/astral-sh/python-build-standalone) +prebuilt tarball instead of the Debian Python package. + +Supported versions: + +- Python 3.14 (`python3.14-debian13`) +- Python 3.15 (`python3.15-debian13`) + +Each image contains everything in the [C/C++ base image](../cc/README.md), +plus a standalone CPython install under `/python`: + +- `/python/bin/python3.X` (with `/python/bin/python` and `/python/bin/python3` symlinks) +- `/python/lib/python3.X/` (standard library) + +Normal images contain no shell, include files, pip, ensurepip, or Tk GUI modules. +Debug variants inherit BusyBox from the base image. Install dependencies in a +builder stage and copy them into the runtime image. +Creating a virtual environment in the runtime image requires `venv --without-pip`. + +python-build-standalone builds are relocatable. The C/C++ base image supplies +their system shared libraries, including glibc and libgcc. + +## Usage + +The entrypoint of these images is set to `python3.X`, so they expect users to +supply a path to a .py file in the CMD. + +See the Python [Hello World](../examples/python3/) directory for an example. + +### Compatibility + +When using these images in a multi-stage build, use a build image with the same +Python version to avoid ABI-related errors. For example, when targeting +`python3.14-debian13`, use a `python:3.14-slim-trixie` (or python-build-standalone) +build stage. + +When building virtual environments, note that the distroless Python path is +`/python/bin/python3.14`. To ensure your virtual environment's internal links +are correct, your build environment should match this path. If your build image +uses a different path, create a symlink during the build stage, e.g.: + +```Dockerfile +RUN mkdir -p /python/bin && ln -s /usr/local/bin/python3.14 /python/bin/python3.14 +``` + +### Shared libraries + +PBS embeds many native libraries into Python. Their standard-library modules +work without separate shared objects. `ctypes.util.find_library()` cannot discover +these embedded libraries. Use a shared library's explicit path or soname when +loading a library with `ctypes.CDLL`. + +## Provenance + +Python comes from a [python-build-standalone](https://github.com/astral-sh/python-build-standalone) +prebuilt tarball (`cpython-3.X.Y+--install_only_stripped.tar.gz`). +The exact release, versions, and SHA-256 digests are pinned in the extension +definition and updated via `knife update-python-archives`. +The image SBOM includes package metadata for the PBS archive. It does not inventory +native libraries embedded in that archive. + +## Update contracts + +Run `./knife update-python-archives` from the repository root. `--verbose` explains +pin changes; `--dry-run` checks release metadata without writing tracked files. +Python 3, jq, curl, and version-aware `sort` are required; Buildifier validates +generated Starlark when installed. + +- The matrix in `config.bzl` defines required minors and architectures. Every + architecture for a minor must have the same CPython version. Missing assets, + invalid or duplicate digests fail before files are replaced. Bazel verifies + archive checksums when downloading them. +- The updater adds new stable minors above the oldest configured minor. A minor + without an architecture row inherits the highest configured minor's architectures. + To opt into a beta or RC, add its minor and architectures to the matrix. Once + a stable release is pinned, only stable releases are selected for that minor. + Removing a prerelease minor opts out until a stable release is available. + Required minors stay in the matrix when PBS stops publishing them. +- A newer PBS release updates the pins even when CPython's patch version is + unchanged. The updater rejects older PBS releases and CPython versions. + It also repairs checksum pins and repository visibility. +- Archive pins, the matrix, and repository visibility are validated before + replacement. Restore these files if a filesystem error interrupts replacement. + Version testdata can be repaired by rerunning the updater against the same release. + Refresh and commit `MODULE.bazel.lock` with + `bazel mod deps --lockfile_mode=update` after changing the extension. + +The offline updater contracts run with `bazel test //python:all`. +Container structure tests are tagged `manual` and require Docker; +run the architecture-specific tests through `./knife test` or the CI workflow. diff --git a/python/config.bzl b/python/config.bzl new file mode 100644 index 000000000..c915f132c --- /dev/null +++ b/python/config.bzl @@ -0,0 +1,17 @@ +"python configurations" + +PYTHON_DISTROS = ["debian13"] + +# Full CPython versions are defined in the extension. +PYTHON_MAJOR_VERSIONS = ["3.14", "3.15"] + +PYTHON_ARCHITECTURES = { + "debian13": { + "3.14": ["amd64", "arm64", "s390x", "riscv64"], + "3.15": ["amd64", "arm64", "s390x", "riscv64"], + }, +} + +PYTHON_PACKAGES = { + "debian13": [], +} diff --git a/python/python.bzl b/python/python.bzl new file mode 100644 index 000000000..a0ceffd1b --- /dev/null +++ b/python/python.bzl @@ -0,0 +1,117 @@ +"python image definitions" + +load("@container_structure_test//:defs.bzl", "container_structure_test") +load("@python_versions//:versions.bzl", "PYTHON_VERSIONS") +load("@rules_oci//oci:defs.bzl", "oci_image", "oci_image_index") +load("//common:variables.bzl", "DEBUG_MODE", "OS_RELEASE", "USERS") +load("//private/util:deb.bzl", "deb") +load("//private/util:tar.bzl", "tar") + +def _bin_version(major_version): + """Return x.y from a beta or RC matrix version.""" + return major_version.split("b")[0].split("rc")[0] + +def python_image_index(distro, major_version, architectures): + """Create a Python image index for a distribution. + + Args: + distro: distribution name + major_version: Python version, such as "3.14" + architectures: architectures included in the index + """ + for mode in DEBUG_MODE: + for user in USERS: + oci_image_index( + name = "python" + major_version.replace(".", "") + mode + "_" + user + "_" + distro, + images = [ + "python" + major_version.replace(".", "") + mode + "_" + user + "_" + arch + "_" + distro + for arch in architectures + ], + ) + +def _example_tar(): + if native.existing_rule("example"): + return + + tar( + name = "example", + extension = "tar.gz", + srcs = ["testdata/stdlib_check.py"], + ) + +def python_image(distro, major_version, arch, packages): + """Create Python and debug images with tests. + + Python comes from a python-build-standalone prebuilt tarball + instead of the Debian Python package. + + Args: + distro: distribution name + major_version: Python version, such as "3.14" + arch: target architecture + packages: Debian packages to add to the image + """ + + _version_key = major_version + "_" + arch + if _version_key not in PYTHON_VERSIONS: + fail("No version found for Python version/arch: " + _version_key) + _annotations = { + "org.opencontainers.image.source": OS_RELEASE["HOME_URL"], + "com.google.distroless.python.version": PYTHON_VERSIONS[_version_key], + } + + for mode in DEBUG_MODE: + for user in USERS: + oci_image( + name = "python" + major_version.replace(".", "") + mode + "_" + user + "_" + arch + "_" + distro, + base = "//cc:cc" + mode + "_" + user + "_" + arch + "_" + distro, + entrypoint = ["/python/bin/python" + _bin_version(major_version)], + env = {"LANG": "C.UTF-8"}, + tars = [ + deb.package(arch, distro, pkg) + for pkg in packages + ] + [ + "@python" + major_version.replace(".", "") + "_" + arch, + ], + annotations = _annotations, + ) + + _example_tar() + + # Debug images include BusyBox; structure tests cover non-debug images. + for user in USERS: + container_structure_test( + name = "python" + major_version.replace(".", "") + "_" + user + "_" + arch + "_" + distro + "_test", + size = "medium", + configs = [ + "testdata/python3.yaml", + "testdata/python3." + _bin_version(major_version).split(".")[1] + ".yaml", + ], + image = ":python" + major_version.replace(".", "") + "_" + user + "_" + arch + "_" + distro, + tags = [ + arch, + "manual", + ], + ) + + for mode in DEBUG_MODE: + for user in USERS: + oci_image( + name = "example_python" + major_version.replace(".", "") + mode + "_" + user + "_" + arch + "_" + distro, + base = ":python" + major_version.replace(".", "") + mode + "_" + user + "_" + arch + "_" + distro, + tars = [ + ":example", + ], + ) + + for user in USERS: + container_structure_test( + name = "example_python" + major_version.replace(".", "") + "_" + user + "_" + arch + "_" + distro + "_test", + size = "medium", + configs = ["testdata/example.yaml"], + image = ":example_python" + major_version.replace(".", "") + "_" + user + "_" + arch + "_" + distro, + tags = [ + arch, + "manual", + ], + ) diff --git a/python/testdata/example.yaml b/python/testdata/example.yaml new file mode 100644 index 000000000..664c96348 --- /dev/null +++ b/python/testdata/example.yaml @@ -0,0 +1,6 @@ +schemaVersion: "2.0.0" +commandTests: + - name: stdlib_check + command: "/python/bin/python3" + args: ["/stdlib_check.py"] + expectedOutput: ["ALL GOOD"] diff --git a/python/testdata/python3.14.yaml b/python/testdata/python3.14.yaml new file mode 100644 index 000000000..57c19a468 --- /dev/null +++ b/python/testdata/python3.14.yaml @@ -0,0 +1,10 @@ +schemaVersion: "2.0.0" +commandTests: + - name: version + command: "/python/bin/python3.14" + args: ["--version"] + expectedOutput: ["Python 3.14.10"] + - name: symlink + command: "/python/bin/python3" + args: ["--version"] + expectedOutput: ["Python 3.14.10"] diff --git a/python/testdata/python3.15.yaml b/python/testdata/python3.15.yaml new file mode 100644 index 000000000..289997d84 --- /dev/null +++ b/python/testdata/python3.15.yaml @@ -0,0 +1,10 @@ +schemaVersion: "2.0.0" +commandTests: + - name: version + command: "/python/bin/python3.15" + args: ["--version"] + expectedOutput: ["Python 3.15.2"] + - name: symlink + command: "/python/bin/python3" + args: ["--version"] + expectedOutput: ["Python 3.15.2"] diff --git a/python/testdata/python3.yaml b/python/testdata/python3.yaml new file mode 100644 index 000000000..723329221 --- /dev/null +++ b/python/testdata/python3.yaml @@ -0,0 +1,119 @@ +schemaVersion: "2.0.0" +commandTests: + - name: hello + command: "/python/bin/python3" + args: ["-c", "print('Hello World')"] + expectedOutput: ['Hello World'] + + # Ensure no shell is present. + - name: no_shell + command: "/python/bin/python3" + args: ["-c", + "import subprocess, sys; subprocess.check_call(sys.executable + ' -h', shell=True)"] + exitCode: 1 + + # File names use UTF-8, the default on modern Linux systems. + # Double-escape the \xe9 sequence to avoid YAML parsing issues. + - name: filesystem_utf8 + command: "/python/bin/python3" + args: ["-c", "open(u'h\\xe9llo', 'w'); import sys; print(sys.getfilesystemencoding())"] + expectedOutput: ['utf-8'] + + # The print function should output UTF-8. + - name: print_utf8 + command: "/python/bin/python3" + args: ["-c", "print(u'h\\xe9llo.txt')"] + expectedOutput: ['h\xe9llo'] + + - name: runtime_contents + command: "/python/bin/python3" + args: ["-c", "import ctypes, glob, importlib.util; ctypes.CDLL('libc.so.6'); assert not glob.glob('/python/lib/libpython*'); assert all(importlib.util.find_spec(m) is None for m in ('pip', 'ensurepip', 'idlelib', 'tkinter', 'turtle', 'turtledemo'))"] + + # Import every module installed with Python. + - name: import_everything + exitCode: 0 + expectedOutput: ['FINISHED ENTIRE SCRIPT'] + command: "/python/bin/python3" + args: + - "-c" + # The YAML block contains a script that imports all installed modules. + # This checks the required native-library dependencies. + - | + import importlib, os, pkgutil, sys + + skip_modules = frozenset(( + # Windows-specific modules + 'asyncio.windows_events', + 'asyncio.windows_utils', + 'ctypes.wintypes', + 'encodings.cp65001', + 'encodings.mbcs', + 'encodings.oem', + 'multiprocessing.popen_spawn_win32', + 'winreg', + + # Python regression tests for internal use. + 'test', + + # Calls sys.exit. + 'unittest.__main__', + 'venv.__main__', + + # python-build-standalone omits _gdbm. + 'dbm.gnu', + + # iOS-only support. + '_ios_support', + + # GUI: no Tcl/Tk in the image; never_import covers the related + # packages, and _tkinter is the C extension. + '_tkinter', + + # The new REPL requires libncurses, which is not shipped. + '_pyrepl', + + # Prints the Zen of Python on import. + 'this', + )) + + # Packages skipped during import: GUI modules (no Tcl/Tk in the image), + # idlelib (which exits without Tk), and removed distutils. + never_import = ('tkinter', 'idlelib', 'turtle', 'distutils', 'test', 'venv') + + failed = [] + + def walk(path, prefix=''): + try: + infos = list(pkgutil.iter_modules(path)) + except Exception as e: + failed.append('walk {}: {}'.format(path, e)) + return + for info in infos: + name = prefix + info.name + if name in skip_modules or name.startswith(never_import): + continue + if info.ispkg: + try: + mod = importlib.import_module(name) + if hasattr(mod, '__path__'): + walk(mod.__path__, name + '.') + except BaseException as e: + failed.append('{}: {}: {}'.format(name, type(e).__name__, e)) + continue + try: + importlib.import_module(name) + except BaseException as e: + failed.append('{}: {}: {}'.format(name, type(e).__name__, e)) + + stdlib_root = os.path.join(os.path.dirname(sys.executable), os.pardir, 'lib', 'python%d.%d' % sys.version_info[:2]) + for p in sys.path: + if os.path.abspath(p).startswith(os.path.abspath(stdlib_root)) and 'site-packages' not in p: + walk([p]) + + if failed: + for f in failed[:20]: + print('FAIL {}'.format(f)) + raise SystemExit('failed to import {} modules'.format(len(failed))) + + # Confirm that the script completed rather than exiting during import. + print('FINISHED ENTIRE SCRIPT') diff --git a/python/testdata/stdlib_check.py b/python/testdata/stdlib_check.py new file mode 100644 index 000000000..0fb8da204 --- /dev/null +++ b/python/testdata/stdlib_check.py @@ -0,0 +1,131 @@ +#!/python/bin/python3 +"""Import every available standard-library module in the distroless Python image +and exercise a representative set with one call each.""" + +import importlib +import pkgutil +import sys + +skip_modules = frozenset(( + # Windows-specific modules + "asyncio.windows_events", + "asyncio.windows_utils", + "ctypes.wintypes", + "encodings.cp65001", + "encodings.mbcs", + "encodings.oem", + "multiprocessing.popen_spawn_win32", + "winreg", + # Python regression tests. + "test", + # Calls sys.exit. + "unittest.__main__", + "venv.__main__", + # python-build-standalone omits _gdbm. + "dbm.gnu", + # Platform-specific or GUI extensions not used in a server image. + "_ios_support", + "_tkinter", + # The new REPL requires libncurses, which is not shipped. + "_pyrepl", + # Prints the Zen of Python on import. + "this", +)) + +# Packages skipped during import: GUI modules (no Tcl/Tk in the image), +# idlelib (which exits without Tk), and removed distutils. +never_import = ("tkinter", "idlelib", "turtle", "distutils", "test", "venv") + +failed = [] + +def walk(path, prefix=""): + try: + infos = list(pkgutil.iter_modules(path)) + except Exception as e: + failed.append("walk %s: %s" % (path, e)) + return + for info in infos: + name = prefix + info.name + if name in skip_modules or name.startswith(never_import): + continue + if info.ispkg: + try: + mod = importlib.import_module(name) + if hasattr(mod, "__path__"): + walk(mod.__path__, name + ".") + except BaseException as e: + failed.append("%s: %s: %s" % (name, type(e).__name__, e)) + continue + try: + importlib.import_module(name) + imported[0] += 1 + except BaseException as e: + failed.append("%s: %s: %s" % (name, type(e).__name__, e)) + +import os + +stdlib_root = os.path.join(os.path.dirname(sys.executable), os.pardir, "lib", "python%d.%d" % sys.version_info[:2]) +imported = [0] +for p in sys.path: + # Scan only the standard-library tree, skipping the script directory and site-packages. + if os.path.abspath(p).startswith(os.path.abspath(stdlib_root)) and "site-packages" not in p: + walk([p]) + +print("imported %d modules" % imported[0]) +if failed: + for f in failed[:30]: + print("FAIL " + f) + print("FAILED %d" % len(failed)) + sys.exit(1) + +# Run one representative call for each module; any exception fails the test. +calls = [ + lambda: importlib.import_module("hashlib").sha256(b"distroless").hexdigest(), + lambda: importlib.import_module("json").dumps({"a": [1, 2.5, None, "x"]}), + lambda: importlib.import_module("sqlite3").connect(":memory:").execute("select 1").fetchone(), + lambda: importlib.import_module("zlib").compress(b"x" * 1000), + lambda: importlib.import_module("bz2").compress(b"x" * 1000), + lambda: importlib.import_module("lzma").compress(b"x" * 1000), + lambda: importlib.import_module("ctypes").CDLL("libc.so.6"), + lambda: importlib.import_module("base64").b64encode(b"hello"), + lambda: importlib.import_module("uuid").uuid4().hex, + lambda: importlib.import_module("datetime").datetime.now().isoformat(), + lambda: importlib.import_module("collections").Counter("abracadabra")["a"], + lambda: importlib.import_module("io").BytesIO(b"data").read(), + lambda: importlib.import_module("struct").pack(">I", 42), + lambda: importlib.import_module("csv").reader(["a,b"]).__next__(), + lambda: importlib.import_module("re").match(r"\d+", "123x").group(), + lambda: importlib.import_module("string").ascii_letters.__len__(), + lambda: importlib.import_module("ssl").create_default_context(), + lambda: importlib.import_module("ssl").get_default_verify_paths(), + lambda: importlib.import_module("socket").getaddrinfo("localhost", 80), + lambda: importlib.import_module("urllib.request").urlopen("https://example.com", timeout=10).status, + lambda: importlib.import_module("subprocess").check_output([sys.executable, "-c", "print(1)"]).strip(), + lambda: importlib.import_module("os").getpid(), + lambda: importlib.import_module("math").sqrt(2), + lambda: importlib.import_module("statistics").mean([1, 2, 3, 4]), + lambda: importlib.import_module("fractions").Fraction(1, 3) * 3, + lambda: importlib.import_module("calendar").isleap(2024), + lambda: importlib.import_module("html").escape("&"), + lambda: importlib.import_module("glob").glob("/python/bin/*").__len__(), + lambda: importlib.import_module("shutil").which(os.path.basename(sys.executable)), + lambda: importlib.import_module("tempfile").gettempdir(), + lambda: importlib.import_module("threading").current_thread().name, + lambda: importlib.import_module("queue").Queue().empty(), + lambda: importlib.import_module("concurrent.futures").ThreadPoolExecutor(max_workers=1).submit(lambda: 1).result(), +] + +for i, call in enumerate(calls): + try: + call() + except Exception as e: + failed.append("call %d: %s: %s" % (i, type(e).__name__, e)) + +if failed: + for f in failed: + print("FAIL " + f) + print("FAILED %d" % len(failed)) + sys.exit(1) + +print("calls OK: %d" % len(calls)) +print("ALL GOOD on Python %s (%s)" % (sys.version.split()[0], sys.platform)) diff --git a/python/update_python_archives_contract_test.sh b/python/update_python_archives_contract_test.sh new file mode 100755 index 000000000..8b01eb10b --- /dev/null +++ b/python/update_python_archives_contract_test.sh @@ -0,0 +1,361 @@ +#!/usr/bin/env bash +# Black-box contract test for the Python updater. +# +# Contract: after a new PBS release, the updater rewrites all files needed to +# build consistent images and converge: +# - archive blocks and version data +# - the matrix and repository visibility for selected minors +# - version-specific testdata +# - a second run returns NO_CHANGE (the updater reaches a fixed point) +# Release data is supplied through PBS_RELEASE_FILE and PBS_SHA256SUMS_FILE. +set -euo pipefail + +cd "$TEST_SRCDIR/${TEST_WORKSPACE:-_main}" + +FIX=$(mktemp -d) +trap 'rm -rf "$FIX"' EXIT + +# Copy every file mutated by the updater into the test workspace. +mkdir -p "$FIX/private/extensions" "$FIX/python/testdata" +mkdir -p "$FIX/knife.d" +cp knife "$FIX/" +cp knife.d/update_java_versions.sh knife.d/update_python_archives.sh "$FIX/knife.d/" +cp knife.d/update_python_archives.sh "$FIX/" +cp private/extensions/python.bzl "$FIX/private/extensions/" +cp python/config.bzl "$FIX/python/" +cp MODULE.bazel "$FIX/" +cp python/update_python_archives_test.sh "$FIX/python/" + +cd "$FIX" +# shellcheck source=knife.d/update_python_archives.sh +source update_python_archives.sh + +# --- fixtures --------------------------------------------------------------- +SHA_A=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +SHA_B=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +SHA_C=cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc +SHA_D=dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd +TRIPLES=(x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu s390x-unknown-linux-gnu riscv64-unknown-linux-gnu) + +make_sha256sums() { # Arguments: release, 3.13 patch, 3.14 patch, optional 3.15 patches. + local release=$1 p313=$2 p314=$3 p315=${4:-} p315_alt=${5:-} + : > SHA256SUMS + for t in "${TRIPLES[@]}"; do + echo "$SHA_A cpython-${p313}+${release}-${t}-install_only_stripped.tar.gz" >> SHA256SUMS + echo "$SHA_B cpython-${p314}+${release}-${t}-install_only_stripped.tar.gz" >> SHA256SUMS + if [ -n "$p315" ]; then + echo "$SHA_C cpython-${p315}+${release}-${t}-install_only_stripped.tar.gz" >> SHA256SUMS + fi + if [ -n "$p315_alt" ]; then + echo "$SHA_D cpython-${p315_alt}+${release}-${t}-install_only_stripped.tar.gz" >> SHA256SUMS + fi + done +} + +make_numeric_fill_sha256sums() { + local release=$1 + : > SHA256SUMS + for t in "${TRIPLES[@]}"; do + echo "$SHA_A cpython-3.9.9+${release}-${t}-install_only_stripped.tar.gz" + echo "$SHA_B cpython-3.10.1+${release}-${t}-install_only_stripped.tar.gz" + echo "$SHA_D cpython-3.10.2rc1+${release}-${t}-install_only_stripped.tar.gz" + done >> SHA256SUMS +} + +make_prerelease_only_sha256sums() { + local release=$1 + : > SHA256SUMS + for t in "${TRIPLES[@]}"; do + echo "$SHA_C cpython-3.15.0rc1+${release}-${t}-install_only_stripped.tar.gz" >> SHA256SUMS + done +} + +run_updater() { # Print stdout and fail the test on a nonzero exit. + # Run in bash -c so an updater failure does not terminate this test script. + PBS_RELEASE_FILE="$FIX/release.json" PBS_SHA256SUMS_FILE="$FIX/SHA256SUMS" \ + bash -c 'source update_python_archives.sh; generate_python_archives' 2>"$FIX/updater.err" +} + +run_updater_required_asset_fail() { + PBS_RELEASE_FILE="$FIX/release.json" PBS_SHA256SUMS_FILE="$FIX/SHA256SUMS" \ + bash -c 'source update_python_archives.sh; generate_python_archives' 2>"$FIX/updater.err" && return 1 || return 0 +} + +enable_315() { + python3 - <<'PYEOF' +from pathlib import Path + +path = Path("python/config.bzl") +text = path.read_text() +text = text.replace( + 'PYTHON_MAJOR_VERSIONS = ["3.13", "3.14"]', + 'PYTHON_MAJOR_VERSIONS = ["3.13", "3.14", "3.15"]', +) +text = text.replace( + ' "3.14": ["amd64", "arm64", "s390x", "riscv64"],\n', + ' "3.14": ["amd64", "arm64", "s390x", "riscv64"],\n' + ' "3.15": ["amd64", "arm64", "s390x", "riscv64"],\n', +) +path.write_text(text) +PYEOF +} + +enable_315_without_arches() { + python3 - <<'PYEOF' +from pathlib import Path + +path = Path("python/config.bzl") +text = path.read_text().replace( + 'PYTHON_MAJOR_VERSIONS = ["3.13", "3.14"]', + 'PYTHON_MAJOR_VERSIONS = ["3.13", "3.14", "3.15"]', +) +path.write_text(text) +PYEOF +} + +disable_315() { + python3 - <<'PYEOF' +from pathlib import Path + +path = Path("python/config.bzl") +text = path.read_text() +text = text.replace(', "3.15"]', ']') +text = text.replace( + ' "3.15": ["amd64", "arm64", "s390x", "riscv64"],\n', + '', +) +path.write_text(text) +PYEOF +} + +# --- tag-only bump (new release, same patches) ------------------------------- +# Seed the fixture without inheriting the checkout's archive pins. +sed_inplace '/^ version = "[0-9]/d' private/extensions/python.bzl +cat > python/config.bzl <<'EOF' +PYTHON_MAJOR_VERSIONS = ["3.13", "3.14"] +PYTHON_ARCHITECTURES = { + "debian13": { + "3.13": ["amd64", "arm64", "s390x", "riscv64"], + "3.14": ["amd64", "arm64", "s390x", "riscv64"], + }, +} +EOF +echo '{"tag": "20981231"}' > release.json +make_sha256sums 20981231 3.13.15 3.14.7 +run_updater >/dev/null +update_test_versions_python >/dev/null +echo '{"tag": "20990101"}' > release.json +make_sha256sums 20990101 3.13.15 3.14.7 +echo "$SHA_A cpython-3.13.999+20990101-x86_64-unknown-linux-gnu-install_only.tar.gz" >> SHA256SUMS +[ "$(run_updater)" = "20990101" ] || { echo "phase A: expected update to 20990101"; cat "$FIX/updater.err"; exit 1; } +grep -q 'releases/download/20990101/' private/extensions/python.bzl || { echo "phase A: archives not re-pointed at new release"; exit 1; } +! grep -q '20260807' private/extensions/python.bzl || { echo "phase A: old release still referenced"; exit 1; } +grep -q '3.13.15+20990101' private/extensions/python.bzl || { echo "phase A: archive version lacks new release tag"; exit 1; } +grep -q '"3.13_amd64": "3.13.15"' private/extensions/python.bzl || { echo "phase A: versions dict must not change on a tag-only bump"; exit 1; } +grep -q 'Python 3.13.15' python/testdata/python3.13.yaml || { echo "phase A: testdata must not change on a tag-only bump"; exit 1; } + +# --- patch bump (new release, new patches) ----------------------------------- +echo '{"tag": "20990102"}' > release.json +make_sha256sums 20990102 3.13.16 3.14.8 +[ "$(run_updater)" = "20990102" ] || { echo "phase B: expected update to 20990102"; cat "$FIX/updater.err"; exit 1; } +grep -q '3.13.16+20990102' private/extensions/python.bzl || { echo "phase B: archive version not bumped"; exit 1; } +grep -q '"3.13_amd64": "3.13.16"' private/extensions/python.bzl || { echo "phase B: versions dict not bumped"; exit 1; } +update_test_versions_python +grep -q 'Python 3.13.16' python/testdata/python3.13.yaml || { echo "phase B: testdata 3.13 not bumped"; exit 1; } +grep -q 'Python 3.14.8' python/testdata/python3.14.yaml || { echo "phase B: testdata 3.14 not bumped"; exit 1; } + +# --- prerelease remains opt-in ------------------------------------------------- +echo '{"tag": "20990103"}' > release.json +make_sha256sums 20990103 3.13.16 3.14.8 3.15.0b4 +[ "$(run_updater)" = "20990103" ] || { echo "phase PRE: expected stable update"; cat "$FIX/updater.err"; exit 1; } +! grep -q '"3.15"' python/config.bzl || { echo "phase PRE: beta must not extend the matrix"; exit 1; } +! grep -q 'python315_' private/extensions/python.bzl || { echo "phase PRE: beta must not enter the extension"; exit 1; } +make_prerelease_only_sha256sums 20990103 +run_updater_required_asset_fail || { echo "phase PRE: missing stable assets must fail"; cat "$FIX/updater.err"; exit 1; } +grep -q 'required matrix entry 3.13 amd64' "$FIX/updater.err" || { echo "phase PRE: missing stable asset error is unclear"; cat "$FIX/updater.err"; exit 1; } + +# --- opted-in prerelease ------------------------------------------------------- +enable_315_without_arches +echo '{"tag": "20990104"}' > release.json +make_sha256sums 20990104 3.13.16 3.14.8 +run_updater_required_asset_fail || { echo "phase OPT-IN: incomplete matrix must fail"; cat "$FIX/updater.err"; exit 1; } +grep -q 'no archs for 3.15' "$FIX/updater.err" || { echo "phase OPT-IN: incomplete matrix error is unclear"; cat "$FIX/updater.err"; exit 1; } +enable_315 +echo '{"tag": "20990104"}' > release.json +make_sha256sums 20990104 3.13.16 3.14.8 +run_updater_required_asset_fail || { echo "phase OPT-IN: missing required asset must fail"; cat "$FIX/updater.err"; exit 1; } +grep -q 'required matrix entry 3.15 amd64' "$FIX/updater.err" || { echo "phase OPT-IN: missing asset error is unclear"; cat "$FIX/updater.err"; exit 1; } +! grep -q '20990104' private/extensions/python.bzl || { echo "phase OPT-IN: failed update changed the extension"; exit 1; } +! grep -q 'python315_' MODULE.bazel || { echo "phase OPT-IN: failed update changed repository visibility"; exit 1; } +make_sha256sums 20990104 3.13.16 3.14.8 3.15.0b4 +[ "$(run_updater)" = "20990104" ] || { echo "phase OPT-IN: expected beta update"; cat "$FIX/updater.err"; exit 1; } +grep -q '3.15.0b4+20990104' private/extensions/python.bzl || { echo "phase OPT-IN: beta archive version wrong"; exit 1; } +update_test_versions_python >/dev/null +make_sha256sums 20990104 3.13.16 3.14.8 3.15.0rc1 3.15.0rc2 +[ "$(run_updater)" = "20990104" ] || { cat "$FIX/updater.err"; exit 1; } +grep -q '3.15.0rc2+20990104' private/extensions/python.bzl || { echo "phase OPT-IN: latest RC archive version wrong"; exit 1; } +for t in "${TRIPLES[@]}"; do + echo "$SHA_C cpython-3.15.0+20990104-${t}-install_only_stripped.tar.gz" >> SHA256SUMS +done +[ "$(run_updater)" = "20990104" ] || { echo "phase OPT-IN: expected final release update"; cat "$FIX/updater.err"; exit 1; } +grep -q 'python315_amd64' MODULE.bazel || { echo "phase OPT-IN: selected repos not visible"; exit 1; } +grep -q '3.15.0+20990104' private/extensions/python.bzl || { echo "phase OPT-IN: final release must outrank RCs"; exit 1; } + +# --- opt-out remains removed --------------------------------------------------- +disable_315 +make_sha256sums 20990104 3.13.16 3.14.8 +[ "$(run_updater)" = "20990104" ] || { echo "phase OPT-OUT: expected cleanup update"; cat "$FIX/updater.err"; exit 1; } +! grep -q 'python315_' MODULE.bazel || { echo "phase OPT-OUT: removed repos were repaired"; exit 1; } +! grep -q 'python315_' private/extensions/python.bzl || { echo "phase OPT-OUT: removed archives were repaired"; exit 1; } + +# --- new stable minor -------------------------------------------------------- +echo '{"tag": "20990105"}' > release.json +make_sha256sums 20990105 3.13.16 3.14.8 3.15.0 +echo "$SHA_D cpython-3.12.99+20990105-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz" >> SHA256SUMS +[ "$(run_updater)" = "20990105" ] || { echo "phase C: expected update to 20990105"; cat "$FIX/updater.err"; exit 1; } +[ "$(get_python_minors)" = $'3.13\n3.14\n3.15' ] +grep -Fxq ' "3.15": ["amd64", "arm64", "s390x", "riscv64"],' python/config.bzl +grep -q 'python315_amd64' MODULE.bazel || { echo "phase C: use_repo not extended with python315 repos"; exit 1; } +grep -q 'python315_amd64' private/extensions/python.bzl || { echo "phase C: 3.15 archive missing from extension"; exit 1; } +grep -q '3.15.0+20990105' private/extensions/python.bzl || { echo "phase C: 3.15 archive version wrong"; exit 1; } +update_test_versions_python +[ -f python/testdata/python3.15.yaml ] || { echo "phase C: python3.15.yaml not created"; exit 1; } +grep -q 'Python 3.15.0' python/testdata/python3.15.yaml || { echo "phase C: python3.15.yaml version wrong"; exit 1; } +sed_inplace "\$s/Python 3.15.0/Python 3.15.0b4/" python/testdata/python3.15.yaml +update_test_versions_python >/dev/null +! grep -q '3.15.0b4' python/testdata/python3.15.yaml || { echo "stale symlink test version was not repaired"; exit 1; } + +# --- convergence and consistency --------------------------------------------- +[ "$(run_updater)" = "NO_CHANGE" ] || { echo "final: expected NO_CHANGE"; cat "$FIX/updater.err"; exit 1; } +for minor in $(get_python_minors); do + for arch in $(get_python_archs "$minor"); do + v=$(current_version "$minor" "$arch") + [ -n "$v" ] || { echo "final: no versions-dict entry for ${minor}_${arch}"; exit 1; } + p=$(pinned_version "$minor" "$arch") + [ -n "$p" ] || { echo "final: no archive pin for ${minor}_${arch}"; exit 1; } + case "$p" in + "$v"+[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]) ;; + *) echo "final: pin for ${minor}_${arch} must be '+', got [$p]"; exit 1 ;; + esac + done +done + +# --- validation, dry run and repair -------------------------------------------- +# Validation failures and dry runs must preserve every generated file. +snapshot() { + cksum private/extensions/python.bzl python/config.bzl MODULE.bazel python/testdata/*.yaml python/update_python_archives_test.sh +} +before=$(snapshot) +cp python/config.bzl config.good +for defect in minor architecture nonstring duplicate_arch empty_arches; do + case "$defect" in + minor) sed_inplace 's/"3.15"/"3.15rc1"/g' python/config.bzl ;; + architecture) sed_inplace 's/"arm64"/"unknown-arch"/g' python/config.bzl ;; + nonstring) sed_inplace 's/"arm64"/64/g' python/config.bzl ;; + duplicate_arch) sed_inplace 's/"amd64"/"amd64", "amd64"/g' python/config.bzl ;; + empty_arches) sed_inplace 's/"3.15": \[[^]]*\]/"3.15": []/' python/config.bzl ;; + esac + if run_updater; then echo "accepted invalid matrix $defect"; exit 1; fi + cp config.good python/config.bzl + [ "$(snapshot)" = "$before" ] || { echo "invalid matrix changed generated files"; exit 1; } +done +[ "$(DRY_RUN=1 run_updater)" = "NO_CHANGE" ] +[ "$(snapshot)" = "$before" ] +echo '{"tag": "20990106"}' > release.json +make_sha256sums 20990106 3.13.16 3.14.8 3.15.0 +[ "$(DRY_RUN=1 run_updater)" = "DRY_RUN" ] +[ "$(snapshot)" = "$before" ] +for defect in duplicate malformed versions release_rollback patch_rollback; do + echo '{"tag": "20990106"}' > release.json + make_sha256sums 20990106 3.13.16 3.14.8 3.15.0 + case "$defect" in + duplicate) duplicate=$(head -1 SHA256SUMS); echo "$duplicate" >> SHA256SUMS ;; + malformed) sed_inplace "s/${SHA_A}/invalid/" SHA256SUMS ;; + versions) sed_inplace 's/3.14.8+20990106-aarch64/3.14.7+20990106-aarch64/' SHA256SUMS ;; + release_rollback) + echo '{"tag": "20990104"}' > release.json + make_sha256sums 20990104 3.13.16 3.14.8 3.15.0 + ;; + patch_rollback) make_sha256sums 20990106 3.13.15 3.14.8 3.15.0 ;; + esac + if run_updater; then echo "accepted invalid $defect fixture"; exit 1; fi + case "$defect" in *_rollback) grep -Fq 'refusing to downgrade Python 3.13 amd64' "$FIX/updater.err" ;; esac + [ "$(snapshot)" = "$before" ] || { echo "$defect mutated generated files"; exit 1; } +done +echo '{"tag": "20990105"}' > release.json +make_sha256sums 20990105 3.13.16 3.14.8 3.15.0 +sed_inplace "s/${SHA_A}/0000000000000000000000000000000000000000000000000000000000000000/" private/extensions/python.bzl +[ "$(run_updater)" = "20990105" ] || { echo "checksum pin was not repaired"; exit 1; } +awk '/version = "3.13.16[+]20990105"/ && !removed++ { next } { print }' private/extensions/python.bzl > extension.tmp +mv extension.tmp private/extensions/python.bzl +[ "$(run_updater)" = "20990105" ] || { echo "missing version pin was not repaired"; exit 1; } +[ "$(run_updater)" = "NO_CHANGE" ] + +# Exercise release discovery through the CLI, including primary-source failure. +mkdir "$FIX/bin" +cat > "$FIX/bin/curl" <<'EOF' +#!/usr/bin/env bash +case "$*" in + *latest-release.json*) exit 22 ;; + *releases/latest*) printf '{"tag_name":"20990105"}' ;; + *SHA256SUMS*) cat "$PBS_SHA_FIXTURE" ;; + *) exit 22 ;; +esac +EOF +chmod +x "$FIX/bin/curl" +before=$(snapshot) +rm python/testdata/python3.15.yaml +sed_inplace 's/Python 3.13.16/Python 3.13.15/g' python/testdata/python3.13.yaml +stale=$(snapshot) +PATH="$FIX/bin:$PATH" PBS_SHA_FIXTURE="$FIX/SHA256SUMS" \ + bash knife update-python-archives --dry-run > "$FIX/cli.out" +grep -q 'python archives are up to date' "$FIX/cli.out" +[ "$(snapshot)" = "$stale" ] +PATH="$FIX/bin:$PATH" PBS_SHA_FIXTURE="$FIX/SHA256SUMS" \ + bash knife update-python-archives > "$FIX/cli.out" +[ "$(snapshot)" = "$before" ] + +# Shell command failures must propagate through knife's conditional capture. +# shellcheck disable=SC2329 # Exported for the child Bash process. +jq() { command jq "$@"; return 37; } +export -f jq +if PATH="$FIX/bin:$PATH" \ + PBS_SHA_FIXTURE="$FIX/SHA256SUMS" bash knife update-python-archives > "$FIX/cli.out" 2>&1; then + echo "CLI ignored a failed shell command"; exit 1 +fi +[ "$(snapshot)" = "$before" ] +unset -f jq + +# --- numeric stable minor ordering --------------------------------------------- +python3 - <<'PYEOF' +from pathlib import Path + +Path("python/config.bzl").write_text('''"python configurations" + +PYTHON_DISTROS = ["debian13"] +PYTHON_MAJOR_VERSIONS = ["3.9"] +PYTHON_ARCHITECTURES = { + "debian13": { + "3.9": ["amd64", "arm64", "s390x", "riscv64"], + "3.10": ["arm64"], + }, +} +PYTHON_PACKAGES = { + "debian13": ["libc-bin"], +} +''') +PYEOF +echo '{"tag": "20990106"}' > release.json +make_numeric_fill_sha256sums 20990106 +PBS_RELEASE_FILE="$FIX/release.json" PBS_SHA256SUMS_FILE="$FIX/SHA256SUMS" \ + bash knife update-python-archives > "$FIX/cli.out" +grep -Fq 'PYTHON_MAJOR_VERSIONS = ["3.9", "3.10"]' python/config.bzl +[ "$(grep -Fc '"3.10": [' python/config.bzl)" = 1 ] +[ "$(get_python_archs 3.10)" = arm64 ] +[ "$(current_version 3.10 arm64)" = 3.10.1 ] +[ "$(grep -Fc 'expectedOutput: ["Python 3.10.1"]' python/testdata/python3.10.yaml)" = 2 ] +before=$(snapshot) +[ "$(run_updater)" = "NO_CHANGE" ] || { echo "stable minor selected an RC on retry"; exit 1; } +[ "$(snapshot)" = "$before" ] + +echo "update_python_archives contract OK (tag-only bump, patch bump, new minor, convergence)" diff --git a/python/update_python_archives_test.sh b/python/update_python_archives_test.sh new file mode 100755 index 000000000..c9a6f43aa --- /dev/null +++ b/python/update_python_archives_test.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Hermetic smoke test for the Python updater's parser functions. +# Verifies that the matrix and extension remain consistent without network access +# or fixtures. +set -euo pipefail + +cd "$TEST_SRCDIR/${TEST_WORKSPACE:-_main}" + +source knife.d/update_python_archives.sh + +minors=$(get_python_minors | tr '\n' ' ') +[ "$minors" = "3.14 3.15 " ] || { echo "unexpected minors: [$minors]"; exit 1; } + +for minor in $(get_python_minors); do + for arch in $(get_python_archs "$minor"); do + version=$(current_version "$minor" "$arch") + [ -n "$version" ] || { echo "missing version for ${minor}_${arch}"; exit 1; } + # Archive pins include the PBS release tag because change detection uses it. + # A tag-only bump must not be silently ignored. + pinned=$(pinned_version "$minor" "$arch") + [ -n "$pinned" ] || { echo "missing pinned version for ${minor}_${arch}"; exit 1; } + case "$pinned" in + "$version"+[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]) ;; + *) echo "pinned version for ${minor}_${arch} must be '+', got: [$pinned]"; exit 1 ;; + esac + done +done + +echo "update-python-archives parser OK"