diff --git a/OneBranchPipelines/build-release-package-pipeline.yml b/OneBranchPipelines/build-release-package-pipeline.yml index abcc40956..711b75184 100644 --- a/OneBranchPipelines/build-release-package-pipeline.yml +++ b/OneBranchPipelines/build-release-package-pipeline.yml @@ -51,6 +51,12 @@ schedules: # PIPELINE PARAMETERS # ========================= parameters: + # Experimental bounded compiler parallelism; other callers retain serial builds. + - name: linuxBuildParallelLevel + type: string + default: '1' + values: ['1', '2'] + # ADO manual runs require a non-empty string; this sentinel maps to no override below. - name: rsVersionOverride displayName: 'mssql-python-rs test version (NonOfficial only; keep committed for Official)' @@ -90,7 +96,7 @@ parameters: # Each platform uses different matrix strategy: # - Windows: Explicit per-version stages (11 stages for x64/ARM64 combos) # - macOS: Explicit per-version stages (6 stages for universal2 builds) - # - Linux: Per-distro stages, builds ALL Python versions in loop (4 stages) + # - Linux: Per-distro stages; ARM64 uses two isolated three-version shards (6 stages) # Windows Configuration Matrix # Each entry creates separate stage: Win_py_ @@ -142,7 +148,7 @@ parameters: - pyVer: '315' # Linux Configuration Matrix - # Each entry creates ONE stage that builds ALL Python versions (3.10-3.15) + # Each entry creates one isolated stage for its explicit Python-version shard. # tag: 'manylinux' (glibc-based, e.g., Ubuntu/CentOS) or 'musllinux' (musl-based, e.g., Alpine) # arch: CPU architecture for Docker platform # platform: Docker platform identifier for multi-arch builds @@ -151,11 +157,13 @@ parameters: default: # manylinux_2_28 (glibc 2.28, AlmaLinux 8 / RHEL 8+) for x86_64 and ARM64 # manylinux_2_28 wheels are forward-compatible: pip on glibc 2.34+ systems installs them fine - - { tag: 'manylinux_2_28', arch: 'x86_64', platform: 'linux/amd64' } - - { tag: 'manylinux_2_28', arch: 'aarch64', platform: 'linux/arm64' } + - { tag: 'manylinux_2_28', arch: 'x86_64', platform: 'linux/amd64', shard: 'all', pythonBins: 'cp310 cp311 cp312 cp313 cp314 cp315' } + - { tag: 'manylinux_2_28', arch: 'aarch64', platform: 'linux/arm64', shard: 'py310_312', pythonBins: 'cp310 cp311 cp312' } + - { tag: 'manylinux_2_28', arch: 'aarch64', platform: 'linux/arm64', shard: 'py313_315', pythonBins: 'cp313 cp314 cp315' } # musllinux (musl-based) for x86_64 and ARM64 - - { tag: 'musllinux', arch: 'x86_64', platform: 'linux/amd64' } - - { tag: 'musllinux', arch: 'aarch64', platform: 'linux/arm64' } + - { tag: 'musllinux', arch: 'x86_64', platform: 'linux/amd64', shard: 'all', pythonBins: 'cp310 cp311 cp312 cp313 cp314 cp315' } + - { tag: 'musllinux', arch: 'aarch64', platform: 'linux/arm64', shard: 'py310_312', pythonBins: 'cp310 cp311 cp312' } + - { tag: 'musllinux', arch: 'aarch64', platform: 'linux/arm64', shard: 'py313_315', pythonBins: 'cp313 cp314 cp315' } # ========================= # ODBC PACKAGE CONFIGURATIONS (mssql-python-odbc) @@ -391,11 +399,47 @@ extends: # ========================= # PIPELINE STAGES # ========================= - # mssql-python: 11 Windows + 6 macOS + 4 Linux + 1 Consolidate = 22 stages + # mssql-python: 11 Windows + 6 macOS + 6 Linux; 41 wheels unchanged. # mssql-python-odbc: 1 ODBC_BuildAll (single host, all 7 wheels) + 1 ConsolidateOdbc = 2 stages - # Total: 24 stages, always built together. The mssql-python build stages depend on - # ConsolidateOdbc so they install the external ODBC wheel before pytest. + # Platform consumers wait for the scanned ODBC producer, not its compatibility hop. + # Runtime transport is staged early and reused verbatim by final consolidation. stages: + - stage: RuntimeWheels + displayName: 'Stage exact-version Rust runtime wheels early' + dependsOn: [] + jobs: + - job: StageWheels + pool: + type: linux + isCustom: true + name: Azure Pipelines + vmImage: 'ubuntu-latest' + variables: + ob_outputDirectory: '$(Build.ArtifactStagingDirectory)' + ob_sdl_binskim_enabled: false + steps: + - checkout: self + - ${{ if eq(variables.effectiveOneBranchType, 'Official') }}: + - task: PowerShell@2 + inputs: + pwsh: true + targetType: filePath + filePath: OneBranchPipelines/scripts/validate-release-versions.ps1 + arguments: '-BuildOnly' + displayName: 'Reject test overrides and prereleases before Official build' + - bash: | + set -euo pipefail + python3 eng/scripts/download_mssql_python_rs_wheels.py --output-dir "$(ob_outputDirectory)/rs-wheels" + displayName: 'Download and validate exact runtime transport' + - template: /OneBranchPipelines/steps/malware-scanning-step.yml@self + parameters: + scanPath: '$(ob_outputDirectory)' + artifactType: 'pkg' + - task: PublishPipelineArtifact@1 + inputs: + targetPath: '$(ob_outputDirectory)' + artifact: 'drop_RuntimeWheels_StageWheels' + publishLocation: 'pipeline' # ========================= # WINDOWS BUILD STAGES # ========================= @@ -425,7 +469,9 @@ extends: signWindowsBinaries: ${{ parameters.signWindowsBinaries }} # Phase 2: install the external ODBC wheel before pytest (bundled driver removed). odbcDependsOn: - - ConsolidateOdbc + - ODBC_BuildAll + - RuntimeWheels + odbcArtifactName: 'drop_ODBC_BuildAll_BuildWheel' installOdbcWheel: true # ========================= @@ -454,15 +500,17 @@ extends: oneBranchType: '${{ variables.effectiveOneBranchType }}' # Phase 2: install the external ODBC wheel before pytest (bundled driver removed). odbcDependsOn: - - ConsolidateOdbc + - ODBC_BuildAll + - RuntimeWheels + odbcArtifactName: 'drop_ODBC_BuildAll_BuildWheel' installOdbcWheel: true # ========================= # LINUX BUILD STAGES # ========================= - # Strategy: One stage per distribution × architecture - # Total: 4 stages (manylinux_2_28×2 + musllinux×2) - # Each stage builds ALL Python versions (3.10-3.15) in a loop + # Strategy: One stage per distribution × architecture × shard + # Total: 6 stages (two x64 full sets + four ARM64 three-version shards). + # Every distribution/architecture still builds/tests Python 3.10-3.15. # Distributions: # - manylinux_2_28: glibc 2.28+ (RHEL 8, Ubuntu 20.04+, etc.) — forward-compatible with newer glibc # - musllinux: musl-based (Alpine Linux) @@ -475,27 +523,31 @@ extends: # b. Builds wheel # c. Installs wheel in isolated directory # d. Runs pytest against SQL Server - # 4. Publishes artifacts (all 6 wheels) + # 4. Publishes artifacts (six x64 wheels or three ARM64 wheels per shard) # 5. Component Governance + AntiMalware scanning - ${{ each config in parameters.linuxConfigs }}: - template: /OneBranchPipelines/stages/build-linux-single-stage.yml@self parameters: - stageName: Linux_${{ config.tag }}_${{ config.arch }} + stageName: Linux_${{ config.tag }}_${{ config.arch }}_${{ config.shard }} jobName: BuildWheels linuxTag: ${{ config.tag }} arch: ${{ config.arch }} dockerPlatform: ${{ config.platform }} + pythonBins: ${{ config.pythonBins }} + buildParallelLevel: ${{ parameters.linuxBuildParallelLevel }} oneBranchType: '${{ variables.effectiveOneBranchType }}' # Phase 2: install the external ODBC wheel before pytest (bundled driver removed). odbcDependsOn: - - ConsolidateOdbc + - ODBC_BuildAll + - RuntimeWheels + odbcArtifactName: 'drop_ODBC_BuildAll_BuildWheel' installOdbcWheel: true # ========================= # CONSOLIDATE STAGE # ========================= # Purpose: Collect all artifacts from platform builds into single dist/ folder - # Dependencies: All 21 build stages (11 Windows + 6 macOS + 4 Linux) + # Dependencies: All 23 build stages and the early Rust transport producer. # Stages run in parallel, Consolidate waits for ALL to complete # Outputs: # - dist/wheels/*.whl (all platform wheels) @@ -506,6 +558,7 @@ extends: - stage: Consolidate displayName: 'Consolidate All Artifacts' dependsOn: + - RuntimeWheels # Windows dependencies (11 stages) - Win_py310_x64 - Win_py311_x64 @@ -525,11 +578,9 @@ extends: - MacOS_py313 - MacOS_py314 - MacOS_py315 - # Linux dependencies (4 stages) - - Linux_manylinux_2_28_x86_64 - - Linux_manylinux_2_28_aarch64 - - Linux_musllinux_x86_64 - - Linux_musllinux_aarch64 + # Configuration-derived dependencies include both isolated ARM64 shards. + - ${{ each config in parameters.linuxConfigs }}: + - Linux_${{ config.tag }}_${{ config.arch }}_${{ config.shard }} jobs: - template: /OneBranchPipelines/jobs/consolidate-artifacts-job.yml@self parameters: @@ -555,7 +606,7 @@ extends: # stages install the matching ODBC wheel before their pytest (Phase 2 removed the # bundled driver, so the mssql-python tests now require the external package). # The ODBC wheels are therefore produced FIRST, ahead of the mssql-python build - # stages, which depend on ConsolidateOdbc (below) to obtain the wheel. + # stages, which depend directly on the successful scanned ODBC_BuildAll stage. - template: /OneBranchPipelines/stages/build-odbc-all-stage.yml@self parameters: stageName: ODBC_BuildAll @@ -567,8 +618,8 @@ extends: # ========================================================================= # Collects the 7 mssql-python-odbc wheels into a single dist/ folder and # publishes them as `drop_ConsolidateOdbc_ConsolidateArtifacts`. Runs - # UNCONDITIONALLY because the mssql-python build stages depend on it to install - # the ODBC wheel before pytest. The release pipeline selects this artifact when + # UNCONDITIONALLY for downstream compatibility, off the platform critical path. + # The release pipeline selects this artifact when # its `releasePackage` parameter targets mssql-python-odbc. - stage: ConsolidateOdbc displayName: 'Consolidate All ODBC Artifacts' @@ -583,5 +634,5 @@ extends: # NOTE: The former post-consolidation "TestBothWheels_*" stages were removed. # Phase 2 removed the bundled ODBC driver from the mssql-python wheel, and the # mssql-python build stages now install the external mssql-python-odbc wheel - # (from ConsolidateOdbc) and run the full pytest suite against it — so the + # (from ODBC_BuildAll) and run the full pytest suite against it — so the # external-package resolution is already validated end-to-end during the build. diff --git a/OneBranchPipelines/jobs/consolidate-artifacts-job.yml b/OneBranchPipelines/jobs/consolidate-artifacts-job.yml index 19d7f0cb1..ddc14a938 100644 --- a/OneBranchPipelines/jobs/consolidate-artifacts-job.yml +++ b/OneBranchPipelines/jobs/consolidate-artifacts-job.yml @@ -1,7 +1,7 @@ # Consolidate Artifacts Job Template # Downloads artifacts from all platform build stages and consolidates into single dist/ folder -# Works with individual stage artifacts (21 stages total: 11 Windows + 6 macOS + 4 Linux) -# Each Linux stage builds 6 Python versions (3.10-3.15), resulting in 41 total wheels +# Collects 11 Windows + 6 macOS + 6 Linux stages (ARM64 split into two shards). +# The wheel matrix remains 41: 11 Windows + 6 macOS + 24 Linux. parameters: - name: oneBranchType type: string @@ -126,10 +126,18 @@ jobs: continueOnError: true # Carry the effective runtime selection with the artifact, including test overrides. + # Reuse the exact early transport; no late network download/version fallback. + - task: DownloadPipelineArtifact@2 + displayName: 'Download early validated runtime transport' + inputs: + buildType: 'current' + artifactName: 'drop_RuntimeWheels_StageWheels' + itemPattern: 'rs-wheels/**' + targetPath: '$(ob_outputDirectory)' - bash: | - set -e + set -euo pipefail python3 "$(Build.SourcesDirectory)/eng/scripts/download_mssql_python_rs_wheels.py" \ - --output-dir "$(ob_outputDirectory)/rs-wheels" + --verify-only --output-dir "$(ob_outputDirectory)/rs-wheels" python3 -c "import json,pathlib; root=pathlib.Path('$(ob_outputDirectory)'); receipt=json.loads((root/'rs-wheels/transport.json').read_text()); (root/'dist/mssql-python-rs.version').write_text(receipt['distribution_version']+'\n'); (root/'dist/transport.json').write_bytes((root/'rs-wheels/transport.json').read_bytes())" echo "mssql-python-rs version: $(cat "$(ob_outputDirectory)/dist/mssql-python-rs.version")" displayName: 'Stage effective mssql-python-rs wheels, version and receipt' diff --git a/OneBranchPipelines/stages/build-linux-single-stage.yml b/OneBranchPipelines/stages/build-linux-single-stage.yml index 4a740aee2..1f8f758f0 100644 --- a/OneBranchPipelines/stages/build-linux-single-stage.yml +++ b/OneBranchPipelines/stages/build-linux-single-stage.yml @@ -1,8 +1,18 @@ # Linux Single Configuration Stage Template # Builds Python wheels for a specific Linux distribution and architecture -# Builds for Python 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 within single job +# Builds/tests the explicit Python shard in its own job, workspace and SQL instance. # Tests each wheel after building with isolated pytest execution parameters: + - name: pythonBins + type: string + default: 'cp310 cp311 cp312 cp313 cp314 cp315' + - name: buildParallelLevel + type: string + default: '1' + values: ['1', '2'] + - name: odbcArtifactName + type: string + default: 'drop_ConsolidateOdbc_ConsolidateArtifacts' # Stage identifier (e.g., 'Linux_manylinux_2_28_x86_64') - name: stageName type: string @@ -70,6 +80,8 @@ stages: # Docker platform for QEMU-based cross-compilation - name: DOCKER_PLATFORM value: ${{ parameters.dockerPlatform }} + - name: PIP_CACHE_DIR + value: '$(Pipeline.Workspace)/.pip-cache' steps: - checkout: self @@ -84,6 +96,12 @@ stages: filePath: OneBranchPipelines/scripts/validate-release-versions.ps1 arguments: '-BuildOnly' + - task: Cache@2 + displayName: 'Cache Linux pip downloads' + inputs: + key: 'release-pip-v1 | "$(Agent.OS)" | "${{ parameters.linuxTag }}" | "${{ parameters.arch }}" | "${{ parameters.pythonBins }}" | eng/requirements-build-linux.txt | eng/requirements-test-linux.txt' + path: '$(PIP_CACHE_DIR)' + # Docker is pre-installed now # Verify it's working and start the daemon - bash: | @@ -122,6 +140,8 @@ stages: displayName: 'Prepare artifact directories' - script: | + set -euo pipefail + mkdir -p "$(PIP_CACHE_DIR)" # Determine image based on LINUX_TAG and ARCH # Pull the public PyPA images directly because GHCR is not reliably # reachable from the hosted 1ES agents. @@ -138,7 +158,8 @@ stages: docker run -e MSSQL_PYTHON_RS_VERSION -d --name build-$(LINUX_TAG)-$(ARCH) \ --platform $(DOCKER_PLATFORM) \ - -v $(Build.SourcesDirectory):/workspace \ + -v "$(Build.SourcesDirectory):/workspace" \ + -v "$(PIP_CACHE_DIR):/pip-cache" \ -w /workspace \ $IMAGE \ tail -f /dev/null @@ -179,6 +200,25 @@ stages: # for any other deps and must NOT fail the job if the in-container package # manager is flaky under emulation (the header gate below is the real check). if [[ "$(LINUX_TAG)" == "manylinux_2_28" ]]; then + # ODBC requires CP949 conversion modules for Korean VARCHAR columns. + docker exec "$CONTAINER" bash -lc ' + set -euo pipefail + if command -v dnf >/dev/null 2>&1; then + dnf -y install glibc-gconv-extra + elif command -v yum >/dev/null 2>&1; then + yum -y install glibc-gconv-extra + else + echo "ERROR: Cannot install required glibc-gconv-extra" >&2 + exit 1 + fi + actual=$(printf "\xbe\xc8\xb3\xe7\xc7\xcf\xbc\xbc\xbf\xe4" | iconv -f CP949 -t UTF-8) + expected=$(printf "\xec\x95\x88\xeb\x85\x95\xed\x95\x98\xec\x84\xb8\xec\x9a\x94") + if [ "$actual" != "$expected" ]; then + echo "ERROR: CP949 to UTF-8 conversion failed fidelity check" >&2 + exit 1 + fi + echo "CP949 conversion verified" + ' docker exec "$CONTAINER" bash -lc ' set -uo pipefail if command -v dnf >/dev/null 2>&1; then @@ -211,33 +251,23 @@ stages: - script: | set -euo pipefail - echo "Starting SQL Server 2022 container for testing..." - docker run -d --name sqlserver-$(LINUX_TAG)-$(ARCH) \ - --platform linux/amd64 \ - -e ACCEPT_EULA=Y \ - -e MSSQL_SA_PASSWORD \ - -p 1433:1433 \ - mcr.microsoft.com/mssql/server:2022-latest - - echo "Waiting for SQL Server to be ready..." - for i in {1..30}; do - if docker exec -e SQLCMDPASSWORD sqlserver-$(LINUX_TAG)-$(ARCH) /opt/mssql-tools18/bin/sqlcmd \ - -S localhost -U SA -C -Q "SELECT 1" >/dev/null 2>&1; then - echo "✓ SQL Server is ready!" - break - fi - sleep 2 - done + python3 eng/scripts/setup_sql_container.py \ + --name "sqlserver-$(LINUX_TAG)-$(ARCH)" \ + --owner "$(Build.BuildId).$(System.JobId)" \ + --image mcr.microsoft.com/mssql/server:2022-latest # Get SQL Server container IP for build container to connect SQL_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' sqlserver-$(LINUX_TAG)-$(ARCH)) + if [ -z "$SQL_IP" ]; then + echo "ERROR: Ready SQL container has no bridge IP" >&2 + exit 1 + fi echo "SQL Server IP: $SQL_IP" echo "##vso[task.setvariable variable=SQL_IP]$SQL_IP" displayName: 'Start SQL Server container for testing' + timeoutInMinutes: 23 env: DB_PASSWORD: $(DB_PASSWORD) - MSSQL_SA_PASSWORD: $(DB_PASSWORD) - SQLCMDPASSWORD: $(DB_PASSWORD) # ========================= # PHASE 2: EXTERNAL ODBC DRIVER PACKAGE @@ -245,7 +275,7 @@ stages: # Phase 2 removed the bundled ODBC driver from the mssql-python wheel, so the # isolated-install pytest below must obtain the driver from the external # mssql-python-odbc package. Download the wheels built earlier this run - # (ConsolidateOdbc) into the repo dir (bind-mounted at /workspace in the build + # (the selected successful ODBC producer) into the repo dir (bind-mounted at /workspace in the build # container) and flatten them so PIP_FIND_LINKS=/workspace/odbc_wheels lets the # in-container `pip install ` resolve the pinned # mssql-python-odbc==18.6.2 dependency locally (no PyPI needed for it). @@ -254,7 +284,7 @@ stages: displayName: 'Download consolidated ODBC wheels' inputs: buildType: 'current' - artifactName: 'drop_ConsolidateOdbc_ConsolidateArtifacts' + artifactName: '${{ parameters.odbcArtifactName }}' itemPattern: '**/*.whl' targetPath: '$(Build.SourcesDirectory)/odbc_wheels' - bash: | @@ -271,9 +301,18 @@ stages: set -euo pipefail if [[ "$(LINUX_TAG)" == "manylinux_2_28" ]]; then SHELL_EXE=bash; else SHELL_EXE=sh; fi docker exec build-$(LINUX_TAG)-$(ARCH) $SHELL_EXE -lc 'mkdir -p /workspace/dist' + # Cap the experiment at two compiler processes and available host resources. + # Keep ~2 GiB available per compiler; SQL Server runs in its own container. + CPU_COUNT=$(getconf _NPROCESSORS_ONLN) + MEMORY_GIB=$(awk '/MemAvailable/ {print int($2/1024/1024)}' /proc/meminfo) + CMAKE_BUILD_PARALLEL_LEVEL=${{ parameters.buildParallelLevel }} + if [ "$CPU_COUNT" -lt "$CMAKE_BUILD_PARALLEL_LEVEL" ]; then CMAKE_BUILD_PARALLEL_LEVEL=$CPU_COUNT; fi + if [ "$MEMORY_GIB" -lt 4 ]; then CMAKE_BUILD_PARALLEL_LEVEL=1; fi + export CMAKE_BUILD_PARALLEL_LEVEL + echo "Compiler experiment: parallel=$CMAKE_BUILD_PARALLEL_LEVEL CPUs=$CPU_COUNT availableGiB=$MEMORY_GIB" # Loop through all Python versions: build wheel -> test wheel -> repeat - for PYBIN in cp310 cp311 cp312 cp313 cp314 cp315; do + for PYBIN in ${{ parameters.pythonBins }}; do echo "" echo "=====================================================" echo "Building and testing $PYBIN on $(LINUX_TAG)/$(ARCH)" @@ -281,12 +320,12 @@ stages: if [[ "$(LINUX_TAG)" == "manylinux_2_28" ]]; then # Manylinux (glibc-based) - use bash - docker exec -e PYBIN=$PYBIN -e SQL_IP=$(SQL_IP) -e DB_PASSWORD -e MANYLINUX_TAG="$(LINUX_TAG)" -e PIP_FIND_LINKS="/workspace/odbc_wheels" build-$(LINUX_TAG)-$(ARCH) bash -lc ' + docker exec -e CMAKE_BUILD_PARALLEL_LEVEL -e PYBIN=$PYBIN -e PIP_CACHE_DIR=/pip-cache/$PYBIN -e SQL_IP=$(SQL_IP) -e DB_PASSWORD -e MANYLINUX_TAG="$(LINUX_TAG)" -e PIP_FIND_LINKS="/workspace/odbc_wheels" build-$(LINUX_TAG)-$(ARCH) bash -lc ' set -euo pipefail; # Step 1: Setup Python environment PY=/opt/python/${PYBIN}-${PYBIN}/bin/python; - test -x $PY || { echo "Python $PY missing - skipping"; exit 0; }; + test -x $PY || { echo "ERROR: Required Python $PY missing"; exit 1; }; ln -sf $PY /usr/local/bin/python; echo "Using: $(python --version)"; @@ -296,7 +335,9 @@ stages: # Step 3: Build native extension (.so) echo "Building native extension..."; cd /workspace/mssql_python/pybind; + BUILD_STARTED=$(date +%s); bash build.sh; + echo "NATIVE_BUILD_SECONDS=$(( $(date +%s) - BUILD_STARTED )) parallel=$CMAKE_BUILD_PARALLEL_LEVEL python=$PYBIN"; # Step 3.5: Install mssql-python-rs for this Python version bash /workspace/eng/scripts/install-mssql-py-core.sh; @@ -365,12 +406,12 @@ stages: ' else # Musllinux (musl libc-based) - use sh - docker exec -e PYBIN=$PYBIN -e SQL_IP=$(SQL_IP) -e DB_PASSWORD -e MANYLINUX_TAG="$(LINUX_TAG)" -e PIP_FIND_LINKS="/workspace/odbc_wheels" build-$(LINUX_TAG)-$(ARCH) sh -lc ' + docker exec -e CMAKE_BUILD_PARALLEL_LEVEL -e PYBIN=$PYBIN -e PIP_CACHE_DIR=/pip-cache/$PYBIN -e SQL_IP=$(SQL_IP) -e DB_PASSWORD -e MANYLINUX_TAG="$(LINUX_TAG)" -e PIP_FIND_LINKS="/workspace/odbc_wheels" build-$(LINUX_TAG)-$(ARCH) sh -lc ' set -euo pipefail; # Step 1: Setup Python environment PY=/opt/python/${PYBIN}-${PYBIN}/bin/python; - test -x $PY || { echo "Python $PY missing - skipping"; exit 0; }; + test -x $PY || { echo "ERROR: Required Python $PY missing"; exit 1; }; ln -sf $PY /usr/local/bin/python; echo "Using: $(python --version)"; @@ -380,7 +421,9 @@ stages: # Step 3: Build native extension (.so) echo "Building native extension..."; cd /workspace/mssql_python/pybind; + BUILD_STARTED=$(date +%s); bash build.sh; + echo "NATIVE_BUILD_SECONDS=$(( $(date +%s) - BUILD_STARTED )) parallel=$CMAKE_BUILD_PARALLEL_LEVEL python=$PYBIN"; # Step 3.5: Install mssql-python-rs for this Python version bash /workspace/eng/scripts/install-mssql-py-core.sh; @@ -458,7 +501,7 @@ stages: echo "=====================================================" echo "✓ All Python versions built and tested successfully!" echo "=====================================================" - displayName: 'Build and test wheels for Python 3.10-3.15' + displayName: 'Build and test wheels for ${{ parameters.pythonBins }}' env: DB_PASSWORD: $(DB_PASSWORD) @@ -485,11 +528,19 @@ stages: echo "✓ Artifacts copied successfully" displayName: 'Copy artifacts to host' - # Cleanup: Stop and remove Docker containers + - script: | + python3 eng/scripts/setup_sql_container.py --cleanup \ + --name "sqlserver-$(LINUX_TAG)-$(ARCH)" \ + --owner "$(Build.BuildId).$(System.JobId)" + displayName: 'Clean up Linux SQL container' + condition: always() + timeoutInMinutes: 3 + + # Cleanup: Stop and remove the build container - script: | echo "Stopping and removing containers..." - docker stop build-$(LINUX_TAG)-$(ARCH) sqlserver-$(LINUX_TAG)-$(ARCH) || true - docker rm build-$(LINUX_TAG)-$(ARCH) sqlserver-$(LINUX_TAG)-$(ARCH) || true + docker stop build-$(LINUX_TAG)-$(ARCH) || true + docker rm build-$(LINUX_TAG)-$(ARCH) || true echo "✓ Containers cleaned up" displayName: 'Cleanup containers' condition: always() # Always run cleanup, even if build/test fails diff --git a/OneBranchPipelines/stages/build-macos-single-stage.yml b/OneBranchPipelines/stages/build-macos-single-stage.yml index cd4acc020..b95af3eba 100644 --- a/OneBranchPipelines/stages/build-macos-single-stage.yml +++ b/OneBranchPipelines/stages/build-macos-single-stage.yml @@ -3,6 +3,9 @@ # Universal2 = combined x86_64 + ARM64 binary in single .so file # Tests with Docker-based SQL Server (using Colima as Docker runtime) parameters: + - name: odbcArtifactName + type: string + default: 'drop_ConsolidateOdbc_ConsolidateArtifacts' # Stage identifier (e.g., 'MacOS_py312') - name: stageName type: string @@ -69,6 +72,10 @@ stages: # Python version as 3-digit string (e.g., '312') for file naming - name: shortPyVer value: ${{ parameters.shortPyVer }} + - name: DOCKER_CONTEXT + value: colima + - name: PIP_CACHE_DIR + value: '$(Pipeline.Workspace)/.pip-cache' steps: # ========================= @@ -96,6 +103,14 @@ stages: addToPath: true displayName: 'Use Python ${{ parameters.pythonVersion }}' continueOnError: false + + - task: Cache@2 + inputs: + key: 'release-pip-v1 | "$(Agent.OS)" | "$(Agent.OSArchitecture)" | "${{ parameters.pythonVersion }}" | eng/requirements-build-macos.txt' + restoreKeys: | + release-pip-v1 | "$(Agent.OS)" | "$(Agent.OSArchitecture)" | "${{ parameters.pythonVersion }}" + path: $(PIP_CACHE_DIR) + displayName: 'Cache release pip downloads' # ========================= # BUILD TOOLS @@ -104,34 +119,67 @@ stages: # Do not run brew update: hosted runners already provide bottle metadata, # while updating can select formulae that compile Go and Lima from source. - script: | + set -euo pipefail brew uninstall cmake --ignore-dependencies || echo "CMake not installed" brew install cmake docker colima displayName: 'Install build & container tooling (Homebrew)' - # ========================= - # PYTHON DEPENDENCIES - # ========================= - # Install build dependencies: - # - requirements-build-macos.txt: tested, hash-locked build and test dependencies + # Match PR validation: keep setup in the same task so it is joined and + # cleaned up on build failure rather than outliving the task. - script: | + set -euo pipefail + SQL_LOG="$(Agent.TempDirectory)/sql-setup-$(System.JobId).log" + SQL_HELPER="$(Build.SourcesDirectory)/eng/scripts/setup_sql_container.py" + SQL_OWNER="$(Build.BuildId).$(System.JobId)" + SQL_PID= + finish_setup() { + status=$? + trap - EXIT INT TERM + if [ -n "$SQL_PID" ]; then + if kill -0 "$SQL_PID" 2>/dev/null; then + kill -TERM "$SQL_PID" || echo "[sql] Background setup already stopped" + fi + wait "$SQL_PID" || echo "[sql] Background setup stopped or failed" + fi + if [ -f "$SQL_LOG" ]; then + cat "$SQL_LOG" + rm -f "$SQL_LOG" + fi + if [ "$status" -ne 0 ]; then + python3 "$SQL_HELPER" --name sqlserver --owner "$SQL_OWNER" --colima --cleanup \ + || echo "[sql] Cleanup failed; final job cleanup will also run" + fi + exit "$status" + } + trap finish_setup EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + + ( umask 077; : > "$SQL_LOG" ) + python3 "$SQL_HELPER" --name sqlserver --owner "$SQL_OWNER" \ + --image mcr.microsoft.com/mssql/server:2022-latest --colima --retry-colima > "$SQL_LOG" 2>&1 & + SQL_PID=$! + python --version python -m pip --version python -m pip install --require-hashes -r eng/requirements-build-macos.txt - displayName: 'Install dependencies' - - # ========================= - # NATIVE EXTENSION BUILD - # ========================= - # Build universal2 .so binary (x86_64 + ARM64 in single file) - # build.sh sets ARCHFLAGS="-arch x86_64 -arch arm64" for clang - # Output: mssql_python.cpython-3XX-darwin.so (Mach-O universal binary) - - script: | + echo "Python Version: ${{ parameters.pythonVersion }}" echo "Building Universal2 Binary" - cd "$(Build.SourcesDirectory)/mssql_python/pybind" - ./build.sh - displayName: 'Build .so file' - continueOnError: false + ( cd "$(Build.SourcesDirectory)/mssql_python/pybind" && ./build.sh ) + + SQL_STATUS=0 + wait "$SQL_PID" || SQL_STATUS=$? + SQL_PID= + if [ "$SQL_STATUS" -ne 0 ]; then + exit "$SQL_STATUS" + fi + displayName: 'Build universal2 bindings alongside SQL setup' + timeoutInMinutes: 50 + env: + DB_PASSWORD: $(DB_PASSWORD) + MSSQL_SA_PASSWORD: $(DB_PASSWORD) + SQLCMDPASSWORD: $(DB_PASSWORD) # Copy native extension to artifact directory for later inspection # .so file will be packaged into wheel in later step @@ -142,44 +190,6 @@ stages: TargetFolder: '$(ob_outputDirectory)/bindings/macOS' displayName: 'Copy .so files' - # Start Colima (macOS Docker runtime). Tooling is installed above so the - # 15-minute timeout covers only VM startup, not Homebrew compilation. - # Colima = lightweight Docker Desktop alternative using macOS virtualization - # 4 CPU cores + 8GB RAM needed for SQL Server container - - script: | - colima start --cpu 4 --memory 8 --disk 50 - docker context use colima >/dev/null || true - docker version - displayName: 'Start Docker (Colima)' - timeoutInMinutes: 15 - - # ========================= - # SQL SERVER CONTAINER - # ========================= - # Start SQL Server 2022 Docker container for pytest execution - # macOS uses host networking (localhost:1433) vs Linux uses container IP - # Container runs in background (-d) and accepts connections on port 1433 - - script: | - docker pull mcr.microsoft.com/mssql/server:2022-latest - docker run --name sqlserver \ - -e ACCEPT_EULA=Y \ - -e MSSQL_SA_PASSWORD \ - -p 1433:1433 -d \ - mcr.microsoft.com/mssql/server:2022-latest - - # Wait for SQL Server to accept connections (up to 60 seconds) - # sqlcmd -C flag = trust server certificate (for TLS connection) - for i in {1..30}; do - docker exec -e SQLCMDPASSWORD sqlserver /opt/mssql-tools18/bin/sqlcmd \ - -S localhost -U SA -C -Q "SELECT 1" && break - sleep 2 - done - displayName: 'Start SQL Server (Docker)' - env: - DB_PASSWORD: $(DB_PASSWORD) - MSSQL_SA_PASSWORD: $(DB_PASSWORD) - SQLCMDPASSWORD: $(DB_PASSWORD) - # ========================= # MSSQL-PYTHON-RS INSTALLATION # ========================= @@ -199,7 +209,7 @@ stages: displayName: 'Download consolidated ODBC wheels' inputs: buildType: 'current' - artifactName: 'drop_ConsolidateOdbc_ConsolidateArtifacts' + artifactName: '${{ parameters.odbcArtifactName }}' itemPattern: '**/*.whl' targetPath: '$(Pipeline.Workspace)/odbc_wheels' - script: | @@ -232,6 +242,15 @@ stages: # Connection string uses localhost (SQL Server container exposed on port 1433) # TrustServerCertificate=yes bypasses SSL cert validation (test env only) DB_CONNECTION_STRING: 'Server=tcp:127.0.0.1,1433;Database=master;Uid=SA;Pwd=$(DB_PASSWORD);TrustServerCertificate=yes' + + - script: | + python3 eng/scripts/setup_sql_container.py --cleanup --colima \ + --name sqlserver --owner "$(Build.BuildId).$(System.JobId)" + displayName: 'Clean up macOS SQL container' + condition: always() + timeoutInMinutes: 3 + env: + DB_PASSWORD: $(DB_PASSWORD) # ========================= # WHEEL BUILD diff --git a/OneBranchPipelines/stages/build-odbc-all-stage.yml b/OneBranchPipelines/stages/build-odbc-all-stage.yml index ff4ccc8f4..1fa943fb9 100644 --- a/OneBranchPipelines/stages/build-odbc-all-stage.yml +++ b/OneBranchPipelines/stages/build-odbc-all-stage.yml @@ -57,12 +57,12 @@ parameters: stages: - stage: ${{ parameters.stageName }} displayName: 'ODBC Build All Wheels (single host)' - # This stage MUST run first: the mssql-python build stages depend on - # ConsolidateOdbc, which depends on this stage. It is declared LAST in the + # This stage MUST run first: the mssql-python build stages and the compatibility + # ConsolidateOdbc stage depend on it. It is declared LAST in the # orchestrator YAML (right after Consolidate), so WITHOUT an explicit empty # dependsOn, Azure's implicit "depends on the previous stage" rule would chain it # to Consolidate and form a cycle: - # ODBC_BuildAll -> Consolidate -> (18 platform builds) -> ConsolidateOdbc -> ODBC_BuildAll + # ODBC_BuildAll -> Consolidate -> (platform builds) -> ODBC_BuildAll # which fails the pipeline at compile time. An empty dependsOn breaks that implicit # link so ODBC_BuildAll has no dependencies and runs first. dependsOn: [] @@ -138,6 +138,8 @@ stages: $ErrorActionPreference = "Stop" Add-Type -AssemblyName System.IO.Compression.FileSystem $wheelDir = "$(ob_outputDirectory)\wheels" + $wheelCount = @(Get-ChildItem -Path $wheelDir -Filter "*.whl").Count + if ($wheelCount -ne 7) { throw "Expected exactly 7 ODBC wheels, found $wheelCount" } # tag -> @{ Must = ; Forbid = } # Must uses the EXACT driver filenames (not loose 'msodbcsql'/'.so'/'.dylib', diff --git a/OneBranchPipelines/stages/build-windows-single-stage.yml b/OneBranchPipelines/stages/build-windows-single-stage.yml index 6db191523..1f0c46bc8 100644 --- a/OneBranchPipelines/stages/build-windows-single-stage.yml +++ b/OneBranchPipelines/stages/build-windows-single-stage.yml @@ -3,6 +3,9 @@ # Supports both x64 (AMD64) and ARM64 cross-compilation # Tests x64 builds with pytest (ARM64 binaries can't run on x64 host) parameters: + - name: odbcArtifactName + type: string + default: 'drop_ConsolidateOdbc_ConsolidateArtifacts' # Stage identifier (e.g., 'Win_py312_x64') - name: stageName type: string @@ -71,6 +74,7 @@ stages: shortPyVer: ${{ parameters.shortPyVer }} # Target architecture (can differ from host for cross-compilation) targetArch: ${{ parameters.architecture }} + PIP_CACHE_DIR: '$(Pipeline.Workspace)\.pip-cache' # Arch suffix used in the built extension's file name. build.bat maps the # target arch to the wheel/PE tag: x64 -> amd64, arm64 -> arm64, x86 -> win32. # Used to name the exact .pyd for signing (no wildcards). @@ -160,6 +164,12 @@ stages: python -c "import platform; print(platform.machine())" displayName: 'Verify Python installation' + - task: Cache@2 + displayName: 'Cache Windows pip downloads' + inputs: + key: 'release-pip-v1 | "$(Agent.OS)" | "$(Agent.OSArchitecture)" | "${{ parameters.pythonVersion }}" | "${{ parameters.architecture }}" | eng/requirements-build-windows.txt' + path: '$(PIP_CACHE_DIR)' + - powershell: | $ErrorActionPreference = "Stop" Write-Host "Installing Python dependencies..." @@ -336,7 +346,7 @@ stages: condition: ne(variables['targetArch'], 'arm64') inputs: buildType: 'current' - artifactName: 'drop_ConsolidateOdbc_ConsolidateArtifacts' + artifactName: '${{ parameters.odbcArtifactName }}' itemPattern: '**/*.whl' targetPath: '$(Pipeline.Workspace)/odbc_wheels' - powershell: | diff --git a/eng/conda_tools/provenance.py b/eng/conda_tools/provenance.py index 2d0a2096e..f581da820 100644 --- a/eng/conda_tools/provenance.py +++ b/eng/conda_tools/provenance.py @@ -116,13 +116,22 @@ def _wheel_security_reasons(get_json: Callable[[str], dict], build: dict, run: d if not isinstance(configs, list) or not configs: return [f"wheel producer {parameter} evidence is missing"] for config in configs: - if not isinstance(config, dict) or any( + if not isinstance(config, dict): + return [f"wheel producer {parameter} evidence is invalid"] + identity_fields = ( + (*fields, "shard") + if parameter == "linuxConfigs" and "shard" in config + else fields + ) + if any( not isinstance(config.get(field), str) or not re.fullmatch(r"[a-zA-Z0-9_]+", config[field]) - for field in fields + for field in identity_fields ): return [f"wheel producer {parameter} evidence is invalid"] - identifier = prefix + "_".join(config[field] for field in fields) + f".{job}.__default" + identifier = ( + prefix + "_".join(config[field] for field in identity_fields) + f".{job}.__default" + ) if identifier in expected_jobs: return [f"wheel producer {parameter} contains duplicate jobs"] expected_jobs.add(identifier) diff --git a/eng/scripts/download_mssql_python_rs_wheels.py b/eng/scripts/download_mssql_python_rs_wheels.py index 212929ea6..89a820c46 100644 --- a/eng/scripts/download_mssql_python_rs_wheels.py +++ b/eng/scripts/download_mssql_python_rs_wheels.py @@ -5,9 +5,14 @@ import argparse import hashlib +import http.client import json import re import shutil +import socket +import tempfile +import time +import urllib.error import urllib.request import zipfile from email.parser import BytesParser @@ -23,6 +28,69 @@ from mssql_python_rs import DEFAULT_INDEX, DEV_INDEX, VERSION_FILE, resolve_runtime PACKAGE_ID = "mssql-python-rs" +DOWNLOAD_ATTEMPTS = 3 + + +def _transient(error: Exception) -> bool: + if isinstance(error, urllib.error.HTTPError): + return error.code in {408, 429, 500, 502, 503, 504} + if isinstance(error, urllib.error.URLError): + error = error.reason + return isinstance( + error, + (TimeoutError, socket.gaierror, ConnectionError, http.client.IncompleteRead), + ) + + +def _fetch(url: str, consume): + """Retry only transient transport failures; never retry invalid wheel contents.""" + for attempt in range(DOWNLOAD_ATTEMPTS): + try: + with urllib.request.urlopen(url, timeout=120) as response: + return consume(response) + except ( + urllib.error.URLError, + TimeoutError, + ConnectionError, + http.client.IncompleteRead, + ) as error: + if not _transient(error) or attempt + 1 == DOWNLOAD_ATTEMPTS: + raise + delay = 2 ** (attempt + 1) + print(f"Transient runtime download failure; retry {attempt + 2}/3 in {delay}s") + time.sleep(delay) + + +def verify_staged_wheels( + output_dir: Path, + distribution_version_file: Path, + *, + version: str | None = None, + index_url: str | None = None, +) -> list[Path]: + """Recheck early-stage transport without a network fallback or version re-resolution.""" + runtime = resolve_runtime(distribution_version_file, version=version) + receipt = json.loads((output_dir / "transport.json").read_text(encoding="utf-8")) + if ( + receipt["distribution_version"] != runtime.version + or receipt["version_override"] != runtime.version_override + or receipt["index_url"].rstrip("/") != (index_url or runtime.index_url).rstrip("/") + ): + raise ValueError("Staged runtime selection does not match the effective runtime") + hashes = receipt["wheel_sha256"] + actual = {path.name for path in output_dir.glob("*.whl")} + if not hashes or set(hashes) != actual: + raise ValueError("Staged runtime wheel set does not match receipt") + wheels = [] + for name, digest in sorted(hashes.items()): + if Path(name).name != name or "/" in name or "\\" in name: + raise ValueError("Unsafe staged runtime wheel name") + path = output_dir / name + if path.is_symlink() or file_sha256(path) != digest: + raise ValueError(f"SHA-256 mismatch for {name}") + validate_wheel(path, runtime.version) + wheels.append(path) + return wheels def file_sha256(path: Path) -> str: @@ -72,8 +140,7 @@ def download_wheels( if urlsplit(package_url).scheme != "https": raise ValueError("The runtime wheel index must use HTTPS") output_dir = mssql_python_build_safety.resolve_safe_output_directory(output_dir) - with urllib.request.urlopen(package_url, timeout=120) as response: - page = response.read().decode("utf-8") + page = _fetch(package_url, lambda response: response.read().decode("utf-8")) parser = _WheelLinks() parser.feed(page) candidates: dict[str, tuple[str, str]] = {} @@ -101,12 +168,32 @@ def download_wheels( staged = [] for filename, (url, expected_hash) in sorted(candidates.items()): destination = output_dir / filename - with urllib.request.urlopen(url, timeout=120) as response: - with destination.open("wb") as target: - shutil.copyfileobj(response, target) - if file_sha256(destination) != expected_hash: - raise ValueError(f"SHA-256 mismatch for {filename}") - validate_wheel(destination, runtime.version) + + def stage(response): + # Each attempt starts with a new file, never appending a partial response. + with tempfile.NamedTemporaryFile(dir=output_dir, suffix=".part", delete=False) as target: + temporary = Path(target.name) + try: + shutil.copyfileobj(response, target) + # Sized HTTPResponse reads can silently stop before Content-Length. + remaining = getattr(response, "length", None) + if remaining is not None and remaining > 0: + raise http.client.IncompleteRead(b"", remaining) + target.close() + if file_sha256(temporary) != expected_hash: + raise ValueError(f"SHA-256 mismatch for {filename}") + # Preserve the expected filename for the wheel identity check. + temporary.replace(destination) + try: + validate_wheel(destination, runtime.version) + except (ValueError, zipfile.BadZipFile): + destination.unlink(missing_ok=True) + raise + finally: + target.close() + temporary.unlink(missing_ok=True) + + _fetch(url, stage) staged.append(destination) receipt = { "distribution_version": runtime.version, @@ -126,13 +213,22 @@ def main() -> None: parser.add_argument("--version") parser.add_argument("--distribution-version-file", type=Path, default=VERSION_FILE) parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--verify-only", action="store_true") args = parser.parse_args() - wheels = download_wheels( - args.index_url, - args.distribution_version_file, - args.output_dir, - version=args.version, - ) + if args.verify_only: + wheels = verify_staged_wheels( + args.output_dir, + args.distribution_version_file, + version=args.version, + index_url=args.index_url, + ) + else: + wheels = download_wheels( + args.index_url, + args.distribution_version_file, + args.output_dir, + version=args.version, + ) for wheel in wheels: print(wheel) diff --git a/eng/scripts/setup_sql_container.py b/eng/scripts/setup_sql_container.py index 7beda1af2..95841cb2d 100644 --- a/eng/scripts/setup_sql_container.py +++ b/eng/scripts/setup_sql_container.py @@ -6,9 +6,11 @@ test legs, --colima on macOS, and --cleanup for the always-running final step. Cleanup refuses containers without the matching owner label. -Only SQL lookup/pull/create/start/readiness/database setup is retried. Colima -starts once within the remaining overall setup budget, without a separate -startup timeout. The owned-container lookup also checks Docker availability, so +Only SQL lookup/pull/create/start/readiness/database setup is retried by default. +Colima starts once within the remaining overall setup budget. Release jobs can +opt into --retry-colima for two startup attempts, each capped at 600 seconds, +with a verified daemon and clean disposable-profile reset between attempts. +The owned-container lookup also checks Docker availability, so transient read-only failures can consume the same two attempts without creating or removing anything. Missing tools, invalid configuration/lookup results, ownership conflicts and unsafe cleanup are terminal. @@ -588,14 +590,29 @@ def cleanup(self, *, evidence=True): def prepare_runtime(self): if self.args.colima and not self.args.cleanup: - self.log("Starting Colima once (outside SQL retry)") - result = self.command( - ["colima", "start", "--cpu", "4", "--memory", "8", "--disk", "50"], - self.deadline - time.monotonic(), - launcher=True, - ) - self.log("Colima launcher completed; Docker and SQL readiness still require checks") - self.log(result.output) + attempts = 2 if self.args.retry_colima else 1 + for number in range(1, attempts + 1): + self.log(f"Colima startup attempt {number}/{attempts} (outside SQL retry)") + try: + result = self.command( + ["colima", "start", "--cpu", "4", "--memory", "8", "--disk", "50"], + 600 if self.args.retry_colima else self.deadline - time.monotonic(), + launcher=True, + ) + self.log(result.output) + if self.args.retry_colima: + self.docker_command("info", timeout=30) + except SetupFailure as exc: + self.log(f"Colima startup failed: {exc}") + if not exc.retryable or number == attempts: + raise + self.log(self.command(["colima", "status"], 15, check=False).output) + # Reset only the disposable default profile on this hosted job. + self.command(["colima", "stop", "--force"], 60) + self.command(["colima", "delete", "--force"], 60) + else: + self.log("Colima launcher completed; SQL readiness still requires checks") + return def acquire_image(self): if self.image_id is not None: @@ -775,8 +792,11 @@ def arguments(argv): parser.add_argument("--image") parser.add_argument("--database", choices=("TestDB",)) parser.add_argument("--colima", action="store_true") + parser.add_argument("--retry-colima", action="store_true") parser.add_argument("--cleanup", action="store_true") args = parser.parse_args(argv) + if args.retry_colima and (not args.colima or args.cleanup): + raise SetupFailure("--retry-colima requires --colima setup", retryable=False) if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", args.name): raise SetupFailure("Invalid SQL container name", retryable=False) if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:-]*", args.owner): diff --git a/eng/scripts/start_colima.py b/eng/scripts/start_colima.py new file mode 100644 index 000000000..71bac3d32 --- /dev/null +++ b/eng/scripts/start_colima.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Start a verified Colima Docker daemon, with one bounded clean retry on CI.""" + +import os +from pathlib import Path +import signal +import subprocess +import time + + +def run(command, timeout): + print(f"+ {' '.join(command)} (timeout={timeout}s)", flush=True) + with subprocess.Popen(command, start_new_session=True) as process: + try: + return process.wait(timeout=timeout) == 0 + except subprocess.TimeoutExpired: + # Kill the command's process group, not unrelated agent processes. + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return False + + +def diagnostics(): + run(["colima", "status"], 15) + root = Path.home() / ".colima" / "_lima" / "colima" + for path in sorted(root.glob("*.log")): + print(f"=== {path.name} (last 16 KiB) ===", flush=True) + with path.open("rb") as stream: + stream.seek(max(0, path.stat().st_size - 16384)) + print(stream.read().decode("utf-8", errors="replace"), flush=True) + + +def start(): + for command in (["sw_vers"], ["uname", "-m"], ["colima", "version"], ["docker", "--version"]): + if not run(command, 15): + raise RuntimeError(f"Tool/runner diagnostic failed: {command[0]}") + for attempt in range(2): + print(f"Colima startup attempt {attempt + 1}/2", flush=True) + if run(["colima", "start", "--cpu", "4", "--memory", "8", "--disk", "50"], 600): + if run(["docker", "context", "use", "colima"], 30): + for _ in range(12): + if run(["docker", "--context", "colima", "info"], 10): + return + time.sleep(5) + diagnostics() + if attempt == 0: + # Only the disposable default profile owned by this hosted CI job. + if not run(["colima", "stop", "--force"], 60): + raise RuntimeError("Colima cleanup failed; refusing an unsafe retry") + if not run(["colima", "delete", "--force"], 60): + raise RuntimeError("Colima profile deletion failed; refusing an unsafe retry") + raise RuntimeError("Colima Docker daemon did not become ready after two attempts") + + +if __name__ == "__main__": + start() diff --git a/tests/test_036_conda_provenance.py b/tests/test_036_conda_provenance.py index 3aa655bff..f0c5b7f61 100644 --- a/tests/test_036_conda_provenance.py +++ b/tests/test_036_conda_provenance.py @@ -792,6 +792,77 @@ def test_exact_recorded_wheel_run_is_verified_not_packaging_mode_or_build_number assert result["versions"] == {"mssql-python": "1.15.0", "mssql-python-odbc": "18.6.2.1"} +@pytest.mark.parametrize("selection", ["all", "x64"]) +@pytest.mark.parametrize("problem", [None, "missing-job", "missing-scan"]) +def test_sharded_linux_matrix_requires_each_selected_jobs_security(chain, selection, problem): + yaml = pytest.importorskip("yaml") + pipeline = yaml.safe_load( + (_PATH.parents[2] / "OneBranchPipelines/build-release-package-pipeline.yml").read_text( + encoding="utf-8" + ) + ) + configs = next(p["default"] for p in pipeline["parameters"] if p["name"] == "linuxConfigs") + if selection == "x64": + configs = [c for c in configs if c["arch"] == "x86_64"] + chain["pipelines/2199/runs/173176?api-version=7.1"]["templateParameters"][ + "linuxConfigs" + ] = configs + timeline = chain["build/builds/173176/timeline?api-version=7.1"]["records"] + legacy = "Linux_manylinux_2_28_aarch64.BuildWheels.__default" + linux_records = [r for r in timeline if r.get("id") == legacy or r.get("parentId") == legacy] + timeline[:] = [r for r in timeline if r not in linux_records] + for config in configs: + identifier = ( + f"Linux_{config['tag']}_{config['arch']}_{config['shard']}.BuildWheels.__default" + ) + timeline.extend( + { + key: ( + value.replace(legacy, identifier) + if key in {"id", "identifier", "parentId"} + else value + ) + for key, value in record.items() + } + for record in linux_records + ) + if problem: + timeline.remove( + next( + r + for r in timeline + if ( + r.get("id") == identifier + if problem == "missing-job" + else r.get("parentId") == identifier + ) + ) + ) + with pytest.raises(ValueError, match="missing or did not succeed|lacks completed"): + _verify(chain) + else: + assert _verify(chain)["productionEligible"] is True + + +@pytest.mark.parametrize("shard", [None, "", "invalid-shard", 1]) +def test_invalid_linux_shard_is_not_treated_as_legacy(chain, shard): + chain["pipelines/2199/runs/173176?api-version=7.1"]["templateParameters"]["linuxConfigs"][0][ + "shard" + ] = shard + with pytest.raises(ValueError, match="linuxConfigs evidence is invalid"): + _verify(chain) + + +def test_duplicate_linux_shards_are_rejected(chain): + configs = chain["pipelines/2199/runs/173176?api-version=7.1"]["templateParameters"][ + "linuxConfigs" + ] + configs[0]["shard"] = "py310_312" + configs.append(dict(configs[0])) + with pytest.raises(ValueError, match="linuxConfigs contains duplicate jobs"): + _verify(chain) + + @pytest.mark.parametrize( "problem", [ diff --git a/tests/test_037_rs_wheel_download.py b/tests/test_037_rs_wheel_download.py index e7ff6920d..49644ab08 100644 --- a/tests/test_037_rs_wheel_download.py +++ b/tests/test_037_rs_wheel_download.py @@ -1,8 +1,11 @@ import hashlib +import http.client import io import json import os import subprocess +import sys +import urllib.error import zipfile from pathlib import Path @@ -169,3 +172,205 @@ def test_ignores_yanked_wheels(tmp_path, monkeypatch): ) with pytest.raises(ValueError, match="No mssql-python-rs"): downloader.download_wheels(None, _pin(tmp_path), tmp_path / "out") + + +@pytest.mark.parametrize("target", ["index", "wheel"]) +@pytest.mark.parametrize("failure", ["timeout", "503", "incomplete"]) +def test_transient_download_retries_cleanly(tmp_path, monkeypatch, target, failure): + name, content, requested = _index(monkeypatch) + original = downloader.urllib.request.urlopen + calls = [] + sleeps = [] + + class Interrupted(io.BytesIO): + def read(self, *args): + super().read(10) + raise downloader.http.client.IncompleteRead(b"partial") + + def flaky(url, timeout): + selected = url.endswith("/mssql-python-rs/") == (target == "index") + if selected: + calls.append(url) + if len(calls) == 1: + if failure == "timeout": + raise urllib.error.URLError(TimeoutError("fixture timeout")) + if failure == "503": + raise urllib.error.HTTPError(url, 503, "fixture unavailable", {}, None) + return Interrupted(content) + return original(url, timeout) + + monkeypatch.setattr(downloader.urllib.request, "urlopen", flaky) + monkeypatch.setattr(downloader.time, "sleep", sleeps.append) + output = tmp_path / "out" + downloader.download_wheels(None, _pin(tmp_path), output) + assert len(calls) == 2 + assert sleeps == [2] + assert (output / name).read_bytes() == content + assert not list(output.glob("*.part")) + + +@pytest.mark.parametrize( + "failure", ["truncated-once", "truncated-always", "complete-hash", "complete-metadata"] +) +def test_http_response_length_controls_transport_retries(tmp_path, monkeypatch, failure): + options = ( + {"hash_value": "0" * 64} + if failure == "complete-hash" + else {"content": _wheel(metadata_version="0.4.0")} if failure == "complete-metadata" else {} + ) + name, content, _ = _index(monkeypatch, **options) + original = downloader.urllib.request.urlopen + calls, sleeps = [], [] + + def urlopen(url, timeout): + if url.endswith("/mssql-python-rs/"): + return original(url, timeout) + calls.append(url) + truncated = failure == "truncated-always" or ( + failure == "truncated-once" and len(calls) == 1 + ) + payload = content[: len(content) // 2] if truncated else content + + class Socket: + def makefile(self, *args, **kwargs): + return io.BytesIO( + f"HTTP/1.1 200 OK\r\nContent-Length: {len(content)}\r\n\r\n".encode() + payload + ) + + response = http.client.HTTPResponse(Socket()) + response.begin() + return response + + monkeypatch.setattr(downloader.urllib.request, "urlopen", urlopen) + monkeypatch.setattr(downloader.time, "sleep", sleeps.append) + output = tmp_path / "out" + pin = _pin(tmp_path) + if failure == "truncated-once": + downloader.download_wheels(None, pin, output) + assert (output / name).read_bytes() == content + assert len(calls) == 2 + assert sleeps == [2] + assert not list(output.glob("*.part")) + else: + error = http.client.IncompleteRead if failure == "truncated-always" else ValueError + with pytest.raises(error): + downloader.download_wheels(None, pin, output) + assert len(calls) == (3 if failure == "truncated-always" else 1) + assert sleeps == ([2, 4] if failure == "truncated-always" else []) + assert list(output.iterdir()) == [] + + +@pytest.mark.parametrize("code", [400, 401, 403, 404]) +def test_permanent_http_error_is_not_retried(tmp_path, monkeypatch, code): + calls = [] + + def unavailable(url, timeout): + calls.append(url) + raise urllib.error.HTTPError(url, code, "fixture rejection", {}, None) + + monkeypatch.setattr(downloader.urllib.request, "urlopen", unavailable) + with pytest.raises(urllib.error.HTTPError): + downloader.download_wheels(None, _pin(tmp_path), tmp_path / "out") + assert len(calls) == 1 + + +def test_retry_exhaustion_removes_partial_files_and_receipt(tmp_path, monkeypatch): + _index(monkeypatch) + original = downloader.urllib.request.urlopen + calls, sleeps = [], [] + + class Interrupted(io.BytesIO): + def read(self, *args): + raise TimeoutError("fixture interrupted stream") + + def unavailable(url, timeout): + if url.endswith("/mssql-python-rs/"): + return original(url, timeout) + calls.append(url) + return Interrupted(b"partial") + + monkeypatch.setattr(downloader.urllib.request, "urlopen", unavailable) + monkeypatch.setattr(downloader.time, "sleep", sleeps.append) + output = tmp_path / "out" + with pytest.raises(TimeoutError): + downloader.download_wheels(None, _pin(tmp_path), output) + assert len(calls) == 3 + assert sleeps == [2, 4] + assert list(output.iterdir()) == [] + + +@pytest.mark.parametrize("failure", ["hash", "metadata"]) +def test_invalid_payload_is_not_retried_or_left_staged(tmp_path, monkeypatch, failure): + options = ( + {"hash_value": "0" * 64} + if failure == "hash" + else {"content": _wheel(metadata_version="0.4.0")} + ) + _, _, requested = _index(monkeypatch, **options) + output = tmp_path / "out" + with pytest.raises(ValueError): + downloader.download_wheels(None, _pin(tmp_path), output) + assert len(requested) == 2 + assert list(output.iterdir()) == [] + + +@pytest.mark.parametrize("tamper", [None, "hash", "version", "extra", "override"]) +def test_rechecks_early_transport_offline(tmp_path, monkeypatch, tamper): + name, _, _ = _index(monkeypatch) + pin, output = _pin(tmp_path), tmp_path / "out" + downloader.download_wheels(None, pin, output) + + def forbidden(*args, **kwargs): + pytest.fail("Offline verification must not access the network") + + monkeypatch.setattr(downloader.urllib.request, "urlopen", forbidden) + if tamper == "hash": + (output / name).write_bytes(b"corrupt") + elif tamper == "version": + pin.write_text("0.4.0\n", encoding="ascii") + elif tamper == "extra": + (output / "extra.whl").touch() + elif tamper == "override": + monkeypatch.setenv(VERSION_ENV, "0.3.0") + if tamper: + with pytest.raises(ValueError): + downloader.verify_staged_wheels(output, pin) + else: + assert downloader.verify_staged_wheels(output, pin) == [output / name] + + +@pytest.mark.parametrize("download_slash", ["", "/"]) +@pytest.mark.parametrize("verify_slash", ["", "/"]) +def test_explicit_index_round_trip_is_verified_offline( + tmp_path, monkeypatch, download_slash, verify_slash +): + index = "https://mirror.example.test/simple" + name, _, _ = _index(monkeypatch) + pin, output = _pin(tmp_path), tmp_path / "out" + downloader.download_wheels(index + download_slash, pin, output) + + def forbidden(*args, **kwargs): + pytest.fail("Offline verification must not access the network") + + monkeypatch.setattr(downloader.urllib.request, "urlopen", forbidden) + assert downloader.verify_staged_wheels(output, pin, index_url=index + verify_slash) == [ + output / name + ] + monkeypatch.setattr( + sys, + "argv", + [ + "download_mssql_python_rs_wheels.py", + "--verify-only", + "--index-url", + index + verify_slash, + "--output-dir", + str(output), + "--distribution-version-file", + str(pin), + ], + ) + downloader.main() + for wrong_index in (None, "https://different.example.test/simple"): + with pytest.raises(ValueError, match="effective runtime"): + downloader.verify_staged_wheels(output, pin, index_url=wrong_index) diff --git a/tests/test_release_pipeline_resilience.py b/tests/test_release_pipeline_resilience.py new file mode 100644 index 000000000..2536f7532 --- /dev/null +++ b/tests/test_release_pipeline_resilience.py @@ -0,0 +1,473 @@ +"""Source-only pipeline contracts; no driver imports or SQL Server required.""" + +import importlib.util +import os +from pathlib import Path +import shutil +import subprocess +from types import SimpleNamespace + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +HELPER = ROOT / "eng/scripts/start_colima.py" +if not HELPER.is_file(): + pytest.skip("Requires the complete pipeline source checkout", allow_module_level=True) + +spec = importlib.util.spec_from_file_location("start_colima", HELPER) +colima = importlib.util.module_from_spec(spec) +spec.loader.exec_module(colima) + + +@pytest.mark.parametrize("failure", [None, "first", "both", "context", "daemon", "cleanup"]) +def test_colima_bounded_startup_and_verified_daemon(monkeypatch, failure): + calls, diagnostics = [], [] + starts = 0 + + def run(command, timeout): + nonlocal starts + calls.append((command, timeout)) + if command[:2] == ["colima", "start"]: + starts += 1 + return failure not in {"both", "cleanup"} and not (failure == "first" and starts == 1) + if command[:3] == ["docker", "context", "use"]: + return failure != "context" + if command[-1] == "info": + return failure != "daemon" + if command[:2] == ["colima", "stop"]: + return failure != "cleanup" + return True + + monkeypatch.setattr(colima, "run", run) + monkeypatch.setattr(colima, "diagnostics", lambda: diagnostics.append(True)) + monkeypatch.setattr(colima.time, "sleep", lambda _: None) + if failure in {"both", "context", "daemon", "cleanup"}: + with pytest.raises(RuntimeError): + colima.start() + else: + colima.start() + assert calls[-1][0] == ["docker", "--context", "colima", "info"] + assert starts == (1 if failure in {None, "cleanup"} else 2) + assert len([c for c, _ in calls if c[-1] == "info"]) <= 24 + assert len([c for c, _ in calls if c[:2] == ["colima", "delete"]]) <= 1 + assert all(0 < timeout <= 600 for _, timeout in calls) + if failure: + assert diagnostics + + +def test_colima_command_timeout_terminates_only_its_process_group(monkeypatch): + class Process: + pid = 12345 + + def __init__(self): + self.waits = [] + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def wait(self, timeout=None): + self.waits.append(timeout) + if len(self.waits) <= 2: + raise colima.subprocess.TimeoutExpired("fixture", timeout) + return -9 + + process, signals = Process(), [] + + def popen(command, **kwargs): + assert kwargs == {"start_new_session": True} + return process + + monkeypatch.setattr(colima.subprocess, "Popen", popen) + monkeypatch.setattr( + colima.os, "killpg", lambda pid, sig: signals.append((pid, sig)), raising=False + ) + monkeypatch.setattr(colima.signal, "SIGKILL", 9, raising=False) + assert colima.run(["colima", "start"], 600) is False + assert signals == [(12345, colima.signal.SIGTERM), (12345, 9)] + assert process.waits == [600, 5, None] + + +def test_linux_default_matrix_and_shards_cover_every_python_once(): + # PyYAML is a tooling-test dependency, not a new driver/runtime dependency. + yaml = pytest.importorskip("yaml") + pipeline = yaml.safe_load( + (ROOT / "OneBranchPipelines/build-release-package-pipeline.yml").read_text() + ) + parameters = {p["name"]: p for p in pipeline["parameters"]} + configs = parameters["linuxConfigs"]["default"] + assert len(configs) == 6 + expected = [f"cp3{minor}" for minor in range(10, 16)] + for tag in ("manylinux_2_28", "musllinux"): + for arch in ("x86_64", "aarch64"): + group = [c for c in configs if (c["tag"], c["arch"]) == (tag, arch)] + assert sorted(p for c in group for p in c["pythonBins"].split()) == expected + assert len(group) == (2 if arch == "aarch64" else 1) + if arch == "aarch64": + assert all(len(c["pythonBins"].split()) == 3 for c in group) + assert sum(len(c["pythonBins"].split()) for c in configs) == 24 + assert parameters["linuxBuildParallelLevel"]["default"] == "1" + assert parameters["runSdlTasks"]["default"] is True + assert parameters["signWindowsBinaries"]["default"] is True + + +def test_odbc_consumers_wait_for_scanned_producer_and_keep_release_interface(): + pipeline = (ROOT / "OneBranchPipelines/build-release-package-pipeline.yml").read_text() + assert pipeline.count("odbcArtifactName: 'drop_ODBC_BuildAll_BuildWheel'") == 3 + assert pipeline.count("- ODBC_BuildAll") == 4 # Three consumers + compatibility. + assert pipeline.count("- RuntimeWheels") == 4 # Three consumers + consolidation. + odbc = (ROOT / "OneBranchPipelines/stages/build-odbc-all-stage.yml").read_text() + assert "if ($wheelCount -ne 7)" in odbc + assert "Assert each ODBC wheel is platform-correct" in odbc + assert "EsrpMalwareScanning@6" in odbc + compatibility = ( + ROOT / "OneBranchPipelines/jobs/consolidate-odbc-artifacts-job.yml" + ).read_text() + assert "artifact: 'drop_ConsolidateOdbc_ConsolidateArtifacts'" in compatibility + consolidate = (ROOT / "OneBranchPipelines/jobs/consolidate-artifacts-job.yml").read_text() + assert "--verify-only" in consolidate + assert 'if [ "$WHEEL_COUNT" -ne 41 ]' in consolidate + + +@pytest.fixture +def linux_job(): + yaml = pytest.importorskip("yaml") + stage = yaml.safe_load( + (ROOT / "OneBranchPipelines/stages/build-linux-single-stage.yml").read_text() + ) + return stage["stages"][0]["jobs"][0] + + +def test_linux_cache_reaches_both_container_build_and_test_pip(linux_job): + variables = {v["name"]: v["value"] for v in linux_job["variables"]} + cache = next(s for s in linux_job["steps"] if s.get("task") == "Cache@2") + assert cache["inputs"]["path"] == "$(PIP_CACHE_DIR)" + assert variables["PIP_CACHE_DIR"] == "$(Pipeline.Workspace)/.pip-cache" + key = cache["inputs"]["key"] + for token in ( + '"$(Agent.OS)"', + '"${{ parameters.linuxTag }}"', + '"${{ parameters.arch }}"', + '"${{ parameters.pythonBins }}"', + "eng/requirements-build-linux.txt", + "eng/requirements-test-linux.txt", + ): + assert token in key + scripts = "\n".join(s.get("script", "") for s in linux_job["steps"]) + assert 'mkdir -p "$(PIP_CACHE_DIR)"' in scripts + assert '-v "$(PIP_CACHE_DIR):/pip-cache"' in scripts + assert scripts.count("-e PIP_CACHE_DIR=/pip-cache/$PYBIN") == 2 + assert scripts.count("--require-hashes -r /workspace/eng/requirements-build-linux.txt") == 2 + assert scripts.count("--require-hashes -r /workspace/eng/requirements-test-linux.txt") == 2 + + +@pytest.mark.parametrize("failure", ["", "install", "conversion", "fidelity"]) +def test_manylinux_requires_working_cp949_conversion(linux_job, tmp_path, failure): + bash = shutil.which("bash") + if not bash: + pytest.skip("Bash is required to exercise the pipeline script") + step = next( + s for s in linux_job["steps"] if s.get("displayName") == "Install system build dependencies" + ) + script = step["script"].split("# ODBC requires CP949", 1)[1] + script = script.split('docker exec "$CONTAINER" bash -lc ', 2)[1].strip() + script = script[1 : script.rfind("'")] + prefix = r""" +dnf() { + if [ "$*" != "-y install glibc-gconv-extra" ]; then return 37; fi + if [ "$FAILURE" = install ]; then return 19; fi +} +iconv() { + cat >/dev/null + if [ "$FAILURE" = conversion ]; then return 23; fi + if [ "$FAILURE" = fidelity ]; then printf incorrect; return 0; fi + printf "\xec\x95\x88\xeb\x85\x95\xed\x95\x98\xec\x84\xb8\xec\x9a\x94" +} +""" + result = subprocess.run( + [bash, "-c", prefix + script], + cwd=tmp_path, + env={**os.environ, "FAILURE": failure}, + capture_output=True, + text=True, + timeout=15, + ) + assert result.returncode == {"": 0, "install": 19, "conversion": 23, "fidelity": 1}[failure] + assert ("CP949 conversion verified" in result.stdout) == (not failure) + + +def test_windows_cache_isolated_by_python_architecture_and_lock(): + yaml = pytest.importorskip("yaml") + stage = yaml.safe_load( + (ROOT / "OneBranchPipelines/stages/build-windows-single-stage.yml").read_text() + ) + job = stage["stages"][0]["jobs"][0] + cache = next(s for s in job["steps"] if s.get("task") == "Cache@2") + assert cache["inputs"]["path"] == "$(PIP_CACHE_DIR)" + assert job["variables"]["PIP_CACHE_DIR"] == r"$(Pipeline.Workspace)\.pip-cache" + for token in ( + '"$(Agent.OS)"', + '"$(Agent.OSArchitecture)"', + '"${{ parameters.pythonVersion }}"', + '"${{ parameters.architecture }}"', + "eng/requirements-build-windows.txt", + ): + assert token in cache["inputs"]["key"] + install = next(s for s in job["steps"] if s.get("displayName") == "Install Python dependencies") + assert "--require-hashes -r eng/requirements-build-windows.txt" in install["powershell"] + assert job["steps"].index(cache) < job["steps"].index(install) + + +@pytest.mark.parametrize("failure,status", [("", 0), ("setup", 19), ("inspect", 23), ("empty", 1)]) +def test_linux_sql_setup_failure_never_publishes_an_address(linux_job, tmp_path, failure, status): + bash = shutil.which("bash") + if not bash: + pytest.skip("Bash is required to exercise the pipeline script") + step = next( + s + for s in linux_job["steps"] + if s.get("displayName") == "Start SQL Server container for testing" + ) + cleanup = next( + s for s in linux_job["steps"] if s.get("displayName") == "Clean up Linux SQL container" + ) + assert cleanup["condition"] == "always()" + assert cleanup["timeoutInMinutes"] * 60 > 115 + assert step["timeoutInMinutes"] * 60 > 1260 + for task in (step, cleanup): + assert '--owner "$(Build.BuildId).$(System.JobId)"' in task["script"] + assert '--name "sqlserver-$(LINUX_TAG)-$(ARCH)"' in task["script"] + assert "setup_sql_container.py" in task["script"] + assert "--cleanup" in cleanup["script"] + assert "--image mcr.microsoft.com/mssql/server:2022-latest" in step["script"] + scripts = "\n".join(s.get("script", "") for s in linux_job["steps"]) + assert "docker stop build-$(LINUX_TAG)-$(ARCH) sqlserver-" not in scripts + script = step["script"] + for token, value in { + "$(LINUX_TAG)": "manylinux_2_28", + "$(ARCH)": "x86_64", + "$(Build.BuildId)": "1", + "$(System.JobId)": "fixture", + }.items(): + script = script.replace(token, value) + prefix = r""" +python3() { + if [ "$FAILURE" = setup ]; then return 19; fi +} +docker() { + if [ "$FAILURE" = inspect ]; then return 23; fi + if [ "$FAILURE" != empty ]; then echo 172.17.0.2; fi +} +""" + result = subprocess.run( + [bash, "-c", prefix + script + "\necho complete\n"], + cwd=tmp_path, + env={**os.environ, "FAILURE": failure}, + capture_output=True, + text=True, + timeout=15, + ) + assert result.returncode == status, result.stdout + result.stderr + if failure: + assert "task.setvariable" not in result.stdout + assert "complete" not in result.stdout + else: + assert "##vso[task.setvariable variable=SQL_IP]172.17.0.2" in result.stdout + + +@pytest.fixture +def macos_job(): + yaml = pytest.importorskip("yaml") + stage = yaml.safe_load( + (ROOT / "OneBranchPipelines/stages/build-macos-single-stage.yml").read_text() + ) + return stage["stages"][0]["jobs"][0] + + +def test_macos_cache_and_cleanup_keep_release_isolation(macos_job): + variables = {v["name"]: v["value"] for v in macos_job["variables"]} + assert variables["DOCKER_CONTEXT"] == "colima" + cache = next(s for s in macos_job["steps"] if s.get("task") == "Cache@2") + assert cache["inputs"]["path"] == "$(PIP_CACHE_DIR)" + assert variables["PIP_CACHE_DIR"] == "$(Pipeline.Workspace)/.pip-cache" + assert cache["inputs"]["key"].endswith("eng/requirements-build-macos.txt") + for key in (cache["inputs"]["key"], cache["inputs"]["restoreKeys"]): + assert '"$(Agent.OS)"' in key + assert '"$(Agent.OSArchitecture)"' in key + assert '"${{ parameters.pythonVersion }}"' in key + cleanup = next( + s for s in macos_job["steps"] if s.get("displayName") == "Clean up macOS SQL container" + ) + assert cleanup["condition"] == "always()" + assert '--owner "$(Build.BuildId).$(System.JobId)"' in cleanup["script"] + assert "--cleanup --colima" in cleanup["script"] + + +@pytest.mark.parametrize("failure", ["", "first", "both", "cancel", "cleanup", "daemon"]) +def test_shared_sql_helper_preserves_bounded_release_colima_retry(monkeypatch, failure): + from eng.scripts import setup_sql_container as sql_setup + + args = sql_setup.arguments( + [ + "--name", + "sqlserver", + "--owner", + "fixture", + "--image", + "mcr.microsoft.com/mssql/server:2022-latest", + "--colima", + "--retry-colima", + ] + ) + setup = sql_setup.SqlSetup(args, "dummy") + calls = [] + + def command(args, timeout=15, **kwargs): + calls.append((args, timeout)) + starts = sum(c[:2] == ["colima", "start"] for c, _ in calls) + if args[:2] == ["colima", "start"]: + if failure == "cancel": + raise sql_setup.Cancelled(15) + if failure in {"both", "cleanup"} or failure == "first" and starts == 1: + raise sql_setup.SetupFailure("fixture startup failure") + if args[-1] == "info" and failure == "daemon": + raise sql_setup.SetupFailure("fixture daemon failure") + if args[:2] == ["colima", "stop"] and failure == "cleanup": + raise sql_setup.SetupFailure("fixture cleanup failure") + return SimpleNamespace(output="") + + monkeypatch.setattr(setup, "command", command) + if failure == "cancel": + with pytest.raises(sql_setup.Cancelled): + setup.prepare_runtime() + elif failure in {"both", "cleanup", "daemon"}: + with pytest.raises(sql_setup.SetupFailure): + setup.prepare_runtime() + else: + setup.prepare_runtime() + assert sum(c[:2] == ["colima", "start"] for c, _ in calls) == ( + 2 if failure in {"first", "both", "daemon"} else 1 + ) + assert sum(c[:2] == ["colima", "delete"] for c, _ in calls) <= 1 + assert all(0 < timeout <= 600 for _, timeout in calls) + + +def test_colima_retry_does_not_change_default_pr_or_linux_setup(monkeypatch): + from eng.scripts import setup_sql_container as sql_setup + + base = [ + "--name", + "sqlserver", + "--owner", + "fixture", + "--image", + "mcr.microsoft.com/mssql/server:2022-latest", + ] + for flags in ([], ["--colima"]): + args = sql_setup.arguments(base + flags) + assert not args.retry_colima + setup = sql_setup.SqlSetup(args, "dummy") + calls = [] + + def command(*args, **kwargs): + calls.append(args) + raise sql_setup.SetupFailure("fixture startup failure") + + monkeypatch.setattr(setup, "command", command) + if flags: + with pytest.raises(sql_setup.SetupFailure): + setup.prepare_runtime() + assert len(calls) == 1 + else: + setup.prepare_runtime() + assert not calls + with pytest.raises(sql_setup.SetupFailure, match="requires --colima setup"): + sql_setup.arguments(base + ["--retry-colima"]) + + +@pytest.mark.parametrize( + "failure,expected_status", [("", 0), ("sql", 19), ("pip", 23), ("build", 29)] +) +def test_macos_overlaps_setup_and_propagates_failures( + macos_job, tmp_path, failure, expected_status +): + bash = shutil.which("bash") + if not bash: + pytest.skip("Bash is required to exercise the pipeline script") + step = next( + s + for s in macos_job["steps"] + if s.get("displayName") == "Build universal2 bindings alongside SQL setup" + ) + script = step["script"] + assert "--require-hashes -r eng/requirements-build-macos.txt" in script + assert "setup_sql_container.py" in script + assert "--image mcr.microsoft.com/mssql/server:2022-latest --colima --retry-colima" in script + for token, value in { + "$(Agent.TempDirectory)": ".", + "$(Build.SourcesDirectory)": ".", + "$(System.JobId)": "fixture", + "$(Build.BuildId)": "1", + "${{ parameters.pythonVersion }}": "3.13", + }.items(): + script = script.replace(token, value) + build_dir = tmp_path / "mssql_python" / "pybind" + build_dir.mkdir(parents=True) + (build_dir / "build.sh").write_text( + "#!/bin/bash\n" + "cd ../..\n" + "echo build-start >> events\n" + "touch build-started\n" + 'if [ "$FAILURE" = build ]; then exit 29; fi\n', + encoding="utf-8", + ) + (build_dir / "build.sh").chmod(0o755) + prefix = r""" +python3() { + case " $* " in + *" --cleanup "*) echo cleanup >> events; return 0 ;; + esac + trap 'echo setup-cancelled >> events; exit 143' TERM + echo setup-start >> events + touch setup-started + for i in {1..100}; do + if [ -f build-started ]; then break; fi + sleep 0.02 + done + if [ ! -f build-started ]; then return 31; fi + if [ "$FAILURE" = sql ]; then return 19; fi + echo setup-ready >> events +} +python() { + if [ "$*" = "-m pip install --require-hashes -r eng/requirements-build-macos.txt" ]; then + for i in {1..100}; do + if [ -f setup-started ]; then break; fi + sleep 0.02 + done + if [ ! -f setup-started ]; then return 37; fi + echo dependencies >> events + if [ "$FAILURE" = pip ]; then return 23; fi + fi +} +""" + result = subprocess.run( + [bash, "-c", prefix + script + "\necho complete >> events\n"], + cwd=tmp_path, + env={**os.environ, "FAILURE": failure}, + capture_output=True, + text=True, + timeout=15, + ) + assert result.returncode == expected_status, result.stdout + result.stderr + events = (tmp_path / "events").read_text().splitlines() + assert events.index("setup-start") < events.index("dependencies") + assert not list(tmp_path.glob("sql-setup-*.log")) + if failure: + assert "complete" not in events + assert "cleanup" in events + else: + assert events.index("dependencies") < events.index("build-start") + assert events.index("setup-ready") < events.index("complete") + assert "cleanup" not in events