diff --git ml-explore/mlx/.github/actionlint.yaml Layr-Labs/mlx/.github/actionlint.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..133b4ad67fbdb5098cb7cf2f20936b0cd698b4c3
--- /dev/null
+++ Layr-Labs/mlx/.github/actionlint.yaml
@@ -0,0 +1,7 @@
+self-hosted-runner:
+ labels:
+ - darkbloom-linux-arm64
+ - darkbloom-macos-arm64-4x16
+ - darkbloom-macos-arm64-4x24
+ - darkbloom-macos-arm64-8x16
+ - darkbloom-macos-arm64-12x32
diff --git ml-explore/mlx/.github/actions/build-docs/action.yml Layr-Labs/mlx/.github/actions/build-docs/action.yml
deleted file mode 100644
index 4d4286e3c86292b903eef16d1dc22c2689e300d1..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/actions/build-docs/action.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-name: 'Build Documentation'
-description: 'Build documentation'
-
-runs:
- using: "composite"
- steps:
- - name: Setup machine
- id: setup
- uses: ./.github/actions/setup
- with:
- ccache-key: 'release'
- ccache-save: false
-
- - name: Install dependencies
- shell: bash
- env:
- CMAKE_ARGS: ${{ steps.setup.outputs.cmake-args }}
- run: |
- sudo apt-get install -y doxygen
- uv pip install -r docs/requirements.txt
- uv pip install . -v
-
- - name: Build documentation
- shell: bash
- run: |
- cd docs
- doxygen
- make html O=-W
-
- - name: Create artifact tar
- shell: bash
- run: tar -cf artifact.tar -C docs --dereference build/html index.html
-
- # Do it manually because upload-pages-artifact requires gtar
- - name: Upload artifact
- id: upload-artifact
- uses: actions/upload-artifact@v7
- with:
- name: github-pages
- path: artifact.tar
- retention-days: 1
- if-no-files-found: error
diff --git ml-explore/mlx/.github/actions/build-wheel/action.yml Layr-Labs/mlx/.github/actions/build-wheel/action.yml
deleted file mode 100644
index c8f86420ab3bc5f0172a70b71723773ce652a3f0..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/actions/build-wheel/action.yml
+++ /dev/null
@@ -1,106 +0,0 @@
-name: 'Build wheel'
-description: 'Build the Python wheels for release on all platforms'
-
-inputs:
- cmake-args:
- description: 'The args for generating CMake project'
- required: true
- build-frontend:
- description: 'Build the frontend mlx package'
- required: false
- default: 'true'
- build-backend:
- description: 'Build the backend mlx-cpu/mlx-cuda/mlx-metal packages'
- required: false
- default: 'true'
- macos-target:
- description: 'The target macOS version to build for'
- required: false
- default: '26.2'
- arch-tag:
- description: 'Platform architecture tag'
- required: false
- default: |-
- ${{ case(runner.arch == 'x64', 'x86_64',
- runner.arch == 'x86', 'i686',
- runner.arch == 'arm', 'armv7l',
- runner.arch == 'arm64', 'aarch64',
- 'unknown')
- }}
-
-runs:
- using: 'composite'
- steps:
- - name: Install dependencies
- shell: bash
- run: |
- uv pip install build setuptools
- if ${{ runner.os == 'Linux' }} ; then
- uv pip install auditwheel patchelf
- fi
- mkdir -p wheelhouse
-
- - name: Build frontend package
- if: inputs.build-frontend == 'true'
- shell: bash
- env:
- CMAKE_ARGS: ${{ inputs.cmake-args }}
- MACOSX_DEPLOYMENT_TARGET: ${{ inputs.macos-target }}
- run: |
- python setup.py clean --all
- MLX_BUILD_FRONTEND_PACKAGE=1 python -m build -w
-
- - name: Post-process frontend package
- if: inputs.build-frontend == 'true'
- shell: bash
- run: |
- if ${{ runner.os == 'Linux' }} ; then
- auditwheel repair dist/mlx-*.whl \
- --plat manylinux_2_35_${{ inputs.arch-tag }} \
- --exclude libmlx.so* \
- --only-plat
- else
- mv dist/mlx-*.whl wheelhouse/
- fi
-
- - name: Build backend package
- if: inputs.build-backend == 'true'
- shell: bash
- env:
- CMAKE_ARGS: ${{ inputs.cmake-args }}
- MACOSX_DEPLOYMENT_TARGET: ${{ inputs.macos-target }}
- run: |
- python setup.py clean --all
- MLX_BUILD_BACKEND_PACKAGE=1 python -m build -w
-
- - name: Post-process backend package
- if: inputs.build-backend == 'true'
- shell: bash
- run: |
- if ${{ runner.os == 'Linux' }} ; then
- if [ -f dist/mlx_cpu*.whl ]; then
- auditwheel repair dist/mlx_cpu*.whl \
- --plat manylinux_2_35_${{ inputs.arch-tag }}
- fi
- if [ -f dist/mlx_cuda*.whl ]; then
- auditwheel repair dist/mlx_cuda*.whl \
- --plat manylinux_2_35_${{ inputs.arch-tag }} \
- --exclude libcublas* \
- --exclude libcuda* \
- --exclude libcudnn* \
- --exclude libcufft* \
- --exclude libcusolver* \
- --exclude libnccl* \
- --exclude libnvrtc*
- fi
- else
- if [ -f dist/mlx_cpu*.whl ]; then
- mv dist/mlx_cpu*.whl wheelhouse/
- fi
- if [ -f dist/mlx_cuda*.whl ]; then
- mv dist/mlx_cuda*.whl wheelhouse/
- fi
- if [ -f dist/mlx_metal*.whl ]; then
- mv dist/mlx_metal*.whl wheelhouse/
- fi
- fi
diff --git ml-explore/mlx/.github/actions/build/action.yml Layr-Labs/mlx/.github/actions/build/action.yml
deleted file mode 100644
index 037e0ea6bca753272efe94c0f9b03f8c56e5af5c..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/actions/build/action.yml
+++ /dev/null
@@ -1,40 +0,0 @@
-name: 'Build'
-description: 'Build C++ and Python binaries for testing on Linux and Windows'
-
-inputs:
- cmake-args:
- description: 'The args for generating CMake project'
- required: true
- debug:
- description: 'Do debug build'
- required: true
-
-runs:
- using: 'composite'
- steps:
- - name: Install Python package
- shell: bash
- env:
- DEBUG: ${{ inputs.debug == 'true' && 1 || 0 }}
- CMAKE_ARGS: ${{ inputs.cmake-args }}
- run: |
- # Install cpu-only torch to save space.
- uv pip install torch --torch-backend=cpu
- uv pip install --no-build-isolation -e ".[dev]" -v
-
- - name: Build CPP only
- shell: bash
- env:
- # The cpp build is using some extra settings to reuse the compile cache
- # generated by the python install:
- # 1. Use the same ccache options with setup.py.
- # 2. Build dynamic library.
- # 3. Put the build dir in the same depth with python build dir.
- CCACHE_BASEDIR: ${{ github.workspace }}/build/cpp/mlx
- CCACHE_NOHASHDIR: true
- run: |
- cmake . -B build/cpp/mlx ${{ inputs.cmake-args }} \
- -DBUILD_SHARED_LIBS=ON \
- -DCMAKE_BUILD_TYPE=${{ inputs.debug == 'true' && 'Debug' || 'Release' }}
- cmake --build build/cpp/mlx \
- -j ${{ runner.os == 'Windows' && '$NUMBER_OF_PROCESSORS' || '$(nproc)' }}
diff --git ml-explore/mlx/.github/actions/fork-build-cache/action.yml Layr-Labs/mlx/.github/actions/fork-build-cache/action.yml
new file mode 100644
index 0000000000000000000000000000000000000000..61c2d92ec35375af3f19ce69dcf8287067705d40
--- /dev/null
+++ Layr-Labs/mlx/.github/actions/fork-build-cache/action.yml
@@ -0,0 +1,188 @@
+name: 'Fork build caches'
+description: 'Set up a fork-tests build job with ccache and the Metal kernel cache, and save the caches'
+
+# phase: restore runs the setup action, restores the ccache files and the
+# Metal kernel cache, and points the build at the cache script in
+# .github/scripts/fork-tests/metal-cache. phase: save prints the cache
+# statistics and saves each cache on pull requests and on pushes to main
+# when the build had cache misses.
+#
+# Cache keys:
+# ccache ccache-fork-tests-KIND-FLAGS-clangCLANG-macOS-ARM64-metal-SHA-RUN-ATTEMPT
+# Metal metal-METAL-KERNELS-KIND-RUN-ATTEMPT
+# CLANG is the clang major.minor version. METAL is the metal compiler
+# version. FLAGS is a hash of CFLAGS, CXXFLAGS, the deployment target and
+# KIND. KIND sets the CMake arguments of the build. KERNELS is a hash of
+# mlx/backend/metal/kernels. A restore takes the newest cache with the same
+# prefix. The ccache restore falls back to a cache of another clang version;
+# ccache checks the compiler content (compiler_check=content), so the
+# objects of another compiler only miss. The Metal restore falls back only to
+# a cache of the same metal compiler version, and the cache script puts the
+# metal compiler version and the SDK build in each entry key.
+
+inputs:
+ phase:
+ description: 'restore or save'
+ required: true
+ kind:
+ description: 'The build kind: wheel or cpp'
+ required: true
+ ccache-save-key:
+ description: 'phase save: the ccache-save-key output of phase restore'
+ required: false
+ default: ''
+ metal-save-key:
+ description: 'phase save: the metal-save-key output of phase restore'
+ required: false
+ default: ''
+
+outputs:
+ cmake-args:
+ description: 'The args for generating CMake project'
+ value: ${{ steps.setup.outputs.cmake-args }} ${{ steps.metal-cpp.outputs.cmake-args }}
+ ccache-save-key:
+ description: 'The key to save the ccache files with'
+ value: ${{ steps.setup.outputs.ccache-save-key }}
+ metal-save-key:
+ description: 'The key to save the Metal kernel cache with'
+ value: ${{ steps.keys.outputs.metal-save }}
+
+runs:
+ using: 'composite'
+ steps:
+ # Before every cache step. On a Darkbloom Sandbox without a Darkbloom
+ # cache (DARKBLOOM_CACHE_URL), a cache step would use GitHub's Actions
+ # cache, so every cache step is skipped (CI_ACTIONS_CACHE=off).
+ - name: Choose this job's Actions cache
+ if: inputs.phase == 'restore'
+ shell: bash
+ run: |
+ if [[ ${RUNNER_NAME:-} != darkbloom-* ]]; then
+ echo "Actions cache: this runner's own"
+ elif [[ -n ${DARKBLOOM_CACHE_URL:-} ]]; then
+ echo "Actions cache: the Darkbloom cache at $DARKBLOOM_CACHE_URL"
+ else
+ echo "CI_ACTIONS_CACHE=off" >> "$GITHUB_ENV"
+ echo "::notice title=Actions cache::The plane gave this Darkbloom Sandbox no cache, so every cache step is skipped."
+ fi
+
+ - name: Make the cache keys
+ id: keys
+ if: inputs.phase == 'restore'
+ shell: bash
+ env:
+ KIND: ${{ inputs.kind }}
+ KERNELS: ${{ hashFiles('mlx/backend/metal/kernels/**') }}
+ run: |
+ # The other lines of --version name the install folder and the OS.
+ # They change between runner images, so the keys use the first line.
+ version() {
+ echo "$1" | head -n 1 | sed -E 's/.* version ([0-9.]+).*/\1/' | tr -c 'A-Za-z0-9.\n' '_'
+ }
+ clang_text=$(xcrun clang --version)
+ metal_text=$(xcrun -sdk macosx metal --version)
+ sdk=$(xcrun -sdk macosx --show-sdk-build-version)
+ printf '%s\n' "$clang_text" "$metal_text" "SDK build: $sdk"
+ clang=$(version "$clang_text" | cut -d . -f 1-2)
+ metal=$(version "$metal_text")
+ if [ -z "$clang" ] || [ -z "$metal" ] || [ -z "$sdk" ]; then
+ echo "::error::Cannot read the clang, metal or SDK version."
+ exit 1
+ fi
+ flags=$(printf '%s\n' "$CFLAGS" "$CXXFLAGS" "$MACOSX_DEPLOYMENT_TARGET" "$KIND" \
+ | shasum -a 256 | cut -c 1-16)
+ kernels=${KERNELS:0:16}
+ {
+ echo "toolchain=$(echo "$metal_text" | head -n 1) SDK $sdk"
+ echo "ccache-key=fork-tests-$KIND-$flags-clang$clang"
+ echo "ccache-fallback=ccache-fork-tests-$KIND-$flags-"
+ echo "metal-restore=metal-$metal-$kernels-"
+ echo "metal-fallback=metal-$metal-"
+ echo "metal-save=metal-$metal-$kernels-$KIND-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
+ } | tee -a "$GITHUB_OUTPUT"
+
+ - uses: ./.github/actions/setup
+ id: setup
+ if: inputs.phase == 'restore'
+ with:
+ toolkit: metal
+ ccache-key: ${{ steps.keys.outputs.ccache-key }}
+ ccache-fallback: ${{ steps.keys.outputs.ccache-fallback }}
+ # The build and the C++ tests do not use openmpi. Only the
+ # distributed test in python-gpu shard 0 does.
+ install-macos-deps: 'false'
+
+ - name: Fetch verified Apple headers with bounded retries
+ id: metal-cpp
+ if: inputs.phase == 'restore' && runner.os == 'macOS' && startsWith(runner.name, 'darkbloom-')
+ shell: bash
+ run: |
+ python3 .github/scripts/fork-tests/test_metal_cpp.py
+ python3 .github/scripts/fork-tests/metal_cpp.py >> "$GITHUB_OUTPUT"
+
+ - name: Restore the Metal kernel cache
+ if: inputs.phase == 'restore' && env.CI_ACTIONS_CACHE != 'off'
+ uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
+ with:
+ path: ${{ github.workspace }}/.metal-cache
+ key: ${{ steps.keys.outputs.metal-restore }}
+ restore-keys: |
+ ${{ steps.keys.outputs.metal-restore }}
+ ${{ steps.keys.outputs.metal-fallback }}
+
+ - name: Prepare the caches
+ if: inputs.phase == 'restore'
+ shell: bash
+ env:
+ TOOLCHAIN: ${{ steps.keys.outputs.toolchain }}
+ run: |
+ # The script reads the restored entries from MLX_METAL_CACHE_IN and
+ # writes each entry that the build uses to MLX_METAL_CACHE_OUT. The
+ # saved cache then holds no entries that the build does not use.
+ in="$RUNNER_TEMP/metal-cache-in"
+ if [ -d .metal-cache ]; then
+ mv .metal-cache "$in"
+ else
+ mkdir -p "$in"
+ fi
+ echo "Restored Metal cache entries: $(ls "$in" | wc -l)"
+ {
+ echo "MLX_METAL_CACHE_TOOLCHAIN=$TOOLCHAIN"
+ echo "MLX_METAL_CACHE_IN=$in"
+ echo "MLX_METAL_CACHE_OUT=$GITHUB_WORKSPACE/.metal-cache"
+ } >> "$GITHUB_ENV"
+ ccache -z
+
+ - name: Show the cache statistics
+ id: stats
+ if: inputs.phase == 'save'
+ shell: bash
+ run: |
+ ccache -s -v
+ ccache_misses=$(ccache -s | awk '$1 == "Misses:" { print $2; exit }')
+ ccache_misses=${ccache_misses:-unknown}
+ metal_misses=0
+ log="$MLX_METAL_CACHE_OUT.log"
+ if [ -f "$log" ]; then
+ metal_misses=$(grep -c '^miss ' "$log" || true)
+ echo "Metal cache: $(grep -c '^hit ' "$log" || true) hits, $metal_misses misses"
+ grep '^miss ' "$log" || true
+ fi
+ du -sh .ccache .metal-cache || true
+ # A build with no misses adds nothing, so it does not save a copy.
+ echo "ccache-misses=$ccache_misses" | tee -a "$GITHUB_OUTPUT"
+ echo "metal-misses=$metal_misses" | tee -a "$GITHUB_OUTPUT"
+
+ - name: Save the ccache files
+ if: inputs.phase == 'save' && env.CI_ACTIONS_CACHE != 'off' && steps.stats.outputs.ccache-misses != '0' && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == 'refs/heads/main'))
+ uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
+ with:
+ path: ${{ github.workspace }}/.ccache
+ key: ${{ inputs.ccache-save-key }}
+
+ - name: Save the Metal kernel cache
+ if: inputs.phase == 'save' && env.CI_ACTIONS_CACHE != 'off' && steps.stats.outputs.metal-misses != '0' && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == 'refs/heads/main'))
+ uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
+ with:
+ path: ${{ github.workspace }}/.metal-cache
+ key: ${{ inputs.metal-save-key }}
diff --git ml-explore/mlx/.github/actions/setup/action.yml Layr-Labs/mlx/.github/actions/setup/action.yml
index 6ba85028bb44d3080a5d386ef2a2c80e376c806a..58440e9d21f907577367a9a2b82e7384d8377041 100644
--- ml-explore/mlx/.github/actions/setup/action.yml
+++ Layr-Labs/mlx/.github/actions/setup/action.yml
@@ -26,11 +26,22 @@ ccache-toolkit:
description: 'Use this instead of inputs.toolkit in the ccache key'
required: false
default: ''
+ ccache-fallback:
+ description: 'A second restore-keys prefix for the ccache files'
+ required: false
+ default: ''
+ install-macos-deps:
+ description: 'Whether to run brew update and install openmpi on macOS'
+ required: false
+ default: 'true'
outputs:
cmake-args:
description: 'The args for generating CMake project'
value: ${{ steps.cmake-args.outputs.cmakeArgs }}
+ ccache-save-key:
+ description: 'The key for actions/cache/save of the ccache files (macOS)'
+ value: ${{ steps.ccache-keys.outputs.save }}
runs:
using: 'composite'
@@ -46,12 +57,14 @@ libblas-dev liblapack-dev liblapacke-dev \
openmpi-bin openmpi-common libopenmpi-dev
- name: Install macOS dependencies
- if: runner.os == 'macOS'
+ if: runner.os == 'macOS' && inputs.install-macos-deps == 'true'
shell: bash
run: |
brew update
brew trust aws/tap # suppress warning in github actions
brew install openmpi
+ xcodebuild -version
+ swift --version
xcodebuild -showComponent MetalToolchain
sysctl -a | grep machdep.cpu
@@ -75,17 +88,45 @@ set CCACHE_SLOPPINESS=include_file_ctime,include_file_mtime
:: Export to all steps.
>>%GITHUB_ENV% set
- - uses: astral-sh/setup-uv@v8.2.0
+ # setup-uv fetches its 1.5 MB version manifest (raw.githubusercontent.com)
+ # with a 5-second limit. Through a Darkbloom sandbox's egress proxy that takes
+ # about 3.3 seconds when it works, and some hosts failed twice in a row on
+ # 2026-11-14; a native job has no hosted fallback. So pin uv and hand setup-uv
+ # a one-entry manifest inline (data: URL, nothing to fetch). The archive still
+ # comes from the Astral mirror, with the tool cache's own retries, and must
+ # match this SHA-256 (the official manifest's, 2026-11-12). Bump all three
+ # together. Only when the first try failed, wait and try once more.
+ - uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
+ id: setup-uv
+ continue-on-error: true
with:
enable-cache: false
quiet: true
+ version: 0.13.8
+ checksum: 6b71028a6b904f2ae3340ef52e595512de807d06c0a20eaef2f692581b246558
+ manifest-file: data:application/x-ndjson;base64,eyJ2ZXJzaW9uIjoiMC4xMy44IiwiZGF0ZSI6IjIwMjYtMTEtMTJUMTc6MDM6MDdaIiwiYXJ0aWZhY3RzIjpbeyJwbGF0Zm9ybSI6ImFhcmNoNjQtYXBwbGUtZGFyd2luIiwidmFyaWFudCI6ImRlZmF1bHQiLCJ1cmwiOiJodHRwczovL2dpdGh1Yi5jb20vYXN0cmFsLXNoL3V2L3JlbGVhc2VzL2Rvd25sb2FkLzAuMTMuOC91di1hYXJjaDY0LWFwcGxlLWRhcndpbi50YXIuZ3oiLCJhcmNoaXZlX2Zvcm1hdCI6InRhci5neiIsInNoYTI1NiI6IjZiNzEwMjhhNmI5MDRmMmFlMzM0MGVmNTJlNTk1NTEyZGU4MDdkMDZjMGEyMGVhZWYyZjY5MjU4MWIyNDY1NTgifV19Cg==
- - name: Use ccache
- if: inputs.use-ccache == 'true'
- uses: hendrikmuhs/ccache-action@v1.2.23
+ - name: Wait before the second uv setup
+ if: steps.setup-uv.outcome == 'failure'
+ shell: bash
+ run: sleep 15
+
+ - uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
+ if: steps.setup-uv.outcome == 'failure'
with:
- key: v7-${{ inputs.ccache-key }}-${{ runner.os }}-${{ runner.arch }}-${{ inputs.ccache-toolkit || inputs.toolkit }}
- max-size: |-
+ enable-cache: false
+ quiet: true
+ version: 0.13.8
+ checksum: 6b71028a6b904f2ae3340ef52e595512de807d06c0a20eaef2f692581b246558
+ manifest-file: data:application/x-ndjson;base64,eyJ2ZXJzaW9uIjoiMC4xMy44IiwiZGF0ZSI6IjIwMjYtMTEtMTJUMTc6MDM6MDdaIiwiYXJ0aWZhY3RzIjpbeyJwbGF0Zm9ybSI6ImFhcmNoNjQtYXBwbGUtZGFyd2luIiwidmFyaWFudCI6ImRlZmF1bHQiLCJ1cmwiOiJodHRwczovL2dpdGh1Yi5jb20vYXN0cmFsLXNoL3V2L3JlbGVhc2VzL2Rvd25sb2FkLzAuMTMuOC91di1hYXJjaDY0LWFwcGxlLWRhcndpbi50YXIuZ3oiLCJhcmNoaXZlX2Zvcm1hdCI6InRhci5neiIsInNoYTI1NiI6IjZiNzEwMjhhNmI5MDRmMmFlMzM0MGVmNTJlNTk1NTEyZGU4MDdkMDZjMGEyMGVhZWYyZjY5MjU4MWIyNDY1NTgifV19Cg==
+
+ # The organization blocks hendrikmuhs/ccache-action. The next three steps
+ # do the same work with Homebrew and actions/cache. They run on macOS only.
+ - name: Install ccache
+ if: runner.os == 'macOS' && inputs.use-ccache == 'true'
+ shell: bash
+ env:
+ MAX_SIZE: |-
${{ case(inputs.ccache-key == 'release',
case(startsWith(inputs.toolkit, 'cuda'),
'300MB',
@@ -97,13 +138,44 @@ '320MB'),
runner.os == 'macOS' && inputs.toolkit == 'metal', '300MB',
'200MB'))
}}
- save: ${{ !startsWith(github.ref, 'refs/pull/') && (inputs.ccache-save != 'false') }}
- # ccache-action bug: running "apt-get update" fails on large arm runner.
- update-package-index: false
+ run: |
+ brew install ccache
+ ccache --set-config=cache_dir="$GITHUB_WORKSPACE/.ccache"
+ ccache --set-config=max_size="$MAX_SIZE"
+ ccache --set-config=compression=true
+ ccache --set-config=compiler_check=content
+ ccache -p
+
+ - name: Make the ccache keys
+ id: ccache-keys
+ if: runner.os == 'macOS' && inputs.use-ccache == 'true'
+ shell: bash
+ env:
+ PREFIX: ccache-${{ inputs.ccache-key }}-${{ runner.os }}-${{ runner.arch }}-${{ inputs.ccache-toolkit || inputs.toolkit }}-
+ FALLBACK: ${{ inputs.ccache-fallback }}
+ run: |
+ {
+ echo "restore=$PREFIX$GITHUB_SHA"
+ echo "save=$PREFIX$GITHUB_SHA-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
+ echo "restore-keys<<EOF"
+ echo "$PREFIX"
+ if [ -n "$FALLBACK" ]; then echo "$FALLBACK"; fi
+ echo "EOF"
+ } | tee -a "$GITHUB_OUTPUT"
+
+ - name: Restore the ccache files
+ # This action only restores the cache. The workflow saves it with
+ # actions/cache/save and the key in the ccache-save-key output.
+ if: runner.os == 'macOS' && inputs.use-ccache == 'true' && env.CI_ACTIONS_CACHE != 'off'
+ uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
+ with:
+ path: ${{ github.workspace }}/.ccache
+ key: ${{ steps.ccache-keys.outputs.restore }}
+ restore-keys: ${{ steps.ccache-keys.outputs.restore-keys }}
- name: Cache JIT-compiled CUDA kernels
if: runner.os == 'Linux' && startsWith(inputs.toolkit, 'cuda')
- uses: actions/cache@v5
+ uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: /tmp/mlx-ptx-cache
key: >-
@@ -125,6 +197,13 @@ # Use PTX ccache for CUDA.
if ${{ startsWith(inputs.toolkit, 'cuda') }} ; then
echo MLX_PTX_CACHE_DIR=/tmp/mlx-ptx-cache >> $GITHUB_ENV
fi
+
+ - name: Install Ninja on macOS
+ if: runner.os == 'macOS'
+ shell: bash
+ run: |
+ uv pip install --python .venv/bin/python --only-binary=:all: 'ninja==1.13.2'
+ .venv/bin/ninja --version
- name: Setup Python venv (Windows)
if: runner.os == 'Windows'
diff --git ml-explore/mlx/.github/actions/test-linux/action.yml Layr-Labs/mlx/.github/actions/test-linux/action.yml
deleted file mode 100644
index 7c5f4322137a5b08c20feba74070b55d343b5e6e..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/actions/test-linux/action.yml
+++ /dev/null
@@ -1,69 +0,0 @@
-name: 'Run tests'
-description: 'Run Python and C++ tests on Linux'
-
-runs:
- using: 'composite'
- steps:
- - name: Check GPU support
- id: gpu-check
- shell: bash
- run: |
- if __nvcc_device_query ; then
- echo "good=true" >> $GITHUB_OUTPUT
- else
- echo "good=false" >> $GITHUB_OUTPUT
- fi
- echo
-
- - name: Run MPI tests
- if: steps.gpu-check.outputs.good == 'false'
- shell: bash
- run: mpirun --bind-to none --allow-run-as-root -host localhost:8 -np 8 python python/tests/mpi_test_distributed.py
-
- - name: Run distributed tests
- if: steps.gpu-check.outputs.good == 'false'
- shell: bash
- run: |
- mlx.launch --verbose -n 8 python python/tests/ring_test_distributed.py -v 2> >(tee -a stderr.log >&2)
- if grep -Fq '[WARN]' stderr.log ; then
- grep -F '[WARN]' stderr.log
- echo "Distributed ring test failed";
- exit 1;
- fi
-
- - name: Run Python tests - CPU
- if: steps.gpu-check.outputs.good == 'false'
- shell: bash
- env:
- DEVICE: cpu
- run: python python/tests/run.py -v
-
- - name: Run Python tests - GPU
- if: steps.gpu-check.outputs.good == 'true'
- shell: bash
- env:
- DEVICE: gpu
- run: python python/tests/run.py -v
-
- - name: Run CPP tests - CPU
- shell: bash
- env:
- DEVICE: cpu
- run: ./build/cpp/mlx/tests/tests
-
- - name: Run CPP tests - GPU
- if: steps.gpu-check.outputs.good == 'true'
- shell: bash
- env:
- DEVICE: gpu
- run: ./build/cpp/mlx/tests/tests -sfe="*linalg_tests.cpp"
-
- - name: Show stack trace on crash
- if: failure()
- shell: bash
- run: |
- set +e
- sleep 10
- if coredumpctl list; then
- coredumpctl debug --debugger-arguments="-batch -ex 'thread apply all bt'"
- fi
diff --git ml-explore/mlx/.github/actions/test-wheel/action.yml Layr-Labs/mlx/.github/actions/test-wheel/action.yml
deleted file mode 100644
index e060876503c631efa05aa838c5c7347701c21396..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/actions/test-wheel/action.yml
+++ /dev/null
@@ -1,49 +0,0 @@
-name: 'Test wheel'
-description: 'Run tests with the built wheels'
-
-inputs:
- toolkit:
- description: 'Which toolkit to test'
- required: false
- default: 'cpu'
-
-runs:
- using: 'composite'
- steps:
- - name: Get Python version
- id: python
- shell: bash
- run: python -c "import sys; print(f'version={sys.version_info.major}.{sys.version_info.minor}')" >> $GITHUB_OUTPUT
-
- - name: Download frontend packages
- uses: actions/download-artifact@v8
- with:
- pattern: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ steps.python.outputs.version }}
- path: wheelhouse
-
- - name: Download backend packages
- uses: actions/download-artifact@v8
- with:
- pattern: backend-${{ inputs.toolkit}}-${{ runner.os }}-${{ runner.arch }}
- path: wheelhouse
-
- - name: Test local packages
- shell: bash
- run: |
- # Fall back to PyPI if PyTorch index has issues.
- uv pip install torch --torch-backend=cpu
- uv pip install numpy
- if ${{ inputs.toolkit == 'cpu' }} ; then
- uv pip install wheelhouse/mlx_cpu*.whl
- uv pip install wheelhouse/mlx-*.whl
- elif ${{ startsWith(inputs.toolkit, 'cuda') }} ; then
- uv pip install wheelhouse/mlx_cuda*.whl
- uv pip install wheelhouse/mlx-*.whl
- elif ${{ inputs.toolkit == 'metal' }} ; then
- uv pip install wheelhouse/mlx_metal-*-macosx_26_0_arm64.whl
- uv pip install wheelhouse/mlx-*-macosx_26_0_arm64.whl
- else
- echo "No matching backend wheel to install"
- exit 1
- fi
- uv run python/tests/run.py -v --failfast
diff --git ml-explore/mlx/.github/actions/test-windows/action.yml Layr-Labs/mlx/.github/actions/test-windows/action.yml
deleted file mode 100644
index 6d89c4e5bd3c3f421a7a1cff505871fbf5e66cd2..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/actions/test-windows/action.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-name: 'Run tests'
-description: 'Run Python and C++ tests on Windows'
-
-runs:
- using: 'composite'
- steps:
- - name: Run Python tests - CPU
- shell: bash
- env:
- DEVICE: cpu
- run: uv run python/tests/run.py -v
-
- - name: Run CPP tests - CPU
- shell: bash
- env:
- DEVICE: cpu
- run: ./build/cpp/mlx/tests.exe -tce="*gguf*"
diff --git ml-explore/mlx/.github/scripts/ci-resource-sampler.py Layr-Labs/mlx/.github/scripts/ci-resource-sampler.py
new file mode 100755
index 0000000000000000000000000000000000000000..bfa54280c9bcf6b8501a1b02c8e92d2dc651b670
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/ci-resource-sampler.py
@@ -0,0 +1,720 @@
+#!/usr/bin/env python3
+"""Sample a macOS CI job's memory and CPU use and report the peaks. Report-only.
+
+`start` runs the sampler in the background and gives later steps the samples
+directory as CI_RESOURCE_SAMPLES. Every INTERVAL seconds it writes one CSV row:
+
+- memory by class, from `vm_stat`: app (anonymous pages less purgeable ones;
+ Metal buffers count here), wired, file cache (file-backed and purgeable
+ pages, which the kernel can reclaim), compressed,
+ and used = app + wired + compressed, as Activity Monitor counts it; swap in
+ use (`sysctl vm.swapusage`) and the kernel's memory pressure level
+ (`kern.memorystatus_vm_pressure_level`: 1 normal, 2 warning, 4 critical);
+- busy vCPUs over the interval, from the host's CPU ticks (`host_statistics`),
+ or the sum of the `ps` %cpu averages where those are not available;
+- the physical footprint of every process this user can read, from
+ `proc_pid_rusage`: `ri_phys_footprint` is the counter `footprint` and
+ Activity Monitor show, and it includes IOAccelerator (Metal) memory. The row
+ keeps their sum and the three largest by lifetime peak
+ (`ri_lifetime_max_phys_footprint`, so a peak between samples counts), each
+ with the test selection it runs under;
+- the largest resident process (`ps` RSS), to compare with earlier runs.
+
+When the largest footprint first reaches 2 GiB, and again when it is 2 GiB
+above the last capture, `/usr/bin/footprint`, where present, writes that
+process's breakdown by category beside the samples (at most twice a job). Test
+runners call `mark start|end LABEL PID` around each selection; a process below
+PID belongs to LABEL.
+
+`report` stops the sampler. It prints the peak of each class, the three
+largest processes, the selections that ran at the peak, the busy vCPU mean,
+95th percentile and maximum, and the sampled time scaled to 4 and 8 vCPUs; in
+CI it also writes them to the step summary, and to summary.json beside the
+samples. No subcommand ever fails a job: every error is printed and exits 0.
+
+Subcommands:
+ start DIRECTORY [--interval SECONDS]
+ report DIRECTORY
+ mark start|end LABEL [PID] into $CI_RESOURCE_SAMPLES (nothing without it);
+ PID defaults to the caller, the mark's parent
+ run DIRECTORY [--interval SECONDS] the background loop `start` launches
+"""
+
+import argparse
+import csv
+import ctypes
+import json
+import os
+import re
+import signal
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+FIELDS = (
+ "time",
+ "used_bytes",
+ "app_bytes",
+ "wired_bytes",
+ "file_bytes",
+ "compressed_bytes",
+ "swap_bytes",
+ "pressure",
+ "busy_vcpus",
+ "footprint_bytes",
+ "top_rss_bytes",
+ "top_command",
+ "top_footprints",
+)
+CLASSES = (
+ ("used_bytes", "Used"),
+ ("app_bytes", "App"),
+ ("wired_bytes", "Wired"),
+ ("file_bytes", "File cache"),
+ ("compressed_bytes", "Compressed"),
+ ("swap_bytes", "Swap"),
+)
+SAMPLES = "samples.csv"
+PID = "sampler.pid"
+MACHINE = "machine.txt"
+MARKS = "marks.csv"
+SUMMARY = "summary.json"
+ENVIRONMENT = "CI_RESOURCE_SAMPLES"
+FOOTPRINT = "/usr/bin/footprint"
+CAPTURES = 2
+CAPTURE_STEP = 2 * 2**30
+CAPTURE_SECONDS = 60
+TOP = 3
+SCALED_VCPUS = (4, 8)
+GIB = 2**30
+UNITS = {"K": 2**10, "M": 2**20, "G": 2**30}
+RUSAGE_INFO_V4 = 4
+HOST_CPU_LOAD_INFO = 3
+
+
+class RusageInfoV4(ctypes.Structure):
+ """struct rusage_info_v4 (<sys/resource.h>)."""
+
+ _fields_ = [("ri_uuid", ctypes.c_uint8 * 16)] + [
+ (name, ctypes.c_uint64)
+ for name in (
+ "ri_user_time",
+ "ri_system_time",
+ "ri_pkg_idle_wkups",
+ "ri_interrupt_wkups",
+ "ri_pageins",
+ "ri_wired_size",
+ "ri_resident_size",
+ "ri_phys_footprint",
+ "ri_proc_start_abstime",
+ "ri_proc_exit_abstime",
+ "ri_child_user_time",
+ "ri_child_system_time",
+ "ri_child_pkg_idle_wkups",
+ "ri_child_interrupt_wkups",
+ "ri_child_pageins",
+ "ri_child_elapsed_abstime",
+ "ri_diskio_bytesread",
+ "ri_diskio_byteswritten",
+ "ri_cpu_time_qos_default",
+ "ri_cpu_time_qos_maintenance",
+ "ri_cpu_time_qos_background",
+ "ri_cpu_time_qos_utility",
+ "ri_cpu_time_qos_legacy",
+ "ri_cpu_time_qos_user_initiated",
+ "ri_cpu_time_qos_user_interactive",
+ "ri_billed_system_time",
+ "ri_serviced_system_time",
+ "ri_logical_writes",
+ "ri_lifetime_max_phys_footprint",
+ "ri_instructions",
+ "ri_cycles",
+ "ri_billed_energy",
+ "ri_serviced_energy",
+ "ri_interval_max_phys_footprint",
+ "ri_runnable_time",
+ )
+ ]
+
+
+# Native calls fail with these; the sampler then records what it can without them.
+NATIVE_ERRORS = (OSError, AttributeError, TypeError, ctypes.ArgumentError)
+_system = None
+
+
+def system():
+ """(libSystem with the calls the sampler makes, the host port).
+
+ OSError where there is none.
+ """
+ global _system
+ if _system is None:
+ if sys.platform != "darwin":
+ raise OSError("proc_pid_rusage and host_statistics need macOS")
+ library = ctypes.CDLL("/usr/lib/libSystem.B.dylib")
+ library.proc_pid_rusage.argtypes = [
+ ctypes.c_int,
+ ctypes.c_int,
+ ctypes.POINTER(RusageInfoV4),
+ ]
+ library.proc_pid_rusage.restype = ctypes.c_int
+ library.mach_host_self.argtypes = []
+ library.mach_host_self.restype = ctypes.c_uint32
+ library.host_statistics.argtypes = [
+ ctypes.c_uint32,
+ ctypes.c_int,
+ ctypes.POINTER(ctypes.c_uint32 * 4),
+ ctypes.POINTER(ctypes.c_uint32),
+ ]
+ library.host_statistics.restype = ctypes.c_int
+ _system = (library, library.mach_host_self())
+ return _system
+
+
+def output(*argv):
+ return subprocess.run(
+ argv, capture_output=True, text=True, timeout=10, check=True
+ ).stdout
+
+
+def memory(vm_stat):
+ """Bytes of each memory class (CLASSES but swap) from `vm_stat` text."""
+ size = int(re.search(r"page size of (\d+) bytes", vm_stat).group(1))
+ pages = {
+ name.strip().lower(): int(value)
+ for name, value in re.findall(r'^"?([^:"]+)"?:\s+(\d+)\.', vm_stat, re.M)
+ }
+ purgeable = pages["pages purgeable"]
+ app = pages["anonymous pages"] - purgeable
+ wired = pages["pages wired down"]
+ compressed = pages["pages occupied by compressor"]
+ return {
+ "used_bytes": (app + wired + compressed) * size,
+ "app_bytes": app * size,
+ "wired_bytes": wired * size,
+ "file_bytes": (pages["file-backed pages"] + purgeable) * size,
+ "compressed_bytes": compressed * size,
+ }
+
+
+def swap_used(swapusage):
+ """Bytes of swap in use from `sysctl -n vm.swapusage` text."""
+ match = re.search(r"used = ([0-9.]+)([KMG])", swapusage)
+ return int(float(match.group(1)) * UNITS[match.group(2)])
+
+
+def processes(ps):
+ """[(pid, ppid, %cpu, RSS bytes, command)] from `ps` text.
+
+ The text is the output of `ps -A -o pid=,ppid=,%cpu=,rss=,comm=`.
+ """
+ rows = []
+ for line in ps.splitlines():
+ fields = line.split(None, 4)
+ try:
+ rows.append(
+ (
+ int(fields[0]),
+ int(fields[1]),
+ float(fields[2]),
+ int(fields[3]) * 1024,
+ os.path.basename(fields[4].strip()) if len(fields) > 4 else "",
+ )
+ )
+ except (IndexError, ValueError):
+ continue
+ return rows
+
+
+def footprints(pids):
+ """{pid: (physical footprint, lifetime peak)} of the processes this user reads."""
+ library, _ = system()
+ info = RusageInfoV4()
+ found = {}
+ for pid in pids:
+ if library.proc_pid_rusage(pid, RUSAGE_INFO_V4, ctypes.byref(info)) == 0:
+ found[pid] = (info.ri_phys_footprint, info.ri_lifetime_max_phys_footprint)
+ return found
+
+
+def cpu_ticks():
+ """(busy, all) CPU ticks of every CPU since boot.
+
+ HOST_CPU_LOAD_INFO: user, system, idle, nice.
+ """
+ library, host = system()
+ ticks = (ctypes.c_uint32 * 4)()
+ count = ctypes.c_uint32(4)
+ if (
+ library.host_statistics(
+ host, HOST_CPU_LOAD_INFO, ctypes.byref(ticks), ctypes.byref(count)
+ )
+ != 0
+ ):
+ raise OSError("host_statistics(HOST_CPU_LOAD_INFO) failed")
+ return ticks[0] + ticks[1] + ticks[3], sum(ticks)
+
+
+def busy_vcpus(before, after, cpus):
+ """Busy vCPUs between two cpu_ticks() readings; None when no tick passed."""
+ busy, total = ((now - then) % 2**32 for now, then in zip(after, before))
+ return busy / total * cpus if total else None
+
+
+def read_marks(path):
+ """[(time, event, label, pid)] of the whole rows of a marks file; [] without one."""
+ try:
+ text = path.read_text()
+ except OSError:
+ return []
+ marks = []
+ for row in csv.reader(text.splitlines()):
+ if len(row) != 4 or not row[3].isdigit():
+ continue
+ stamp, event, label, pid = row
+ try:
+ marks.append((float(stamp), event, label, int(pid)))
+ except ValueError:
+ continue
+ return marks
+
+
+def active_marks(path):
+ """{pid: label} of the selections started under pid and not yet ended.
+
+ From a marks file.
+ """
+ active = {}
+ for _, event, label, pid in read_marks(path):
+ if event == "start":
+ active[pid] = label
+ elif event == "end" and active.get(pid) == label:
+ del active[pid]
+ return active
+
+
+def selection_of(pid, parents, active):
+ """The label of the nearest marked ancestor of pid (itself included), or ""."""
+ seen = set()
+ while pid and pid not in seen:
+ if pid in active:
+ return active[pid]
+ seen.add(pid)
+ pid = parents.get(pid)
+ return ""
+
+
+class Sampler:
+ """One sample a call; keeps the CPU ticks and footprint captures between calls."""
+
+ def __init__(self, directory):
+ self.directory = directory
+ self.cpus = os.cpu_count() or 1
+ self.ticks = self.read_ticks()
+ self.captured_bytes = 0
+ self.captures = []
+
+ def read_ticks(self):
+ try:
+ return cpu_ticks()
+ except NATIVE_ERRORS:
+ return None
+
+ def busy(self, listed):
+ ticks = self.read_ticks()
+ busy = (
+ busy_vcpus(self.ticks, ticks, self.cpus) if ticks and self.ticks else None
+ )
+ self.ticks = ticks
+ return sum(cpu for _, _, cpu, _, _ in listed) / 100 if busy is None else busy
+
+ def sample(self):
+ row = {"time": f"{time.time():.0f}", **memory(output("vm_stat"))}
+ row["swap_bytes"] = swap_used(output("sysctl", "-n", "vm.swapusage"))
+ row["pressure"] = output(
+ "sysctl", "-n", "kern.memorystatus_vm_pressure_level"
+ ).strip()
+ listed = processes(output("ps", "-A", "-o", "pid=,ppid=,%cpu=,rss=,comm="))
+ row["busy_vcpus"] = f"{self.busy(listed):.2f}"
+ largest = max(
+ listed, key=lambda process: process[3], default=(0, 0, 0.0, 0, "")
+ )
+ row["top_rss_bytes"], row["top_command"] = largest[3], largest[4]
+ try:
+ found = footprints([pid for pid, *_ in listed])
+ except NATIVE_ERRORS:
+ found = {}
+ if found:
+ parents = {pid: ppid for pid, ppid, *_ in listed}
+ commands = {pid: command for pid, _, _, _, command in listed}
+ active = active_marks(self.directory / MARKS)
+ ranked = sorted(found, key=lambda pid: found[pid][1], reverse=True)[:TOP]
+ row["footprint_bytes"] = sum(current for current, _ in found.values())
+ row["top_footprints"] = json.dumps(
+ [
+ [
+ pid,
+ commands[pid],
+ *found[pid],
+ selection_of(pid, parents, active),
+ ]
+ for pid in ranked
+ ]
+ )
+ current = max(found, key=lambda pid: found[pid][0])
+ self.capture(current, found[current][0], row["time"])
+ self.reap()
+ return [row.get(field, "") for field in FIELDS]
+
+ def capture(self, pid, footprint, stamp):
+ """`footprint PID` into the directory.
+
+ Only when footprint is CAPTURE_STEP above the last capture (or 0).
+ """
+ if (
+ footprint < self.captured_bytes + CAPTURE_STEP
+ or len(self.captures) >= CAPTURES
+ or not os.access(FOOTPRINT, os.X_OK)
+ ):
+ return
+ self.captured_bytes = footprint
+ with open(self.directory / f"footprint-{stamp}-{pid}.txt", "w") as handle:
+ self.captures.append(
+ (
+ time.monotonic(),
+ subprocess.Popen(
+ [FOOTPRINT, str(pid)],
+ stdin=subprocess.DEVNULL,
+ stdout=handle,
+ stderr=subprocess.STDOUT,
+ ),
+ )
+ )
+
+ def reap(self):
+ for started, child in self.captures:
+ if child.poll() is None and time.monotonic() - started > CAPTURE_SECONDS:
+ child.kill()
+
+
+def run(directory, interval):
+ sampler = Sampler(directory)
+ with open(directory / SAMPLES, "a", newline="") as handle:
+ writer = csv.writer(handle)
+ while True:
+ try:
+ writer.writerow(sampler.sample())
+ handle.flush()
+ except (
+ Exception
+ ): # Report-only: a failed sample is skipped; the loop goes on.
+ pass
+ time.sleep(interval)
+
+
+def start(directory, interval):
+ directory.mkdir(parents=True, exist_ok=True)
+ with open(directory / SAMPLES, "w", newline="") as handle:
+ csv.writer(handle).writerow(FIELDS)
+ try:
+ machine = output("sysctl", "-n", "hw.ncpu", "hw.memsize").split()
+ (directory / MACHINE).write_text(f"{machine[0]} {machine[1]}\n")
+ except (OSError, IndexError, subprocess.SubprocessError):
+ pass
+ child = subprocess.Popen(
+ [
+ sys.executable,
+ os.path.abspath(__file__),
+ "run",
+ str(directory),
+ "--interval",
+ str(interval),
+ ],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ (directory / PID).write_text(f"{child.pid}\n")
+ github_env = os.environ.get("GITHUB_ENV")
+ if github_env:
+ with open(github_env, "a") as handle:
+ handle.write(f"{ENVIRONMENT}={directory.resolve()}\n")
+ print(
+ f"Resource sampler: pid {child.pid}, every {interval} s, "
+ f"into {directory / SAMPLES}"
+ )
+
+
+def mark(event, label, pid=None):
+ """Note that selection `label` starts or ends under process pid.
+
+ pid defaults to the caller. Nothing outside a sampled job.
+ """
+ directory = os.environ.get(ENVIRONMENT)
+ if not directory:
+ return
+ if event not in ("start", "end"):
+ raise ValueError(f"mark takes start or end, got {event!r}")
+ with open(Path(directory) / MARKS, "a", newline="") as handle:
+ csv.writer(handle).writerow(
+ [
+ f"{time.time():.3f}",
+ event,
+ label,
+ os.getppid() if pid is None else int(pid),
+ ]
+ )
+
+
+def percentile(values, fraction):
+ ordered = sorted(values)
+ return ordered[min(len(ordered) - 1, int(fraction * len(ordered)))]
+
+
+def number(value):
+ return int(value) if value not in (None, "") else None
+
+
+def gib(value):
+ return "n/a" if value is None else f"{value / GIB:.2f}"
+
+
+def utc(stamp):
+ return time.strftime("%H:%M:%S", time.gmtime(float(stamp)))
+
+
+def selections_at(path, moment):
+ """The labels of the marks file that had started and not ended at moment."""
+ spans = {}
+ for stamp, event, label, pid in read_marks(path):
+ span = spans.setdefault((label, pid), [None, None])
+ span[0 if event == "start" else 1] = stamp
+ return sorted(
+ label
+ for (label, _), (began, ended) in spans.items()
+ if began is not None and began <= moment and (ended is None or ended >= moment)
+ )
+
+
+def scaled_seconds(rows, cpus):
+ """Sampled seconds if busy vCPUs above `cpus` had run on `cpus`.
+
+ Each interval is stretched by busy / cpus.
+ """
+ total = 0.0
+ for before, after in zip(rows, rows[1:]):
+ total += (int(after["time"]) - int(before["time"])) * max(
+ 1.0, float(after["busy_vcpus"]) / cpus
+ )
+ return total
+
+
+def top_processes(rows):
+ """The TOP processes by lifetime footprint peak.
+
+ [pid, command, peak bytes, selection, time].
+ """
+ best = {}
+ for row in rows:
+ for pid, command, _, peak, label in json.loads(
+ row.get("top_footprints") or "[]"
+ ):
+ known = best.get(pid)
+ if known is None or peak > known[2]:
+ best[pid] = [
+ pid,
+ command,
+ peak,
+ label or (known[3] if known else ""),
+ row["time"],
+ ]
+ elif label and not known[3]:
+ known[3] = label
+ return sorted(best.values(), key=lambda process: process[2], reverse=True)[:TOP]
+
+
+def footprint_captures(directory):
+ """[(file, its header and IOAccelerator lines)] of the `footprint` captures."""
+ captured = []
+ for path in sorted(directory.glob("footprint-*.txt")):
+ lines = [
+ line.strip()
+ for line in path.read_text(errors="replace").splitlines()
+ if line.strip()
+ ]
+ kept = [
+ line for line in lines if "Footprint" in line or "IOAccelerator" in line
+ ][:4] or lines[:1]
+ captured.append((path.name, kept))
+ return captured
+
+
+def summary(directory):
+ """The report's Markdown lines; also writes summary.json."""
+ with open(directory / SAMPLES, newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ if not rows:
+ return ["Resource sampler: no samples."]
+ facts = {
+ "samples": len(rows),
+ "seconds": int(rows[-1]["time"]) - int(rows[0]["time"]),
+ "peaks": {},
+ }
+ lines = []
+ machine = directory / MACHINE
+ cpus = None
+ if machine.is_file():
+ cpus, memsize = (int(value) for value in machine.read_text().split())
+ facts["machine"] = {"vcpus": cpus, "memory_bytes": memsize}
+ lines.append(f"Machine: {cpus} vCPUs, {memsize / GIB:.1f} GiB.")
+ for key, _ in CLASSES + (("footprint_bytes", "footprints"),):
+ known = [row for row in rows if number(row.get(key)) is not None]
+ peak = max(known, key=lambda row: number(row[key]), default=None)
+ facts["peaks"][key] = (
+ None
+ if peak is None
+ else {"bytes": number(peak[key]), "time": int(peak["time"])}
+ )
+
+ def peak_bytes(key):
+ return None if facts["peaks"][key] is None else facts["peaks"][key]["bytes"]
+
+ busy = [float(row["busy_vcpus"]) for row in rows]
+ facts["pressure"] = max(int(row["pressure"]) for row in rows)
+ facts["busy_vcpus"] = {
+ "mean": sum(busy) / len(busy),
+ "p95": percentile(busy, 0.95),
+ "max": max(busy),
+ }
+ lines += [
+ "| Samples | "
+ + " | ".join(f"{name} (GiB)" for _, name in CLASSES)
+ + " | Worst pressure | Busy vCPUs mean | p95 | max |",
+ "|---" * (len(CLASSES) + 5) + "|",
+ f"| {len(rows)} over {facts['seconds']} s | "
+ + " | ".join(gib(peak_bytes(key)) for key, _ in CLASSES)
+ + f" | {facts['pressure']} | {facts['busy_vcpus']['mean']:.2f} | "
+ f"{facts['busy_vcpus']['p95']:.2f} | "
+ f"{facts['busy_vcpus']['max']:.2f} |",
+ "",
+ "Each class peaks at its own time. Used = app + wired + compressed "
+ "(`vm_stat`); app holds Metal buffers; the file cache is reclaimable.",
+ ]
+ if facts["peaks"]["used_bytes"]:
+ moment = facts["peaks"]["used_bytes"]["time"]
+ running = selections_at(directory / MARKS, moment)
+ facts["selections_at_peak_used"] = running
+ lines.append(
+ f"Peak used at {utc(moment)} UTC"
+ + (f", during: {', '.join(running)}." if running else ".")
+ )
+ top = top_processes(rows)
+ facts["top_processes"] = [
+ {
+ "pid": pid,
+ "command": command,
+ "peak_footprint_bytes": footprint,
+ "selection": label,
+ "time": int(stamp),
+ }
+ for pid, command, footprint, label, stamp in top
+ ]
+ if top:
+ lines += [
+ "",
+ "| Process | PID | Peak footprint (GiB) | Selection | Seen at (UTC) |",
+ "|---|---|---|---|---|",
+ ]
+ lines += [
+ f"| `{command}` | {pid} | {gib(footprint)} | {label or '-'} "
+ f"| {utc(stamp)} |"
+ for pid, command, footprint, label, stamp in top
+ ]
+ lines.append(
+ "Footprints: `proc_pid_rusage` lifetime peak (includes "
+ "IOAccelerator/Metal memory), processes of this user only; their sum "
+ f"peaked at {gib(peak_bytes('footprint_bytes'))} GiB."
+ )
+ largest = max(rows, key=lambda row: int(row["top_rss_bytes"]))
+ lines.append(
+ "Largest RSS (`ps`, earlier runs' figure): "
+ f"{gib(int(largest['top_rss_bytes']))} GiB "
+ f"(`{largest['top_command']}`)."
+ )
+ if cpus:
+ facts["scaled_seconds"] = {
+ str(n): scaled_seconds(rows, n) for n in SCALED_VCPUS if n < cpus
+ }
+ if facts["scaled_seconds"]:
+ lines.append(
+ f"Sampled {facts['seconds']} s; at "
+ + ", at ".join(
+ f"{n} vCPUs about {seconds:.0f} s"
+ for n, seconds in facts["scaled_seconds"].items()
+ )
+ + " (each interval stretched by busy vCPUs / vCPUs where busy "
+ "exceeds them)."
+ )
+ captures = footprint_captures(directory)
+ facts["footprint_tool"] = "present" if os.access(FOOTPRINT, os.X_OK) else "absent"
+ facts["footprint_captures"] = [
+ {"file": name, "lines": kept} for name, kept in captures
+ ]
+ lines.append(
+ f"`{FOOTPRINT}`: {facts['footprint_tool']}, {len(captures)} captures "
+ "in the samples artifact."
+ )
+ lines += [
+ f"- `{name}`: " + "; ".join(f"`{line}`" for line in kept)
+ for name, kept in captures
+ ]
+ (directory / SUMMARY).write_text(json.dumps(facts, indent=2, sort_keys=True) + "\n")
+ return lines
+
+
+def report(directory):
+ pid = directory / PID
+ if pid.is_file():
+ try:
+ os.kill(int(pid.read_text()), signal.SIGTERM)
+ except (OSError, ValueError):
+ pass
+ lines = ["### Resource samples (report-only)", "", *summary(directory)]
+ print("\n".join(lines))
+ step_summary = os.environ.get("GITHUB_STEP_SUMMARY")
+ if step_summary:
+ with open(step_summary, "a") as handle:
+ handle.write("\n".join(lines) + "\n\n")
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ commands = parser.add_subparsers(dest="command", required=True)
+ for name in ("start", "run", "report"):
+ command = commands.add_parser(name)
+ command.add_argument("directory", type=Path)
+ if name != "report":
+ command.add_argument("--interval", type=float, default=5.0)
+ marking = commands.add_parser("mark")
+ marking.add_argument("event")
+ marking.add_argument("label")
+ marking.add_argument("pid", nargs="?")
+ args = parser.parse_args(argv)
+ try:
+ if args.command == "start":
+ start(args.directory, args.interval)
+ elif args.command == "run":
+ run(args.directory, args.interval)
+ elif args.command == "mark":
+ mark(args.event, args.label, args.pid)
+ else:
+ report(args.directory)
+ except Exception as error: # Report-only: never fail the job.
+ print(f"::warning title=Resource sampler::{type(error).__name__}: {error}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git ml-explore/mlx/.github/scripts/codeql_artifacts.py Layr-Labs/mlx/.github/scripts/codeql_artifacts.py
new file mode 100644
index 0000000000000000000000000000000000000000..dacee361744f10718b59c8234eee408850b2f725
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/codeql_artifacts.py
@@ -0,0 +1,201 @@
+#!/usr/bin/env python3
+"""Bind read-only CodeQL SARIF to the exact Actions run before upload."""
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import urllib.parse
+from pathlib import Path, PurePosixPath
+
+# BEGIN DATA VALIDATOR
+LANGUAGES = {
+ "actions": "/language:actions",
+ "cpp": "/language:c-cpp",
+ "python": "/language:python",
+}
+CODEQL_VERSION = "2.27.4"
+MAX_FILE = 16 * 1024 * 1024
+MAX_BUNDLE = 64 * 1024 * 1024
+
+
+def context():
+ return {
+ key: os.environ[env]
+ for key, env in {
+ "repository": "GITHUB_REPOSITORY",
+ "sha": "GITHUB_SHA",
+ "ref": "GITHUB_REF",
+ "run_id": "GITHUB_RUN_ID",
+ "attempt": "GITHUB_RUN_ATTEMPT",
+ }.items()
+ }
+
+
+def relative_path(value):
+ if not isinstance(value, str) or not value or "\\" in value or "\x00" in value:
+ raise ValueError("invalid bundle path")
+ path = PurePosixPath(value)
+ if path.is_absolute() or any(part in ("..", ".git") for part in path.parts):
+ raise ValueError("bundle path escapes its data directory")
+ if path.as_posix() != value:
+ raise ValueError("bundle path is not canonical")
+ return path
+
+
+def digest(path):
+ with path.open("rb") as source:
+ return hashlib.file_digest(source, "sha256").hexdigest()
+
+
+def validate_sarif(sarif):
+ if sarif.get("version") != "2.1.0" or not sarif.get("runs"):
+ raise ValueError("invalid SARIF")
+ if not any(
+ run.get("tool", {}).get("driver", {}).get("rules") for run in sarif["runs"]
+ ):
+ raise ValueError("analysis has no rules")
+ for run in sarif["runs"]:
+ driver = run.get("tool", {}).get("driver", {})
+ if (
+ driver.get("name") != "CodeQL"
+ or driver.get("semanticVersion") != CODEQL_VERSION
+ ):
+ raise ValueError("SARIF was not produced by the qualified CodeQL version")
+ artifacts = run.get("artifacts", [])
+ for result in run.get("results", []):
+ locations = result.get("locations", [])
+ if not locations:
+ continue
+ primary = locations[0].get("physicalLocation", {})
+ location = primary.get("artifactLocation", {})
+ if "uri" not in location and "index" in location:
+ index = location["index"]
+ if type(index) is not int or not 0 <= index < len(artifacts):
+ raise ValueError("invalid artifact index")
+ location = artifacts[index]["location"]
+ uri = urllib.parse.urlsplit(location.get("uri", ""))
+ if uri.scheme or uri.netloc:
+ raise ValueError("source location is not repository relative")
+ relative_path(urllib.parse.unquote(uri.path))
+ if primary.get("region", {}).get("startLine") is not None:
+ fingerprint = result.get("partialFingerprints", {}).get(
+ "primaryLocationLineHash", ""
+ )
+ if not re.fullmatch(r"[0-9a-f]+:[1-9][0-9]*", fingerprint):
+ raise ValueError("source-line finding lacks a stable fingerprint")
+
+
+def verify_bundle(root, expected):
+ root = root.resolve(strict=True)
+ manifest_file = root / "manifest.json"
+ if manifest_file.is_symlink() or manifest_file.stat().st_size > 256 * 1024:
+ raise ValueError("invalid manifest")
+ manifest = json.loads(manifest_file.read_text())
+ if manifest.get("context") != expected or manifest.get("version") != 1:
+ raise ValueError(
+ "scan belongs to another run, attempt, repository, ref or commit"
+ )
+ if (
+ manifest.get("codeql_version") != CODEQL_VERSION
+ or manifest.get("categories") != LANGUAGES
+ ):
+ raise ValueError("unexpected CodeQL recipe")
+ files = manifest.get("files")
+ if not isinstance(files, dict) or len(files) != 3:
+ raise ValueError("invalid file inventory")
+ required = {f"sarif/{language}.sarif" for language in LANGUAGES}
+ if not required.issubset(files):
+ raise ValueError("missing language")
+ actual = set()
+ total = 0
+ for path in root.rglob("*"):
+ if path.is_symlink():
+ raise ValueError("symlinks are not scan data")
+ if not path.is_file():
+ if path.is_dir():
+ continue
+ raise ValueError("only regular files are scan data")
+ rel = path.relative_to(root).as_posix()
+ if rel == "manifest.json":
+ continue
+ relative_path(rel)
+ if not path.resolve().is_relative_to(root):
+ raise ValueError("file escapes bundle")
+ spec = files.get(rel)
+ size = path.stat().st_size
+ if not isinstance(spec, dict) or not 0 <= size <= MAX_FILE:
+ raise ValueError("unexpected or oversized file")
+ if spec.get("size") != size or spec.get("sha256") != digest(path):
+ raise ValueError("scan data changed")
+ if rel not in required:
+ raise ValueError("only the three SARIF files may be supplied")
+ actual.add(rel)
+ total += size
+ if actual != set(files) or total > MAX_BUNDLE:
+ raise ValueError("file inventory differs or bundle exceeds limit")
+ for language in LANGUAGES:
+ sarif = json.loads((root / f"sarif/{language}.sarif").read_text())
+ validate_sarif(sarif)
+ # The official uploader falls back to event SHA/ref without a checkout.
+ # Native CodeQL already supplies every primary-line fingerprint.
+ empty_checkout = root / "empty-checkout"
+ empty_checkout.mkdir(exist_ok=True)
+ return empty_checkout
+
+
+# END DATA VALIDATOR
+
+
+def pack_bundle(checkout, results, output):
+ checkout = checkout.resolve(strict=True)
+ expected = context()
+ actual_sha = subprocess.check_output(
+ ["git", "-C", str(checkout), "rev-parse", "HEAD"], text=True
+ ).strip()
+ if actual_sha != expected["sha"]:
+ raise ValueError("checkout is not the event commit")
+ output.mkdir(parents=True, exist_ok=False)
+ (output / "sarif").mkdir()
+ used = 0
+ for language in LANGUAGES:
+ source = results / f"{language}.sarif"
+ if source.is_symlink() or source.stat().st_size > MAX_FILE:
+ raise ValueError("invalid SARIF input")
+ data = json.loads(source.read_text())
+ validate_sarif(data)
+ used += source.stat().st_size
+ if used > MAX_BUNDLE:
+ raise ValueError("bundle exceeds limit")
+ destination = output / "sarif" / source.name
+ shutil.copyfile(source, destination)
+ destination.chmod(0o644)
+ files = {
+ path.relative_to(output).as_posix(): {
+ "sha256": digest(path),
+ "size": path.stat().st_size,
+ }
+ for path in sorted(output.rglob("*"))
+ if path.is_file()
+ }
+ manifest = {
+ "version": 1,
+ "context": expected,
+ "codeql_version": CODEQL_VERSION,
+ "categories": LANGUAGES,
+ "files": files,
+ }
+ (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
+ verify_bundle(output, expected)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--checkout", type=Path, required=True)
+ parser.add_argument("--results", type=Path, required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ pack_bundle(args.checkout, args.results, args.output)
diff --git ml-explore/mlx/.github/scripts/codeql_artifacts_test.py Layr-Labs/mlx/.github/scripts/codeql_artifacts_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..dae67fdb562a158678506c9eb45b38ffa8c5768c
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/codeql_artifacts_test.py
@@ -0,0 +1,194 @@
+import copy
+import importlib.util
+import json
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+SPEC = importlib.util.spec_from_file_location(
+ "bundle", Path(__file__).with_name("codeql_artifacts.py")
+)
+bundle = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(bundle)
+
+
+class DataBoundaryTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ self.expected = {
+ "repository": "Layr-Labs/mlx",
+ "sha": "a" * 40,
+ "ref": "refs/pull/42/merge",
+ "run_id": "7",
+ "attempt": "1",
+ }
+ (self.root / "sarif").mkdir()
+ for language in bundle.LANGUAGES:
+ data = {
+ "version": "2.1.0",
+ "runs": [
+ {
+ "tool": {
+ "driver": {
+ "name": "CodeQL",
+ "semanticVersion": "2.27.4",
+ "rules": [{"id": "example"}],
+ }
+ },
+ "results": [],
+ }
+ ],
+ }
+ (self.root / f"sarif/{language}.sarif").write_text(json.dumps(data))
+ self.manifest = {
+ "version": 1,
+ "context": self.expected,
+ "codeql_version": "2.27.4",
+ "categories": bundle.LANGUAGES,
+ }
+ self.seal()
+
+ def seal(self):
+ self.manifest["files"] = {
+ p.relative_to(self.root).as_posix(): {
+ "sha256": bundle.digest(p),
+ "size": p.stat().st_size,
+ }
+ for p in self.root.rglob("*")
+ if p.is_file() and p.name != "manifest.json"
+ }
+ (self.root / "manifest.json").write_text(json.dumps(self.manifest))
+
+ def test_valid_bundle_and_fork_merge_attribution(self):
+ self.assertEqual(
+ bundle.verify_bundle(self.root, self.expected),
+ self.root.resolve() / "empty-checkout",
+ )
+
+ def test_every_context_dimension_is_bound(self):
+ for key in self.expected:
+ changed = copy.deepcopy(self.expected)
+ changed[key] += "-different"
+ with self.subTest(key=key), self.assertRaises(ValueError):
+ bundle.verify_bundle(self.root, changed)
+
+ def test_content_changes_are_rejected(self):
+ (self.root / "sarif/actions.sarif").write_text("altered content\n")
+ with self.assertRaises(ValueError):
+ bundle.verify_bundle(self.root, self.expected)
+
+ def test_missing_language_is_rejected(self):
+ (self.root / "sarif/python.sarif").unlink()
+ self.seal()
+ with self.assertRaises(ValueError):
+ bundle.verify_bundle(self.root, self.expected)
+
+ def test_extra_files_and_incorrect_inventory_are_rejected(self):
+ (self.root / "unexpected.sh").write_text("exit 0\n")
+ with self.assertRaises(ValueError):
+ bundle.verify_bundle(self.root, self.expected)
+ self.seal()
+ with self.assertRaises(ValueError):
+ bundle.verify_bundle(self.root, self.expected)
+
+ def test_source_symlinks_are_rejected(self):
+ (self.root / "link").symlink_to("/etc/passwd")
+ with self.assertRaisesRegex(ValueError, "symlink"):
+ bundle.verify_bundle(self.root, self.expected)
+
+ def test_ruleless_or_malformed_sarif_is_rejected(self):
+ p = self.root / "sarif/actions.sarif"
+ p.write_text(
+ json.dumps(
+ {"version": "2.1.0", "runs": [{"tool": {"driver": {"rules": []}}}]}
+ )
+ )
+ self.seal()
+ with self.assertRaisesRegex(ValueError, "no rules"):
+ bundle.verify_bundle(self.root, self.expected)
+
+ def test_bounds_are_enforced(self):
+ with patch.object(bundle, "MAX_BUNDLE", 1), self.assertRaises(ValueError):
+ bundle.verify_bundle(self.root, self.expected)
+ with patch.object(bundle, "MAX_FILE", 1), self.assertRaises(ValueError):
+ bundle.verify_bundle(self.root, self.expected)
+
+ def test_traversal_git_and_ambiguous_paths_are_rejected(self):
+ for path in (
+ "../private",
+ "/tmp/private",
+ "source/../private",
+ "source/.git/config",
+ "a\\b",
+ "a//b",
+ ):
+ with self.subTest(path=path), self.assertRaises(ValueError):
+ bundle.relative_path(path)
+
+ def test_primary_locations_and_fingerprints_are_required(self):
+ primary = {
+ "artifactLocation": {"uri": "mlx/ops.cpp"},
+ "region": {"startLine": 12},
+ }
+ result = {
+ "locations": [{"physicalLocation": primary}],
+ "partialFingerprints": {"primaryLocationLineHash": "ab12:1"},
+ }
+ data = {
+ "version": "2.1.0",
+ "runs": [
+ {
+ "tool": {
+ "driver": {
+ "name": "CodeQL",
+ "semanticVersion": "2.27.4",
+ "rules": [{"id": "rule"}],
+ }
+ },
+ "results": [result],
+ }
+ ],
+ }
+ bundle.validate_sarif(data)
+ del result["partialFingerprints"]
+ with self.assertRaisesRegex(ValueError, "fingerprint"):
+ bundle.validate_sarif(data)
+ primary["artifactLocation"]["uri"] = "../private"
+ with self.assertRaises(ValueError):
+ bundle.validate_sarif(data)
+
+ def test_different_tool_version_is_rejected(self):
+ p = self.root / "sarif/cpp.sarif"
+ data = json.loads(p.read_text())
+ data["runs"][0]["tool"]["driver"]["semanticVersion"] = "different"
+ p.write_text(json.dumps(data))
+ self.seal()
+ with self.assertRaisesRegex(ValueError, "CodeQL version"):
+ bundle.verify_bundle(self.root, self.expected)
+
+ def test_publisher_embeds_the_exact_tested_validator(self):
+ source = (
+ Path(bundle.__file__)
+ .read_text()
+ .split("# BEGIN DATA VALIDATOR\n", 1)[1]
+ .split("# END DATA VALIDATOR", 1)[0]
+ )
+ workflow = (
+ Path(__file__)
+ .parents[1]
+ .joinpath("workflows/codeql-native.yml")
+ .read_text()
+ )
+ # YAML removes this common indentation before the shell sees the program.
+ embedded = "\n".join(
+ line[10:] if line.startswith(" ") else line
+ for line in workflow.splitlines()
+ )
+ self.assertIn(source.strip(), embedded)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git ml-explore/mlx/.github/scripts/fedora-proot/fedora_proot.py Layr-Labs/mlx/.github/scripts/fedora-proot/fedora_proot.py
new file mode 100755
index 0000000000000000000000000000000000000000..4a47bad41ceda86f42bbf715df5d2ad200a1b37f
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/fedora-proot/fedora_proot.py
@@ -0,0 +1,475 @@
+#!/usr/bin/env python3
+"""Run MLX's Fedora 42 C++ build test in Fedora userspace on a Darkbloom ARM64 runner.
+
+The sandbox has no Docker, so the unchanged Fedora build script
+(.github/scripts/setup+build-cpp-linux-fedora-container.sh) runs under PRoot, built here
+from pinned source, in the official archived Fedora 42 container rootfs. PRoot
+translates paths and fakes UID 0 through ptrace; it is not an isolation boundary (the
+job VM is).
+"""
+
+import argparse
+import hashlib
+import http.client
+import json
+import os
+import platform
+import shutil
+import subprocess
+import tarfile
+import time
+import urllib.request
+from pathlib import Path, PurePosixPath
+
+PTRACE_PROBE = r"""
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/prctl.h>
+#include <sys/ptrace.h>
+#include <sys/wait.h>
+#include <unistd.h>
+int main(void) {
+ if (getuid() != 1000 || geteuid() != 1000 || prctl(PR_GET_NO_NEW_PRIVS,0,0,0,0) != 1)
+ return 10;
+ printf("PTRACE_PROBE uid=%lu dumpable=%d no_new_privs=1\n",
+ (unsigned long)getuid(), prctl(PR_GET_DUMPABLE));
+ fflush(stdout);
+ pid_t child = fork();
+ if (child < 0) { perror("fork"); return 11; }
+ if (!child) {
+ if (ptrace(PTRACE_TRACEME,0,0,0)) { perror("PTRACE_TRACEME"); _exit(12); }
+ raise(SIGSTOP); _exit(0);
+ }
+ int status;
+ if (waitpid(child,&status,0) != child || !WIFSTOPPED(status)) return 13;
+ if (ptrace(PTRACE_CONT,child,0,0)) { perror("PTRACE_CONT"); return 14; }
+ if (waitpid(child,&status,0) != child || !WIFEXITED(status) || WEXITSTATUS(status))
+ return 15;
+ puts("PTRACE_PROBE_OK"); return 0;
+}
+"""
+
+
+def load_pins():
+ return json.loads(Path(__file__).with_name("pins.json").read_text())
+
+
+def verified(path, spec):
+ if path.stat().st_size != spec["size"]:
+ raise ValueError(f"wrong size: {path.name}")
+ with path.open("rb") as src:
+ digest = hashlib.file_digest(src, "sha256").hexdigest()
+ if digest != spec["sha256"]:
+ raise ValueError(f"wrong SHA-256: {path.name}")
+
+
+OCI_GZIP_LAYER = "application/vnd.oci.image.layer.v1.tar+gzip"
+
+
+def oci_layer(archive, spec, target):
+ """Write the one pinned gzip layer of the pinned archived OCI image to target.
+
+ Only index.json, the pinned manifest and the pinned layer are read; the index
+ must name exactly that manifest, whose bytes must hash to its digest, and the
+ manifest must list exactly that one layer (media type, digest and size).
+ """
+ if target.exists():
+ verified(target, spec)
+ return
+ manifest_sha = spec["manifest"].removeprefix("sha256:")
+ part = target.with_name(target.name + ".part")
+ with tarfile.open(archive, "r:xz") as src:
+
+ def regular(name, limit):
+ member = src.getmember(name)
+ if not member.isfile() or member.size > limit:
+ raise ValueError(f"unexpected OCI member: {name}")
+ return member
+
+ index = json.loads(src.extractfile(regular("index.json", 1 << 16)).read())
+ manifests = index.get("manifests")
+ if (
+ not isinstance(manifests, list)
+ or len(manifests) != 1
+ or manifests[0].get("digest") != spec["manifest"]
+ ):
+ raise ValueError("OCI index must name exactly the pinned manifest")
+ raw = src.extractfile(regular("blobs/sha256/" + manifest_sha, 1 << 16)).read()
+ if hashlib.sha256(raw).hexdigest() != manifest_sha:
+ raise ValueError("OCI manifest does not match its digest")
+ layers = json.loads(raw).get("layers")
+ if (
+ not isinstance(layers, list)
+ or len(layers) != 1
+ or layers[0].get("mediaType") != OCI_GZIP_LAYER
+ or layers[0].get("digest") != "sha256:" + spec["sha256"]
+ or layers[0].get("size") != spec["size"]
+ ):
+ raise ValueError("OCI manifest must list exactly the pinned gzip layer")
+ with (
+ src.extractfile(
+ regular("blobs/sha256/" + spec["sha256"], spec["size"])
+ ) as data,
+ part.open("xb") as out,
+ ):
+ shutil.copyfileobj(data, out)
+ verified(part, spec)
+ part.rename(target)
+
+
+def patch_proot_faccessat2(src):
+ """Add faccessat2 (439) to PRoot 5.4.1's ARM64 syscall table before it is built.
+
+ The table stops at clone3, so PRoot passes faccessat2 to the kernel untranslated:
+ a guest `test -x` (bash uses faccessat2) would read the host's path, not the
+ guest's. enter.c and the seccomp filter already handle PR_faccessat2.
+ """
+ table = src / "syscall" / "sysnums-arm64.h"
+ text = table.read_text()
+ anchor = " [435] = PR_clone3,\n"
+ if text.count(anchor) != 1 or "PR_faccessat2" in text:
+ raise RuntimeError("unexpected PRoot ARM64 syscall table")
+ text = text.replace(anchor, anchor + " [439] = PR_faccessat2,\n")
+ table.write_text(text)
+ return hashlib.sha256(text.encode()).hexdigest()
+
+
+def verify_inputs(inputs, pins):
+ """Every pinned download, and the rootfs layer derived from the OCI archive."""
+ for name, spec in pins["files"].items():
+ verified(inputs / name, spec)
+ verified(inputs / "fedora.tar.gz", pins["fedora_layer"])
+
+
+def download(url, part, size, attempts=3, pause=5):
+ """One pinned download with bounded retries; any stale partial file goes first."""
+ for attempt in range(1, attempts + 1):
+ part.unlink(missing_ok=True)
+ try:
+ with urllib.request.urlopen(url, timeout=60) as src, part.open("xb") as out:
+ copied = 0
+ while chunk := src.read(1024 * 1024):
+ copied += len(chunk)
+ if copied > size:
+ raise ValueError(f"oversized download: {part.name}")
+ out.write(chunk)
+ if copied != size:
+ raise ValueError(
+ f"truncated download: {part.name} ({copied} of {size} bytes)"
+ )
+ return
+ except (OSError, ValueError, http.client.HTTPException) as error:
+ part.unlink(missing_ok=True)
+ if attempt == attempts:
+ raise
+ print(
+ f"FEDORA_PROOT_RETRY {part.name} attempt {attempt}: "
+ f"{type(error).__name__}: {error}",
+ flush=True,
+ )
+ time.sleep(pause * attempt)
+
+
+def fetch_inputs(dest, pins):
+ dest.mkdir(parents=True, exist_ok=True)
+ for name, spec in pins["files"].items():
+ target = dest / name
+ if not target.exists():
+ part = dest / (name + ".part")
+ download(spec["url"], part, spec["size"])
+ verified(part, spec)
+ part.rename(target)
+ verified(target, spec)
+ layer = pins["fedora_layer"]
+ oci_layer(dest / layer["archive"], layer, dest / "fedora.tar.gz")
+
+
+def extract_root(archive, dest):
+ """One pinned layer, no overlay merging; links are created after regular files.
+
+ This order prevents tar members writing through links, including absolute
+ rootfs links. Device nodes are unnecessary: /dev is an explicit PRoot bind.
+ All real ownership remains the calling runner; setuid/setgid bits are dropped.
+ """
+ dest.mkdir()
+ dest = dest.resolve()
+ seen = set()
+ links = []
+ with tarfile.open(archive, "r:*") as src:
+ for member in src:
+ p = PurePosixPath(member.name)
+ if p.is_absolute() or ".." in p.parts or not p.parts:
+ raise ValueError(f"unsafe tar path: {member.name}")
+ if any(part.startswith(".wh.") for part in p.parts):
+ raise ValueError("overlay whiteouts require a different unpacker")
+ key = str(p)
+ if key == ".":
+ continue
+ if key in seen:
+ raise ValueError(f"duplicate tar path: {key}")
+ seen.add(key)
+ target = dest.joinpath(*p.parts)
+ if member.isdir():
+ target.mkdir(parents=True, exist_ok=True)
+ elif member.isfile():
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with src.extractfile(member) as source, target.open("xb") as out:
+ shutil.copyfileobj(source, out)
+ target.chmod(member.mode & 0o777)
+ elif member.issym() or member.islnk():
+ links.append((member, target))
+ elif not (member.ischr() or member.isblk() or member.isfifo()):
+ raise ValueError(f"unsupported tar entry: {key}")
+ # Hardlinks must name an already extracted regular file, never a symlink.
+ for member, target in links:
+ if not member.islnk():
+ continue
+ link = PurePosixPath(member.linkname)
+ source = dest.joinpath(*link.parts)
+ if link.is_absolute() or ".." in link.parts or not source.is_file():
+ raise ValueError(f"unsafe hardlink: {member.name}")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ os.link(source, target)
+ for member, target in links:
+ if member.issym():
+ if not target.parent.resolve().is_relative_to(dest):
+ raise ValueError(f"symlink parent escapes root: {member.name}")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.symlink_to(member.linkname)
+
+
+def archived_repos(root):
+ root = root.resolve(strict=True)
+ repo_dir = root / "etc/yum.repos.d"
+ target = repo_dir / "pilot-fedora42.repo"
+ if root.stat().st_uid != os.geteuid():
+ raise ValueError("rootfs is not owned by this job user")
+ for path in (repo_dir, target):
+ if not path.resolve().is_relative_to(root):
+ raise ValueError("repository configuration escapes the owned rootfs")
+ repo_dir.mkdir(parents=True, exist_ok=True)
+ for repo in repo_dir.glob("*.repo"):
+ repo.rename(repo.with_suffix(".repo.disabled-pilot"))
+ key = "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-42-primary"
+ text = ""
+ for name, suffix in (
+ ("fedora", "releases/42/Everything/aarch64/os"),
+ ("updates", "updates/42/Everything/aarch64"),
+ ):
+ text += (
+ f"[{name}]\nname=Fedora 42 archived {name}\n"
+ f"baseurl=https://archives.fedoraproject.org/pub/archive/fedora/linux/{suffix}/\n"
+ f"enabled=1\ngpgcheck=1\ngpgkey={key}\n\n"
+ )
+ target.write_text(text)
+
+
+SCRIPT = ".github/scripts/setup+build-cpp-linux-fedora-container.sh"
+
+
+def run_pilot(work, source, pins):
+ if platform.system() != "Linux" or platform.machine() != "aarch64":
+ raise RuntimeError("run only on a Linux ARM64 runner")
+ if os.getuid() != 1000 or os.geteuid() != 1000:
+ raise RuntimeError("run as the unchanged UID1000 job user")
+ status = Path("/proc/self/status").read_text()
+ if "NoNewPrivs:\t1" not in status:
+ raise RuntimeError("the job must inherit no_new_privs")
+ work.mkdir(parents=True, exist_ok=False)
+ start = time.monotonic()
+ evidence = {
+ "pins": pins,
+ "host_arch": platform.machine(),
+ "uid": os.getuid(),
+ "kernel": platform.release(),
+ "steps": [],
+ "result": "running",
+ }
+
+ def call(name, args, *, cwd=work, env=None, timeout=180):
+ before = time.monotonic()
+ print(f"FEDORA_PROOT_STEP {name}", flush=True)
+ with (work / (name + ".log")).open("w") as log:
+ proc = subprocess.Popen(
+ args,
+ cwd=cwd,
+ env=env,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ try:
+ proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ import signal
+
+ os.killpg(proc.pid, signal.SIGKILL)
+ proc.wait()
+ evidence["steps"].append(
+ {
+ "name": name,
+ "seconds": time.monotonic() - before,
+ "exit": "timeout",
+ }
+ )
+ print(
+ (work / (name + ".log")).read_text(errors="replace"),
+ end="",
+ flush=True,
+ )
+ raise
+ duration = time.monotonic() - before
+ evidence["steps"].append(
+ {"name": name, "seconds": duration, "exit": proc.returncode}
+ )
+ print((work / (name + ".log")).read_text(errors="replace"), end="", flush=True)
+ if proc.returncode:
+ raise subprocess.CalledProcessError(proc.returncode, args)
+
+ try:
+ script = (source / SCRIPT).resolve(strict=True)
+ if not script.is_file() or not script.is_relative_to(source):
+ raise RuntimeError("the checked-out Fedora build script is missing")
+ inputs = work / "inputs"
+ fetch_inputs(inputs, pins)
+ verify_inputs(inputs, pins)
+ (work / "ptrace.c").write_text(PTRACE_PROBE)
+ call(
+ "ptrace-build",
+ ["cc", "-O2", "-Wall", "-Wextra", "-Werror", "ptrace.c", "-o", "ptrace"],
+ )
+ call("ptrace", [str(work / "ptrace")], timeout=15)
+ deps = work / "deps"
+ for deb in (
+ "libtalloc-dev.deb",
+ "libtalloc2.deb",
+ "pkgconf-bin.deb",
+ "libpkgconf3.deb",
+ ):
+ call(deb, ["dpkg-deb", "--extract", str(inputs / deb), str(deps)])
+ (deps / "usr/bin/pkg-config").symlink_to("pkgconf")
+ extract_root(inputs / "proot.tar.gz", work / "proot-source")
+ proot_src = work / "proot-source" / ("proot-" + pins["proot_commit"]) / "src"
+ evidence["proot_arm64_table_sha256"] = patch_proot_faccessat2(proot_src)
+ lib = deps / "usr/lib/aarch64-linux-gnu"
+ env = dict(
+ os.environ,
+ PKG_CONFIG_LIBDIR=str(lib / "pkgconfig"),
+ PKG_CONFIG_SYSROOT_DIR=str(deps),
+ LDFLAGS=f"-Wl,-rpath,{lib}",
+ PATH=f"{deps / 'usr/bin'}:{os.environ['PATH']}",
+ LD_LIBRARY_PATH=str(lib),
+ )
+ call(
+ "proot-build",
+ ["make", "-j2", "HAS_SWIG=", "HAS_PYTHON_CONFIG=", "proot"],
+ cwd=proot_src,
+ env=env,
+ )
+ proot = proot_src / "proot"
+ call("proot-version", [str(proot), "--version"])
+ with proot.open("rb") as src:
+ evidence["proot_sha256"] = hashlib.file_digest(src, "sha256").hexdigest()
+ extract_root(inputs / "fedora.tar.gz", work / "fedora")
+ root = work / "fedora"
+ if "VERSION_ID=42" not in (root / "etc/os-release").read_text():
+ raise RuntimeError("rootfs is not Fedora42")
+ archived_repos(root)
+ scratch = work / "tmp"
+ scratch.mkdir()
+ command = [
+ str(proot),
+ "-0",
+ "-r",
+ str(root),
+ "-b",
+ "/dev",
+ "-b",
+ "/proc",
+ "-b",
+ f"{scratch}:/tmp",
+ "-b",
+ f"{source}:/work",
+ "-w",
+ "/work",
+ ]
+ # The checkout belongs to the runner's UID 1000; git in the fake-root guest
+ # must accept it.
+ guest = dict(
+ os.environ,
+ GIT_CONFIG_COUNT="1",
+ GIT_CONFIG_KEY_0="safe.directory",
+ GIT_CONFIG_VALUE_0="/work",
+ )
+ # No sudo, no Docker, no namespaces/capabilities, no host /etc or /run bind.
+ call(
+ "fedora-smoke",
+ command
+ + [
+ "/bin/bash",
+ "-ec",
+ "cat /etc/fedora-release; test $(uname -m) = aarch64; "
+ # faccessat2 translation: Fedora has dnf and no apt-get; the Ubuntu host
+ # has apt-get.
+ "test -x /usr/bin/dnf; test ! -x /usr/bin/apt-get; "
+ "test $(id -u) = 0; ldd --version; dnf --version; "
+ "grep '^NoNewPrivs:' /proc/self/status; (true)& wait",
+ ],
+ env=guest,
+ timeout=60,
+ )
+ # Exercise actual DNS/proxy/TLS and both literal archive repositories
+ # before the expensive build, using Fedora's own libcurl/trust store.
+ call(
+ "fedora-archive-network",
+ command + ["/usr/bin/dnf", "-q", "makecache", "--refresh"],
+ env=guest,
+ timeout=300,
+ )
+ call(
+ "fedora-build-test",
+ command + ["/bin/bash", "/work/" + SCRIPT],
+ env=guest,
+ timeout=1800,
+ )
+ evidence["result"] = "pass"
+ except BaseException as error:
+ evidence["result"] = "failure"
+ evidence["error_type"] = type(error).__name__
+ raise
+ finally:
+ evidence["seconds"] = time.monotonic() - start
+ (work / "evidence.json").write_text(json.dumps(evidence, indent=2) + "\n")
+ print(
+ json.dumps({k: v for k, v in evidence.items() if k != "pins"}, indent=2),
+ flush=True,
+ )
+ print("FEDORA_PROOT_EVIDENCE " + str(work / "evidence.json"), flush=True)
+ print("FEDORA_PROOT_OK " + evidence["result"], flush=True)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("action", choices=("fetch", "run"))
+ parser.add_argument(
+ "--inputs", type=Path, help="fetch: download and verify the pinned inputs here"
+ )
+ parser.add_argument(
+ "--source", type=Path, help="run: the MLX checkout to build and test"
+ )
+ parser.add_argument("--work", type=Path, help="run: a new private work directory")
+ args = parser.parse_args()
+ pins = load_pins()
+ if args.action == "fetch":
+ if args.inputs is None:
+ parser.error("fetch requires --inputs")
+ fetch_inputs(args.inputs.resolve(), pins)
+ else:
+ if args.source is None or args.work is None:
+ parser.error("run requires --source and --work")
+ run_pilot(args.work.resolve(), args.source.resolve(strict=True), pins)
+
+
+if __name__ == "__main__":
+ main()
diff --git ml-explore/mlx/.github/scripts/fedora-proot/pins.json Layr-Labs/mlx/.github/scripts/fedora-proot/pins.json
new file mode 100644
index 0000000000000000000000000000000000000000..34fb962429b092b9ba196b5fb32e9c416416f7a0
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/fedora-proot/pins.json
@@ -0,0 +1,43 @@
+{
+ "schema": 1,
+ "proot_commit": "d4b49e2243dee34e41c13dfeca6a3d07e9cf0f00",
+ "fedora_manifest": "sha256:cf9e82fbfad546ad06c626dabe8ba1aac6100ecfde4339e521352e9b77eaa794",
+ "files": {
+ "fedora.oci.tar.xz": {
+ "url": "https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/42/Container/aarch64/images/Fedora-Container-Base-Generic-42-1.1.aarch64.oci.tar.xz",
+ "size": 57715532,
+ "sha256": "137a907cd0931d9c4c7cfd5467031e03da3715141f24c39078c7b7f76c809038"
+ },
+ "proot.tar.gz": {
+ "url": "https://codeload.github.com/proot-me/proot/tar.gz/d4b49e2243dee34e41c13dfeca6a3d07e9cf0f00",
+ "size": 234642,
+ "sha256": "25ffd8f31f32a0edd644da770008d8b8ee99197da03dc80cd20226b3012b7d26"
+ },
+ "libtalloc-dev.deb": {
+ "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/t/talloc/libtalloc-dev_2.4.2-1build2_arm64.deb",
+ "size": 62224,
+ "sha256": "d63fc770129092ba8c40d44db4e2d740f645d5291ea6a9bf9b61d7e5294dcf5c"
+ },
+ "libtalloc2.deb": {
+ "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/t/talloc/libtalloc2_2.4.2-1build2_arm64.deb",
+ "size": 26748,
+ "sha256": "4b182e41db5537937a423fc8f9593c65330553442eba17e058c4cc1c7a73a382"
+ },
+ "pkgconf-bin.deb": {
+ "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/p/pkgconf/pkgconf-bin_1.8.1-2build1_arm64.deb",
+ "size": 20458,
+ "sha256": "bcd0d24c48b8b73ed7ba20ffc21a3575d5d9bdd53c3cee5a8051b7bde5fbf638"
+ },
+ "libpkgconf3.deb": {
+ "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/p/pkgconf/libpkgconf3_1.8.1-2build1_arm64.deb",
+ "size": 31226,
+ "sha256": "f476cb81e1ecec6bf974f21181469cf5edcc749c4ead621469cdbf584dfd3be8"
+ }
+ },
+ "fedora_layer": {
+ "archive": "fedora.oci.tar.xz",
+ "manifest": "sha256:cf9e82fbfad546ad06c626dabe8ba1aac6100ecfde4339e521352e9b77eaa794",
+ "sha256": "cfc0be9fb5518ec8eb4521cdb4dc2ee14df42924e0f468d24a8e6cfbdda5fdc9",
+ "size": 58468983
+ }
+}
diff --git ml-explore/mlx/.github/scripts/fedora-proot/test_fedora_proot.py Layr-Labs/mlx/.github/scripts/fedora-proot/test_fedora_proot.py
new file mode 100644
index 0000000000000000000000000000000000000000..7656bba1447e8602276f461926fa049dd7fb8574
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/fedora-proot/test_fedora_proot.py
@@ -0,0 +1,410 @@
+import hashlib
+import importlib.util
+import io
+import json
+import tarfile
+import tempfile
+import unittest
+import unittest.mock
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+SPEC = importlib.util.spec_from_file_location("pilot", HERE / "fedora_proot.py")
+pilot = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(pilot)
+
+
+class InputValidation(unittest.TestCase):
+ def test_size_and_digest_must_both_match(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ p = Path(tmp) / "input"
+ p.write_bytes(b"approved")
+ spec = {"size": 8, "sha256": hashlib.sha256(b"approved").hexdigest()}
+ pilot.verified(p, spec)
+ p.write_bytes(b"replaced")
+ with self.assertRaisesRegex(ValueError, "SHA-256"):
+ pilot.verified(p, spec)
+ p.write_bytes(b"short")
+ with self.assertRaisesRegex(ValueError, "size"):
+ pilot.verified(p, spec)
+
+ def extract(self, entries, tmp):
+ archive = Path(tmp) / "layer.tar"
+ with tarfile.open(archive, "w") as tar:
+ for name, typ, content in entries:
+ info = tarfile.TarInfo(name)
+ info.type = typ
+ if typ == tarfile.REGTYPE:
+ info.size = len(content)
+ info.mode = 0o6755
+ tar.addfile(info, io.BytesIO(content))
+ else:
+ info.linkname = content
+ tar.addfile(info)
+ root = Path(tmp) / "root"
+ pilot.extract_root(archive, root)
+ return root
+
+ def test_absolute_rootfs_symlink_is_created_last(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = self.extract(
+ [
+ ("lib", tarfile.SYMTYPE, "/usr/lib"),
+ ("usr/lib/tool", tarfile.REGTYPE, b"tool"),
+ ],
+ tmp,
+ )
+ self.assertEqual((root / "lib").readlink(), Path("/usr/lib"))
+ self.assertEqual((root / "usr/lib/tool").read_bytes(), b"tool")
+ self.assertEqual((root / "usr/lib/tool").stat().st_mode & 0o6000, 0)
+
+ def test_bad_paths_and_overlay_layers_are_refused(self):
+ for name in ("/outside", "../outside", "usr/../../outside", "usr/.wh.hidden"):
+ with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
+ with self.assertRaises(ValueError):
+ self.extract([(name, tarfile.REGTYPE, b"bad")], tmp)
+
+ def test_symlink_cannot_redirect_another_symlink_outside(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ with self.assertRaisesRegex(ValueError, "parent escapes"):
+ self.extract(
+ [
+ ("escape", tarfile.SYMTYPE, tmp),
+ ("escape/other", tarfile.SYMTYPE, "/usr/lib"),
+ ],
+ tmp,
+ )
+ self.assertFalse((Path(tmp) / "other").exists())
+
+ def test_duplicate_and_escaping_hardlinks_are_refused(self):
+ cases = [
+ [("tool", tarfile.REGTYPE, b"x"), ("tool", tarfile.REGTYPE, b"y")],
+ [("tool", tarfile.LNKTYPE, "../../outside")],
+ ]
+ for entries in cases:
+ with tempfile.TemporaryDirectory() as tmp, self.assertRaises(ValueError):
+ self.extract(entries, tmp)
+
+ def test_archived_repos_keep_package_signature_checks(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ repo = root / "etc/yum.repos.d"
+ repo.mkdir(parents=True)
+ (repo / "mirror.repo").write_text("metalink=https://unbounded.example/\n")
+ pilot.archived_repos(root)
+ files = list(repo.glob("*.repo"))
+ self.assertEqual(len(files), 1)
+ text = files[0].read_text()
+ self.assertEqual(text.count("gpgcheck=1"), 2)
+ self.assertNotIn("metalink", text)
+ self.assertEqual(text.count("https://archives.fedoraproject.org/"), 2)
+
+ def test_repository_writes_cannot_follow_rootfs_links_outside(self):
+ for escape_file in (False, True):
+ with (
+ self.subTest(escape_file=escape_file),
+ tempfile.TemporaryDirectory() as tmp,
+ ):
+ root = Path(tmp) / "root"
+ outside = Path(tmp) / "outside"
+ root.mkdir()
+ outside.mkdir()
+ (root / "etc").mkdir()
+ if escape_file:
+ (root / "etc/yum.repos.d").mkdir()
+ (root / "etc/yum.repos.d/pilot-fedora42.repo").symlink_to(
+ outside / "target"
+ )
+ else:
+ (root / "etc/yum.repos.d").symlink_to(outside)
+ with self.assertRaisesRegex(ValueError, "escapes"):
+ pilot.archived_repos(root)
+ self.assertEqual(list(outside.iterdir()), [])
+
+
+class OciLayer(unittest.TestCase):
+ """The archived Fedora OCI image: only its one pinned gzip layer, by digest."""
+
+ LAYER = "application/vnd.oci.image.layer.v1.tar+gzip"
+
+ def build(self, tmp, layers=1, manifests=1, media=None, tamper_manifest=False):
+ layer = b"layer-bytes-" * 100
+ digest = hashlib.sha256(layer).hexdigest()
+ entries = [
+ {
+ "mediaType": media or self.LAYER,
+ "digest": "sha256:" + digest,
+ "size": len(layer),
+ }
+ ] * layers
+ manifest = json.dumps({"schemaVersion": 2, "layers": entries}).encode()
+ mdigest = hashlib.sha256(manifest).hexdigest()
+ stored = manifest + (b" " if tamper_manifest else b"")
+ index = json.dumps(
+ {
+ "schemaVersion": 2,
+ "manifests": [{"digest": "sha256:" + mdigest}] * manifests,
+ }
+ ).encode()
+ archive = Path(tmp) / "fedora.oci.tar.xz"
+ with tarfile.open(archive, "w:xz") as tar:
+ for name, data in (
+ ("index.json", index),
+ ("blobs/sha256/" + mdigest, stored),
+ ("blobs/sha256/" + digest, layer),
+ ):
+ info = tarfile.TarInfo(name)
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ spec = {
+ "archive": "fedora.oci.tar.xz",
+ "manifest": "sha256:" + mdigest,
+ "sha256": digest,
+ "size": len(layer),
+ }
+ return archive, spec, layer
+
+ def test_pinned_layer_is_extracted_and_verified(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ archive, spec, layer = self.build(tmp)
+ target = Path(tmp) / "fedora.tar.gz"
+ pilot.oci_layer(archive, spec, target)
+ self.assertEqual(target.read_bytes(), layer)
+ pilot.oci_layer(archive, spec, target) # an existing verified layer is kept
+
+ def test_other_manifest_layers_or_media_are_refused(self):
+ cases = [
+ dict(layers=2),
+ dict(manifests=2),
+ dict(media="application/vnd.oci.image.layer.v1.tar"),
+ dict(tamper_manifest=True),
+ ]
+ for case in cases:
+ with tempfile.TemporaryDirectory() as tmp:
+ archive, spec, _ = self.build(tmp, **case)
+ with self.assertRaises(ValueError):
+ pilot.oci_layer(archive, spec, Path(tmp) / "fedora.tar.gz")
+ self.assertFalse((Path(tmp) / "fedora.tar.gz").exists())
+
+ def test_pins_must_name_the_manifest_and_layer(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ archive, spec, _ = self.build(tmp)
+ for change in (
+ {"manifest": "sha256:" + "0" * 64},
+ {"sha256": "0" * 64},
+ {"size": spec["size"] - 1},
+ ):
+ with self.assertRaises(ValueError):
+ pilot.oci_layer(
+ archive, dict(spec, **change), Path(tmp) / "fedora.tar.gz"
+ )
+ self.assertFalse((Path(tmp) / "fedora.tar.gz").exists())
+
+ def rebuild(self, tmp, archive, replace):
+ """Copy archive, replacing members by name: (TarInfo, bytes or None)."""
+ out = Path(tmp) / "hostile.oci.tar.xz"
+ with tarfile.open(archive, "r:xz") as src, tarfile.open(out, "w:xz") as dst:
+ for member in src:
+ if member.name in replace:
+ info, data = replace[member.name]
+ dst.addfile(info, io.BytesIO(data) if data is not None else None)
+ else:
+ dst.addfile(member, src.extractfile(member))
+ return out
+
+ def test_non_regular_or_oversized_members_are_refused(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ archive, spec, _ = self.build(tmp)
+ link = tarfile.TarInfo("blobs/sha256/" + spec["sha256"])
+ link.type = tarfile.SYMTYPE
+ link.linkname = "index.json"
+ big = json.dumps(
+ {"manifests": [{"digest": spec["manifest"]}], "pad": "x" * (1 << 16)}
+ ).encode()
+ index = tarfile.TarInfo("index.json")
+ index.size = len(big)
+ for replace in ({link.name: (link, None)}, {"index.json": (index, big)}):
+ hostile = self.rebuild(tmp, archive, replace)
+ with self.assertRaisesRegex(ValueError, "unexpected OCI member"):
+ pilot.oci_layer(hostile, spec, Path(tmp) / "fedora.tar.gz")
+ self.assertFalse((Path(tmp) / "fedora.tar.gz").exists())
+
+ def test_existing_target_must_be_the_pinned_layer(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ archive, spec, _ = self.build(tmp)
+ target = Path(tmp) / "fedora.tar.gz"
+ target.write_bytes(b"not the layer")
+ with self.assertRaises(ValueError):
+ pilot.oci_layer(archive, spec, target)
+
+ def test_fetch_inputs_derives_the_layer_and_verify_inputs_checks_it(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ archive, spec, layer = self.build(tmp)
+ raw = archive.read_bytes()
+ pins = {
+ "files": {
+ "fedora.oci.tar.xz": {
+ "url": "https://unused.invalid/",
+ "size": len(raw),
+ "sha256": hashlib.sha256(raw).hexdigest(),
+ }
+ },
+ "fedora_layer": spec,
+ }
+ dest = Path(tmp) / "inputs"
+ dest.mkdir()
+ (dest / "fedora.oci.tar.xz").write_bytes(raw)
+ pilot.fetch_inputs(dest, pins) # present and verified: no download
+ self.assertEqual((dest / "fedora.tar.gz").read_bytes(), layer)
+ pilot.verify_inputs(dest, pins)
+ (dest / "fedora.tar.gz").write_bytes(b"x" * len(layer))
+ with self.assertRaisesRegex(ValueError, "SHA-256"):
+ pilot.verify_inputs(dest, pins)
+
+ def test_rootfs_comes_from_the_archived_oci_image(self):
+ pins = json.loads((HERE / "pins.json").read_text())
+ layer = pins["fedora_layer"]
+ self.assertNotIn("fedora.tar.gz", pins["files"])
+ source = pins["files"][layer["archive"]]
+ self.assertTrue(
+ source["url"].startswith(
+ "https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/42/Container/aarch64/images/"
+ )
+ )
+ self.assertEqual(pins["fedora_manifest"], layer["manifest"])
+ self.assertEqual(len(layer["sha256"]), 64)
+ self.assertGreater(layer["size"], 0)
+
+
+class ProotFaccessat2(unittest.TestCase):
+ """PRoot 5.4.1's ARM64 table lacks faccessat2 (439).
+
+ Guest access checks would otherwise read host paths.
+ """
+
+ TABLE = (
+ "static const Sysnum sysnums_arm64[] = {\n"
+ " [291] = PR_statx,\n"
+ " [435] = PR_clone3,\n"
+ "};\n"
+ )
+
+ def table(self, tmp, text):
+ path = Path(tmp) / "syscall"
+ path.mkdir()
+ (path / "sysnums-arm64.h").write_text(text)
+ return Path(tmp)
+
+ def test_faccessat2_is_added_once_after_clone3(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ src = self.table(tmp, self.TABLE)
+ digest = pilot.patch_proot_faccessat2(src)
+ text = (src / "syscall/sysnums-arm64.h").read_text()
+ self.assertIn(" [435] = PR_clone3,\n [439] = PR_faccessat2,\n", text)
+ self.assertEqual(digest, hashlib.sha256(text.encode()).hexdigest())
+
+ def test_unexpected_tables_are_refused(self):
+ for text in (
+ self.TABLE.replace("[435] = PR_clone3,", ""),
+ self.TABLE + " [435] = PR_clone3,\n",
+ self.TABLE.replace("};", " [439] = PR_faccessat2,\n};"),
+ ):
+ with tempfile.TemporaryDirectory() as tmp:
+ with self.assertRaises(RuntimeError):
+ pilot.patch_proot_faccessat2(self.table(tmp, text))
+
+
+class Downloads(unittest.TestCase):
+ """Pinned downloads retry a bounded number of times; no partial file is kept."""
+
+ class Response(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def test_a_stale_partial_file_is_removed_before_the_first_attempt(self):
+ calls = []
+
+ def urlopen(url, timeout):
+ calls.append(url)
+ return self.Response(b"approved")
+
+ with (
+ tempfile.TemporaryDirectory() as tmp,
+ unittest.mock.patch.object(pilot.urllib.request, "urlopen", urlopen),
+ unittest.mock.patch.object(pilot.time, "sleep", lambda s: None),
+ ):
+ part = Path(tmp) / "input.part"
+ part.write_bytes(b"stale")
+ pilot.download("https://example.invalid/x", part, 8)
+ self.assertEqual(part.read_bytes(), b"approved")
+ # One attempt: the stale file was removed up front, not after a failure.
+ self.assertEqual(len(calls), 1)
+
+ def test_a_truncated_body_is_retried(self):
+ bodies = [b"appr", b"approved"]
+ with (
+ tempfile.TemporaryDirectory() as tmp,
+ unittest.mock.patch.object(
+ pilot.urllib.request,
+ "urlopen",
+ lambda url, timeout: self.Response(bodies.pop(0)),
+ ),
+ unittest.mock.patch.object(pilot.time, "sleep", lambda s: None),
+ ):
+ part = Path(tmp) / "input.part"
+ pilot.download("https://example.invalid/x", part, 8)
+ self.assertEqual(part.read_bytes(), b"approved")
+ self.assertEqual(bodies, [])
+
+ def test_a_failed_attempt_is_retried_after_removing_the_partial_file(self):
+ calls = []
+
+ def urlopen(url, timeout):
+ calls.append(url)
+ if len(calls) == 1:
+ raise OSError("Tunnel connection failed: 502 Bad Gateway")
+ return self.Response(b"approved")
+
+ with (
+ tempfile.TemporaryDirectory() as tmp,
+ unittest.mock.patch.object(pilot.urllib.request, "urlopen", urlopen),
+ unittest.mock.patch.object(pilot.time, "sleep", lambda s: None),
+ ):
+ part = Path(tmp) / "input.part"
+ part.write_bytes(b"stale")
+ pilot.download("https://example.invalid/x", part, 8)
+ self.assertEqual(part.read_bytes(), b"approved")
+ self.assertEqual(len(calls), 2)
+
+ def test_retries_are_bounded_and_oversized_bodies_refused(self):
+ calls = []
+
+ def urlopen(url, timeout):
+ calls.append(url)
+ return self.Response(b"x" * 9)
+
+ with (
+ tempfile.TemporaryDirectory() as tmp,
+ unittest.mock.patch.object(pilot.urllib.request, "urlopen", urlopen),
+ unittest.mock.patch.object(pilot.time, "sleep", lambda s: None),
+ ):
+ part = Path(tmp) / "input.part"
+ with self.assertRaisesRegex(ValueError, "oversized"):
+ pilot.download("https://example.invalid/x", part, 8, attempts=2)
+ self.assertFalse(part.exists())
+ self.assertEqual(len(calls), 2)
+
+ def test_pins_name_no_mlx_source_archive(self):
+ pins = json.loads((HERE / "pins.json").read_text())
+ self.assertNotIn("mlx.tar.gz", pins["files"])
+ self.assertFalse({"mlx_commit", "mlx_script", "mlx_script_sha256"} & set(pins))
+ for spec in pins["files"].values():
+ self.assertEqual(len(spec["sha256"]), 64)
+ self.assertTrue(spec["url"].startswith("https://"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git ml-explore/mlx/.github/scripts/find-eligible-contributors.js Layr-Labs/mlx/.github/scripts/find-eligible-contributors.js
deleted file mode 100644
index 296c8f2be69b06b1ef3b5177b624c9a93b1171c8..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/scripts/find-eligible-contributors.js
+++ /dev/null
@@ -1,232 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * find-eligible-contributors.js
- *
- * Finds users who have opened pull requests on a GitHub repo,
- * are NOT collaborators on that repo, and match:
- * - fewer than 5 currently open PRs
- * - more than 2 merged PRs
- * - merge rate (merged / closed) > 50%
- * - "low priority" PRs < 50%
- *
- * Usage:
- * GITHUB_TOKEN=xxxx node find-eligible-contributors.js <owner> <repo>
- */
-
-const GITHUB_API = 'https://api.github.com';
-
-function authHeaders(token) {
- return {
- Authorization: `Bearer ${token}`,
- Accept: 'application/vnd.github+json',
- 'X-GitHub-Api-Version': '2022-11-28',
- 'User-Agent': 'find-eligible-contributors-script',
- };
-}
-
-async function fetchAllPages(url, token, { stopWhen } = {}) {
- const results = [];
- let page = 1;
- const perPage = 100;
- const concurrentRequests = 5;
-
- while (true) {
- const responses = await Promise.all(
- Array.from({ length: concurrentRequests }, async (_, index) => {
- const pageUrl = new URL(url);
- pageUrl.searchParams.set('per_page', String(perPage));
- pageUrl.searchParams.set('page', String(page + index));
-
- const res = await fetch(pageUrl, { headers: authHeaders(token) });
- if (!res.ok) {
- const body = await res.text();
- throw new Error(`GitHub API error ${res.status} for ${pageUrl}: ${body}`);
- }
- return res.json();
- })
- );
-
- let end = false;
- for (const data of responses) {
- if (!Array.isArray(data) || data.length === 0) {
- end = true;
- continue;
- }
- if (data.length < perPage) {
- end = true;
- }
-
- for (const item of data) {
- if (stopWhen && stopWhen(item)) break;
- results.push(item);
- }
- }
-
- if (end) {
- break;
- }
-
- page += concurrentRequests;
- }
-
- return results;
-}
-
-async function fetchPullRequests(owner, repo, token) {
- const url = `${GITHUB_API}/repos/${owner}/${repo}/pulls?state=all&sort=created&direction=desc`;
-
- const oneYearAgo = new Date();
- oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
-
- return fetchAllPages(url, token, {
- stopWhen: (pr) => new Date(pr.created_at) < oneYearAgo,
- });
-}
-
-async function fetchCollaborators(owner, repo, token) {
- const url = `${GITHUB_API}/repos/${owner}/${repo}/collaborators`;
- const collaborators = await fetchAllPages(url, token);
- return new Set(collaborators.map((c) => c.login));
-}
-
-/**
- * Aggregate per-user PR stats from the list of PRs.
- * Returns Map<login, {
- * open: number,
- * closed: number,
- * merged: number,
- * total: number,
- * lowPriority: number,
- * mostRecentCreatedAt: Date
- * }>
- */
-function aggregateUserStats(pullRequests) {
- const stats = new Map();
-
- for (const pr of pullRequests) {
- const login = pr.user?.login;
- if (!login) continue;
-
- if (!stats.has(login)) {
- stats.set(login, {
- open: 0,
- closed: 0,
- merged: 0,
- total: 0,
- lowPriority: 0,
- mostRecentCreatedAt: null,
- });
- }
- const s = stats.get(login);
-
- s.total += 1;
- if (pr.labels?.some((label) => label.name === 'low priority')) {
- s.lowPriority += 1;
- }
-
- if (pr.state === 'open') {
- s.open += 1;
- } else if (pr.state === 'closed') {
- s.closed += 1;
- if (pr.merged_at) {
- s.merged += 1;
- }
- }
-
- const createdAt = new Date(pr.created_at);
- if (!s.mostRecentCreatedAt || createdAt > s.mostRecentCreatedAt) {
- s.mostRecentCreatedAt = createdAt;
- }
- }
-
- return stats;
-}
-
-/**
- * Apply eligibility filters:
- * - fewer than 5 currently open PRs
- * - more than 2 merged PRs
- * - merge rate (merged / closed) > 50%
- * - "low priority" PRs < 50%
- * - not a collaborator
- * - has an open PR or at least one PR within the past 6 weeks
- */
-function filterEligibleUsers(stats, collaboratorLogins) {
- const SIX_WEEKS_MS = 6 * 7 * 24 * 60 * 60 * 1000;
- const cutoff = new Date((new Date).getTime() - SIX_WEEKS_MS);
- const eligible = [];
-
- for (const [login, s] of stats.entries()) {
- if (s.open >= 5) continue;
- if (s.merged <= 2) continue;
- if (collaboratorLogins.has(login)) continue;
- if (s.open == 0 && s.mostRecentCreatedAt < cutoff) continue;
- if ((s.merged / s.closed) < 0.5) continue;
- if ((s.lowPriority / s.total) > 0.5) continue;
-
- eligible.push(login);
- }
- return eligible;
-}
-
-/**
- * Given a repo (owner/repo) and a GitHub token, returns the login names of
- * eligible external contributors matching all filters.
- *
- * @param {Object} params
- * @param {string} params.owner - Repo owner (user or org).
- * @param {string} params.repo - Repo name.
- * @param {string} params.token - GitHub token with repo read (and ideally push) access.
- * @returns {Promise<string[]>}
- */
-async function findEligibleContributors({ owner, repo, token } = {}) {
- if (!owner || !repo) {
- throw new Error('findEligibleContributors requires both "owner" and "repo".');
- }
- if (!token) {
- throw new Error('findEligibleContributors requires a "token".');
- }
-
- const [pullRequests, collaboratorLogins] = await Promise.all([
- fetchPullRequests(owner, repo, token),
- fetchCollaborators(owner, repo, token),
- ]);
-
- const stats = aggregateUserStats(pullRequests);
- return filterEligibleUsers(stats, collaboratorLogins);
-}
-
-// ---- CLI entry point ----
-
-function isRunAsCLI() {
- return import.meta.url === `file://${process.argv[1]}`;
-}
-
-async function runCLI() {
- const [, , owner, repo] = process.argv;
- if (!owner || !repo) {
- console.error('Usage: node find-eligible-contributors.js <owner> <repo>');
- process.exit(1);
- }
- const token = process.env.GITHUB_TOKEN;
- if (!token) {
- console.error('Error: set GITHUB_TOKEN environment variable with a valid GitHub token.');
- process.exit(1);
- }
-
- console.error(`Fetching pull requests and collaborators for ${owner}/${repo} in parallel...`);
- const eligibleLogins = await findEligibleContributors({ owner, repo, token });
-
- console.log(JSON.stringify(eligibleLogins, null, 2));
- console.error(`\n${eligibleLogins.length} user(s) match the criteria.`);
-}
-
-if (isRunAsCLI()) {
- runCLI().catch((err) => {
- console.error('Fatal error:', err);
- process.exit(1);
- });
-}
-
-export { findEligibleContributors };
diff --git ml-explore/mlx/.github/scripts/fork-tests/metal-cache/xcrun Layr-Labs/mlx/.github/scripts/fork-tests/metal-cache/xcrun
new file mode 100755
index 0000000000000000000000000000000000000000..5b7de48845032488017d64dbd3a60606bb7d6b05
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/fork-tests/metal-cache/xcrun
@@ -0,0 +1,94 @@
+#!/bin/bash
+# A cache for the Metal kernel build of fork-tests.yml.
+#
+# The build jobs put this folder first in PATH. The kernel rules in
+# mlx/backend/metal/kernels/CMakeLists.txt call "xcrun -sdk macosx metal"
+# to compile each .metal file to an .air file and to link the .air files to
+# mlx.metallib. This script gives those two calls a cache. It sends all other
+# calls to /usr/bin/xcrun without a change.
+#
+# The key of an .air file is the SHA-256 of the toolchain ID, the arguments
+# without "-o FILE", and the preprocessed source. The key of a .metallib file
+# is the SHA-256 of the toolchain ID and the arguments, with each .air input
+# replaced by the SHA-256 of its content.
+#
+# Environment:
+# MLX_METAL_CACHE_TOOLCHAIN the metal compiler version and the SDK build
+# MLX_METAL_CACHE_IN the folder with the restored entries
+# MLX_METAL_CACHE_OUT the folder that gets every entry that this
+# build uses; the job saves this folder
+# If one of them is not set, the script only calls /usr/bin/xcrun.
+set -euo pipefail
+
+real=/usr/bin/xcrun
+
+if [[ -z "${MLX_METAL_CACHE_TOOLCHAIN:-}" || -z "${MLX_METAL_CACHE_IN:-}" ||
+ -z "${MLX_METAL_CACHE_OUT:-}" || $# -lt 4 ||
+ "$1" != "-sdk" || "$2" != "macosx" || "$3" != "metal" ]]; then
+ exec "$real" "$@"
+fi
+
+out=""
+compile=0
+key_args=()
+pre_args=()
+args=("${@:4}")
+i=0
+while (( i < ${#args[@]} )); do
+ arg=${args[i]}
+ if [[ $arg == "-o" && $(( i + 1 )) -lt ${#args[@]} ]]; then
+ out=${args[i + 1]}
+ pre_args+=(-o -)
+ i=$(( i + 2 ))
+ continue
+ fi
+ if [[ $arg == "-c" ]]; then
+ compile=1
+ key_args+=(-c)
+ pre_args+=(-E)
+ elif [[ $arg == *.air && -f $arg ]]; then
+ key_args+=("air:$(shasum -a 256 < "$arg" | cut -d ' ' -f 1)")
+ pre_args+=("$arg")
+ else
+ key_args+=("$arg")
+ pre_args+=("$arg")
+ fi
+ i=$(( i + 1 ))
+done
+
+if [[ $compile == 1 && $out == *.air ]]; then
+ mode=compile
+elif [[ $compile == 0 && $out == *.metallib ]]; then
+ mode=link
+else
+ exec "$real" "$@"
+fi
+
+{
+ printf '%s\0' "$MLX_METAL_CACHE_TOOLCHAIN" "$mode" "${key_args[@]}"
+ if [[ $mode == compile ]]; then
+ # The toolchain mount folder has a random suffix on each runner, for
+ # example MetalToolchain-v17.6.109.0.oxYh3g. Remove it from the line
+ # markers, and keep the version.
+ "$real" -sdk macosx metal "${pre_args[@]}" 2>/dev/null |
+ sed -E 's#(MetalToolchain-v[0-9.]*[0-9])\.[A-Za-z0-9]+/#\1/#g'
+ fi
+} > "$out.key" || {
+ rm -f "$out.key"
+ exec "$real" "$@"
+}
+key=$(shasum -a 256 < "$out.key" | cut -d ' ' -f 1)
+rm -f "$out.key"
+
+mkdir -p "$MLX_METAL_CACHE_OUT"
+log="$MLX_METAL_CACHE_OUT.log"
+if [[ -f "$MLX_METAL_CACHE_IN/$key" ]]; then
+ cp "$MLX_METAL_CACHE_IN/$key" "$out"
+ echo "hit $mode $(basename "$out")" >> "$log"
+else
+ "$real" "$@"
+ echo "miss $mode $(basename "$out")" >> "$log"
+fi
+tmp="$MLX_METAL_CACHE_OUT/$key.$$"
+cp "$out" "$tmp"
+mv "$tmp" "$MLX_METAL_CACHE_OUT/$key"
diff --git ml-explore/mlx/.github/scripts/fork-tests/metal_cpp.py Layr-Labs/mlx/.github/scripts/fork-tests/metal_cpp.py
new file mode 100644
index 0000000000000000000000000000000000000000..69c8c04cbea5a5ef9490bd73ac0d6c839b75fbed
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/fork-tests/metal_cpp.py
@@ -0,0 +1,129 @@
+"""Fetch the pinned Apple headers before a native CI build."""
+
+import hashlib
+import shutil
+import stat
+import subprocess
+import sys
+import tempfile
+import time
+import zipfile
+from pathlib import Path, PurePosixPath
+
+URL = "https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip"
+SHA256 = "4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4"
+SIZE = 260405
+ATTEMPTS = 4
+
+
+def download(path, *, run=subprocess.run, sleep=time.sleep):
+ partial = path.with_suffix(".partial")
+ for attempt in range(1, ATTEMPTS + 1):
+ partial.unlink(missing_ok=True)
+ try:
+ result = run(
+ [
+ "curl",
+ "--disable",
+ "--fail",
+ "--location",
+ "--proto",
+ "=https",
+ "--proto-redir",
+ "=https",
+ "--connect-timeout",
+ "10",
+ "--max-time",
+ "60",
+ "--max-filesize",
+ str(SIZE),
+ "--silent",
+ "--show-error",
+ "--output",
+ str(partial),
+ URL,
+ ],
+ timeout=65,
+ check=False,
+ )
+ if result.returncode == 0 and partial.stat().st_size == SIZE:
+ if hashlib.sha256(partial.read_bytes()).hexdigest() == SHA256:
+ partial.replace(path)
+ return
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ partial.unlink(missing_ok=True)
+ print(
+ f"Apple header download attempt {attempt}/{ATTEMPTS} failed",
+ file=sys.stderr,
+ )
+ if attempt < ATTEMPTS:
+ sleep(2)
+ raise RuntimeError("Apple headers failed the bounded download/integrity check")
+
+
+def unpack(archive, destination):
+ with zipfile.ZipFile(archive) as source:
+ entries = source.infolist()
+ if (
+ len(entries) > 512
+ or sum(item.file_size for item in entries) > 16 * 1024 * 1024
+ ):
+ raise ValueError("Apple header archive exceeds its bounds")
+ names = set()
+ files = set()
+ for item in entries:
+ path = PurePosixPath(item.filename)
+ mode = stat.S_IFMT(item.external_attr >> 16)
+ if (
+ path.is_absolute()
+ or ".." in path.parts
+ or "\\" in item.filename
+ or "\x00" in item.filename
+ or not path.parts
+ or path.parts[0] != "metal-cpp"
+ or path.as_posix() != item.filename.rstrip("/")
+ or path in names
+ or item.flag_bits & 1
+ or mode not in (0, stat.S_IFREG, stat.S_IFDIR)
+ ):
+ raise ValueError("unsafe Apple header archive entry")
+ names.add(path)
+ if not item.is_dir():
+ files.add(path)
+ required = {
+ PurePosixPath("metal-cpp") / name
+ for name in (
+ "Metal/Metal.hpp",
+ "Foundation/Foundation.hpp",
+ "QuartzCore/QuartzCore.hpp",
+ )
+ }
+ if not required.issubset(files):
+ raise ValueError("Apple header archive is incomplete")
+ destination.mkdir()
+ for item in entries:
+ target = destination / item.filename
+ if item.is_dir():
+ target.mkdir(parents=True, exist_ok=True)
+ else:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with source.open(item) as reader, target.open("xb") as writer:
+ shutil.copyfileobj(reader, writer)
+ return destination / "metal-cpp"
+
+
+def main():
+ directory = Path(tempfile.mkdtemp(prefix="mlx-metal-cpp-", dir="/tmp"))
+ try:
+ archive = directory / "headers.zip"
+ download(archive)
+ source = unpack(archive, directory / "source")
+ print(f"cmake-args=-DFETCHCONTENT_SOURCE_DIR_METAL_CPP={source}")
+ except BaseException:
+ shutil.rmtree(directory)
+ raise
+
+
+if __name__ == "__main__":
+ main()
diff --git ml-explore/mlx/.github/scripts/fork-tests/python-shards.json Layr-Labs/mlx/.github/scripts/fork-tests/python-shards.json
new file mode 100644
index 0000000000000000000000000000000000000000..8d181d7fedb8b25d7f14dc21ceba0ce3a42954a2
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/fork-tests/python-shards.json
@@ -0,0 +1,98 @@
+{
+ "gpu": [
+ [
+ "test_quantized",
+ "test_ops",
+ "test_reduce",
+ "test_nn",
+ "test_threads",
+ "test_autograd",
+ "test_vmap",
+ "test_conv",
+ "test_optimizers",
+ "test_fast",
+ "test_linalg",
+ "test_load",
+ "test_eval",
+ "test_einsum",
+ "test_export_import",
+ "test_upsample",
+ "test_memory",
+ "test_init",
+ "test_random",
+ "test_losses",
+ "test_zero_copy",
+ "test_bf16",
+ "test_conv_transpose",
+ "test_double",
+ "test_constants",
+ "test_device",
+ "test_extension",
+ "test_graph",
+ "test_metal_threadgroup_bounds",
+ "test_tree"
+ ],
+ [
+ "test_fast_sdpa",
+ "test_fast_gated_delta",
+ "test_compile",
+ "test_fft",
+ "test_array",
+ "test_blas"
+ ]
+ ],
+ "cpu": [
+ [
+ "test_fast_gated_delta.TestGatedDelta.test_gated_delta_simdgroup",
+ "test_fast_sdpa.TestFastSDPA.test_sdpa_vector_gqa_long",
+ "test_fft",
+ "test_fast_gated_delta:rest",
+ "test_ops",
+ "test_array",
+ "test_conv",
+ "test_eval",
+ "test_autograd",
+ "test_metal_threadgroup_bounds",
+ "test_zero_copy",
+ "test_bf16",
+ "test_einsum",
+ "test_double",
+ "test_memory"
+ ],
+ [
+ "test_quantized:rest",
+ "test_reduce",
+ "test_fast_gated_delta.TestGatedDelta.test_gated_delta_sequential",
+ "test_compile",
+ "test_quantized.TestQuantized.test_qmv_wide",
+ "test_quantized.TestQuantized.test_gather_qmm_sorted",
+ "test_nn",
+ "test_quantized.TestQuantized.test_qmv",
+ "test_fast",
+ "test_upsample",
+ "test_threads",
+ "test_random",
+ "test_vmap",
+ "test_conv_transpose",
+ "test_tree",
+ "test_graph"
+ ],
+ [
+ "test_fast_gated_delta.TestGatedDelta.test_gated_delta_nax",
+ "test_fast_sdpa.TestFastSDPA.test_sdpa",
+ "test_fast_sdpa:rest",
+ "test_export_import",
+ "test_quantized.TestQuantized.test_gather_qmm_sorted_nax_large_m",
+ "test_blas",
+ "test_quantized.TestQuantized.test_qmm_large_dims",
+ "test_optimizers",
+ "test_load",
+ "test_extension",
+ "test_linalg",
+ "test_init",
+ "test_constants",
+ "test_losses",
+ "test_device"
+ ]
+ ]
+}
diff --git ml-explore/mlx/.github/scripts/fork-tests/python_shards.py Layr-Labs/mlx/.github/scripts/fork-tests/python_shards.py
new file mode 100755
index 0000000000000000000000000000000000000000..a1fc84736ec5e82c8e36e7fb6772a072cb3b13ef
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/fork-tests/python_shards.py
@@ -0,0 +1,371 @@
+#!/usr/bin/env python3
+"""Check and run the Python test shards of fork-tests.yml.
+
+The shard map (python-shards.json) has one list of shards for each pass
+("gpu" and "cpu"). A shard is a list of entries. Each entry runs in its own
+child process, and the child writes its own log. An entry is one of these:
+
+ test_x all tests in python/tests/test_x.py
+ test_x.Class.test_y one test (or a class with test_x.Class)
+ test_x:rest the tests in test_x.py that no other entry names
+
+Commands:
+
+ check Check the map without importing mlx. Every
+ python/tests/test*.py file must be in the map of
+ each pass exactly one time: as one whole-file
+ entry, or as named entries with at most one rest
+ entry. The command fails on any other case.
+ run PASS SHARD COUNT Check the map, expand the split files to test IDs
+ (this imports them), and fail if the named IDs of
+ a split file are not a partition of its tests.
+ Then run the entries of shard SHARD, JOBS at a
+ time. COUNT is the number of shard jobs in the
+ workflow, and it must equal the shards in the map.
+ verify DIR Read the test ID files that the shard jobs wrote
+ and fail if a test ran in two shards of a pass or
+ if a shard result is missing.
+"""
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+import threading
+import time
+import unittest
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+TESTS = Path("python/tests")
+MAP = Path(__file__).with_name("python-shards.json")
+PASSES = ("gpu", "cpu")
+
+
+def parse(entry):
+ """Return (file, kind) for a map entry."""
+ if entry.endswith(":rest"):
+ return entry[: -len(":rest")], "rest"
+ if "." in entry:
+ return entry.split(".", 1)[0], "named"
+ return entry, "whole"
+
+
+def load_map():
+ with open(MAP) as f:
+ data = json.load(f)
+ if sorted(data) != sorted(PASSES):
+ sys.exit(f"error: {MAP} must have exactly the keys {PASSES}")
+ return data
+
+
+def check_static(shards):
+ """Return a list of errors. Does not import mlx or the test files."""
+ errors = []
+ files = sorted(p.stem for p in TESTS.glob("test*.py"))
+ for name in PASSES:
+ uses = {}
+ entries = []
+ for index, shard in enumerate(shards[name]):
+ if not shard:
+ errors.append(f"{name} shard {index} has no entries")
+ for entry in shard:
+ file, kind = parse(entry)
+ uses.setdefault(file, []).append((index, kind, entry))
+ entries.append(entry)
+ for entry in sorted({e for e in entries if entries.count(e) > 1}):
+ errors.append(f"{name}: the entry {entry} is in the map more than one time")
+ for file in files:
+ found = uses.pop(file, [])
+ kinds = [kind for _, kind, _ in found]
+ where = ", ".join(f"shard {i}: {e}" for i, _, e in found)
+ if not found:
+ errors.append(f"{name}: {TESTS}/{file}.py is in no shard")
+ elif "whole" in kinds and len(found) > 1:
+ errors.append(
+ f"{name}: {TESTS}/{file}.py is in more than one shard "
+ f"or entry ({where})"
+ )
+ elif kinds.count("rest") > 1:
+ errors.append(
+ f"{name}: {TESTS}/{file}.py has more than one rest entry ({where})"
+ )
+ for file, found in sorted(uses.items()):
+ names = ", ".join(e for _, _, e in found)
+ errors.append(f"{name}: {names} names no file {TESTS}/{file}.py")
+ return errors
+
+
+def flatten(suite):
+ for test in suite:
+ if isinstance(test, unittest.TestSuite):
+ yield from flatten(test)
+ else:
+ yield test
+
+
+def test_ids(module):
+ suite = unittest.defaultTestLoader.loadTestsFromName(module)
+ ids = [test.id() for test in flatten(suite)]
+ bad = [i for i in ids if not i.startswith(module + ".")]
+ if bad:
+ sys.exit(f"error: {module} did not load: {bad}")
+ return ids
+
+
+def expand(shards, name):
+ """Expand the entries of one pass to child arguments.
+
+ Returns a list (one item for each shard) of lists of (entry, names),
+ where names is the list of unittest names for the child. Also returns
+ a list of errors.
+ """
+ errors = []
+ split = {}
+ for shard in shards[name]:
+ for entry in shard:
+ file, kind = parse(entry)
+ if kind != "whole":
+ split.setdefault(file, []).append(entry)
+ sys.path.insert(0, str(TESTS))
+ owner = {}
+ rest_ids = {}
+ for file, entries in sorted(split.items()):
+ ids = test_ids(file)
+ count = {i: 0 for i in ids}
+ for entry in entries:
+ if parse(entry)[1] != "named":
+ continue
+ matched = [i for i in ids if i == entry or i.startswith(entry + ".")]
+ if not matched:
+ errors.append(f"{name}: the entry {entry} matches no test in {file}.py")
+ for i in matched:
+ count[i] += 1
+ owner[i] = entry
+ twice = [i for i, c in count.items() if c > 1]
+ if twice:
+ errors.append(f"{name}: these tests are in more than one entry: {twice}")
+ missing = [i for i, c in count.items() if c == 0]
+ if f"{file}:rest" in entries:
+ rest_ids[file] = missing
+ elif missing:
+ errors.append(
+ f"{name}: these tests of {file}.py are in no shard: {missing}"
+ )
+ plan = []
+ for shard in shards[name]:
+ units = []
+ for entry in shard:
+ file, kind = parse(entry)
+ if kind == "whole":
+ units.append((entry, [entry]))
+ elif kind == "rest":
+ units.append((entry, rest_ids.get(file, [])))
+ else:
+ units.append((entry, sorted(i for i, e in owner.items() if e == entry)))
+ plan.append(units)
+ return plan, errors
+
+
+def child(log_dir, unit, names):
+ """Run the tests in names in this process. Used by run."""
+ # The same settings as python/tests/run.py.
+ os.environ["MLX_ENABLE_TF32"] = "0"
+ os.environ["MLX_ENABLE_CACHE_THRASHING_CHECK"] = "0"
+ sys.path.insert(0, str(TESTS))
+ import mlx.core as mx
+
+ exclude = set(os.environ.get("CPU_EXCLUDE", "").split())
+ suite = unittest.defaultTestLoader.loadTestsFromNames(names)
+ tests = [t for t in flatten(suite) if t.id() not in exclude]
+ ran = []
+
+ class Result(unittest.TextTestResult):
+ def startTest(self, test):
+ ran.append(test.id())
+ super().startTest(test)
+
+ runner = unittest.TextTestRunner(
+ sys.stdout, verbosity=2, durations=0, resultclass=Result
+ )
+ result = runner.run(unittest.TestSuite(tests))
+ with open(Path(log_dir) / f"{unit}.ids", "w") as f:
+ json.dump(ran, f)
+ mx.clear_streams()
+ sys.exit(0 if result.wasSuccessful() else 1)
+
+
+def file_name(entry):
+ return re.sub(r"[^A-Za-z0-9_.-]", "_", entry)
+
+
+def run(args):
+ shards = load_map()
+ errors = check_static(shards)
+ if errors:
+ report(errors)
+ if args.count != len(shards[args.name]):
+ report(
+ [
+ f"the workflow runs {args.count} {args.name} shard jobs, "
+ f"but {MAP.name} has {len(shards[args.name])} {args.name} shards"
+ ]
+ )
+ plan, errors = expand(shards, args.name)
+ if errors:
+ report(errors)
+ units = plan[args.shard]
+ logs = Path(args.logs)
+ logs.mkdir(parents=True, exist_ok=True)
+ lock = threading.Lock()
+ results = {}
+
+ def one(unit):
+ entry, names = unit
+ name = file_name(entry)
+ start = time.monotonic()
+ with open(logs / f"{name}.log", "w") as log:
+ code = subprocess.run(
+ [sys.executable, "-u", __file__, "child", str(logs), name, *names],
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ ).returncode
+ seconds = time.monotonic() - start
+ with lock:
+ results[entry] = (code, seconds)
+ state = "passed" if code == 0 else f"failed (exit code {code})"
+ print(f"{entry}: {state} in {seconds:.1f} s", flush=True)
+ # Print the end of a failed log at once. The full logs print
+ # after all entries finish, and a killed job never gets there.
+ if code != 0:
+ tail = (
+ (logs / f"{name}.log")
+ .read_text(errors="replace")
+ .splitlines()[-80:]
+ )
+ print("\n".join(f" | {line}" for line in tail), flush=True)
+
+ print(
+ f"{args.name} shard {args.shard}: {len(units)} entries, {args.jobs} at a time",
+ flush=True,
+ )
+ with ThreadPoolExecutor(max_workers=args.jobs) as pool:
+ list(pool.map(one, units))
+
+ ran = {}
+ failed = []
+ for entry, _ in units:
+ name = file_name(entry)
+ print(f"::group::Python tests ({args.name}): {entry}")
+ print((logs / f"{name}.log").read_text(errors="replace"), end="")
+ print("::endgroup::")
+ if results[entry][0] != 0:
+ failed.append(entry)
+ ids_file = logs / f"{name}.ids"
+ ran[entry] = json.loads(ids_file.read_text()) if ids_file.exists() else []
+ out = {
+ "pass": args.name,
+ "shard": args.shard,
+ "count": args.count,
+ "entries": {
+ e: {
+ "exit": results[e][0],
+ "seconds": round(results[e][1], 1),
+ "tests": ran[e],
+ }
+ for e, _ in units
+ },
+ }
+ with open(logs / f"testids-{args.name}-{args.shard}.json", "w") as f:
+ json.dump(out, f)
+ summary = os.environ.get("GITHUB_STEP_SUMMARY")
+ if summary:
+ with open(summary, "a") as f:
+ f.write(f"### Python tests, {args.name} pass, shard {args.shard}\n\n")
+ f.write("| Entry | Result | Tests | Seconds |\n|---|---|---|---|\n")
+ for e, _ in sorted(units, key=lambda u: -results[u[0]][1]):
+ code, seconds = results[e]
+ state = "passed" if code == 0 else f"failed ({code})"
+ f.write(f"| `{e}` | {state} | {len(ran[e])} | {seconds:.1f} |\n")
+ total = sum(len(t) for t in ran.values())
+ f.write(f"\nTests started: {total}\n\n")
+ if failed:
+ names = " ".join(failed)
+ print(f"::error::Python test entries that failed ({args.name} pass): {names}")
+ sys.exit(1)
+
+
+def verify(args):
+ shards = load_map()
+ errors = []
+ lines = [
+ "### Python tests in all shards",
+ "",
+ "| Pass | Shards | Tests started |",
+ "|---|---|---|",
+ ]
+ for name in PASSES:
+ seen = {}
+ found = 0
+ for index in range(len(shards[name])):
+ path = Path(args.dir) / f"testids-{name}-{index}.json"
+ if not path.exists():
+ errors.append(f"{name} shard {index} wrote no result ({path.name})")
+ continue
+ found += 1
+ data = json.loads(path.read_text())
+ for entry, info in data["entries"].items():
+ for test in info["tests"]:
+ seen.setdefault(test, []).append(f"shard {index} {entry}")
+ twice = {t: w for t, w in seen.items() if len(w) > 1}
+ for test, where in sorted(twice.items()):
+ errors.append(f"{name}: {test} ran more than one time: {where}")
+ lines.append(f"| {name} | {found} of {len(shards[name])} | {len(seen)} |")
+ summary = os.environ.get("GITHUB_STEP_SUMMARY")
+ if summary:
+ with open(summary, "a") as f:
+ f.write("\n".join(lines) + "\n\n")
+ print("\n".join(lines))
+ if errors:
+ report(errors)
+
+
+def report(errors):
+ for error in errors:
+ print(f"::error::{error}")
+ sys.exit(1)
+
+
+def main():
+ if len(sys.argv) > 1 and sys.argv[1] == "child":
+ child(sys.argv[2], sys.argv[3], sys.argv[4:])
+ return
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ sub = parser.add_subparsers(dest="command", required=True)
+ sub.add_parser("check")
+ p = sub.add_parser("run")
+ p.add_argument("name", choices=PASSES)
+ p.add_argument("shard", type=int)
+ p.add_argument("count", type=int)
+ p.add_argument("--jobs", type=int, default=1)
+ p.add_argument("--logs", required=True)
+ p = sub.add_parser("verify")
+ p.add_argument("dir")
+ args = parser.parse_args()
+ if args.command == "check":
+ errors = check_static(load_map())
+ if errors:
+ report(errors)
+ print(f"{MAP.name}: every test file is in exactly one place in each pass.")
+ elif args.command == "run":
+ if not 0 <= args.shard < args.count:
+ report([f"shard {args.shard} is not in 0..{args.count - 1}"])
+ run(args)
+ else:
+ verify(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git ml-explore/mlx/.github/scripts/fork-tests/test_metal_cpp.py Layr-Labs/mlx/.github/scripts/fork-tests/test_metal_cpp.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3cf327957baece4339171d16199576ded32c670
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/fork-tests/test_metal_cpp.py
@@ -0,0 +1,158 @@
+import hashlib
+import io
+import stat
+import subprocess
+import tempfile
+import unittest
+import warnings
+import zipfile
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import metal_cpp
+
+
+def archive(entries=()):
+ data = io.BytesIO()
+ with warnings.catch_warnings(), zipfile.ZipFile(data, "w") as output:
+ warnings.simplefilter("ignore", UserWarning)
+ for name in (
+ "Metal/Metal.hpp",
+ "Foundation/Foundation.hpp",
+ "QuartzCore/QuartzCore.hpp",
+ ):
+ output.writestr("metal-cpp/" + name, b"header")
+ for name, value in entries:
+ output.writestr(name, value)
+ return data.getvalue()
+
+
+class MetalCppIntegrity(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+
+ def test_cmake_pins_the_verified_archive(self):
+ source = Path(__file__).resolve().parents[3] / "CMakeLists.txt"
+ self.assertRegex(source.read_text(), r"URL_HASH\s+SHA256=" + metal_cpp.SHA256)
+ self.assertIn(metal_cpp.URL, source.read_text())
+
+ def test_partial_transfer_retries_from_empty_file(self):
+ content = archive()
+ calls = []
+
+ def run(args, **kwargs):
+ path = Path(args[args.index("--output") + 1])
+ self.assertFalse(path.exists())
+ self.assertEqual(kwargs["timeout"], 65)
+ self.assertEqual(args[args.index("--max-filesize") + 1], str(len(content)))
+ self.assertIn("=https", args)
+ self.assertNotIn("--insecure", args)
+ calls.append(args)
+ path.write_bytes(content[:5] if len(calls) == 1 else content)
+ return SimpleNamespace(returncode=18 if len(calls) == 1 else 0)
+
+ sleep = Mock()
+ with (
+ patch.object(metal_cpp, "SIZE", len(content)),
+ patch.object(metal_cpp, "SHA256", hashlib.sha256(content).hexdigest()),
+ ):
+ metal_cpp.download(self.root / "headers.zip", run=run, sleep=sleep)
+ self.assertEqual(len(calls), 2)
+ self.assertEqual((self.root / "headers.zip").read_bytes(), content)
+ sleep.assert_called_once_with(2)
+
+ def test_timeout_clears_partial_file_before_retry(self):
+ content = archive()
+ calls = []
+
+ def run(args, **kwargs):
+ path = Path(args[args.index("--output") + 1])
+ self.assertFalse(path.exists())
+ calls.append(args)
+ if len(calls) == 1:
+ path.write_bytes(content[:5])
+ raise subprocess.TimeoutExpired(args, kwargs["timeout"])
+ path.write_bytes(content)
+ return SimpleNamespace(returncode=0)
+
+ with (
+ patch.object(metal_cpp, "SIZE", len(content)),
+ patch.object(metal_cpp, "SHA256", hashlib.sha256(content).hexdigest()),
+ ):
+ metal_cpp.download(self.root / "headers.zip", run=run, sleep=Mock())
+ self.assertEqual(len(calls), 2)
+ self.assertEqual((self.root / "headers.zip").read_bytes(), content)
+
+ def test_wrong_digest_aborts_after_four_attempts(self):
+ content = b"bad content of expected length"
+ run = Mock()
+
+ def write(args, **kwargs):
+ Path(args[args.index("--output") + 1]).write_bytes(content)
+ return SimpleNamespace(returncode=0)
+
+ run.side_effect = write
+ sleep = Mock()
+ with (
+ patch.object(metal_cpp, "SIZE", len(content)),
+ self.assertRaises(RuntimeError),
+ ):
+ metal_cpp.download(self.root / "headers.zip", run=run, sleep=sleep)
+ self.assertEqual(run.call_count, 4)
+ self.assertEqual(sleep.call_count, 3)
+ self.assertEqual(list(self.root.iterdir()), [])
+
+ def test_failed_transfers_abort_without_publishing(self):
+ run = Mock(return_value=SimpleNamespace(returncode=18))
+ with self.assertRaises(RuntimeError):
+ metal_cpp.download(self.root / "headers.zip", run=run, sleep=Mock())
+ self.assertEqual(run.call_count, 4)
+ self.assertEqual(list(self.root.iterdir()), [])
+
+ def test_valid_headers_extract(self):
+ path = self.root / "headers.zip"
+ path.write_bytes(archive())
+ result = metal_cpp.unpack(path, self.root / "source")
+ self.assertEqual((result / "Metal/Metal.hpp").read_bytes(), b"header")
+
+ def test_unsafe_paths_are_rejected_before_extraction(self):
+ for name in (
+ "../escape",
+ "/escape",
+ "metal-cpp/../escape",
+ "metal-cpp\\escape",
+ "other/file",
+ ):
+ with self.subTest(name=name):
+ path = self.root / "headers.zip"
+ path.write_bytes(archive([(name, b"bad")]))
+ with self.assertRaises(ValueError):
+ metal_cpp.unpack(path, self.root / "source")
+ self.assertFalse((self.root / "source").exists())
+
+ def test_duplicate_or_symlink_is_rejected(self):
+ link = zipfile.ZipInfo("metal-cpp/link")
+ link.external_attr = (stat.S_IFLNK | 0o777) << 16
+ for extra in [
+ [("metal-cpp/Metal/Metal.hpp", b"duplicate")],
+ [(link, b"/escape")],
+ ]:
+ path = self.root / "headers.zip"
+ path.write_bytes(archive(extra))
+ with self.assertRaises(ValueError):
+ metal_cpp.unpack(path, self.root / "source")
+ self.assertFalse((self.root / "source").exists())
+
+ def test_expanded_archive_bound_is_enforced(self):
+ path = self.root / "headers.zip"
+ path.write_bytes(archive([("metal-cpp/large", b"x" * (16 * 1024 * 1024))]))
+ with self.assertRaises(ValueError):
+ metal_cpp.unpack(path, self.root / "source")
+ self.assertFalse((self.root / "source").exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git ml-explore/mlx/.github/scripts/test-ci-resource-sampler.py Layr-Labs/mlx/.github/scripts/test-ci-resource-sampler.py
new file mode 100755
index 0000000000000000000000000000000000000000..fc890c16a463e536296485b0783a8ef22fe59f88
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/test-ci-resource-sampler.py
@@ -0,0 +1,406 @@
+#!/usr/bin/env python3
+"""Offline checks of the report-only resource sampler.
+
+They check parsing, attribution, the summary, and that it never fails.
+
+The native readers (`proc_pid_rusage`, `host_statistics`) and a whole sample
+run only on macOS; the CI jobs' own samples are their check.
+"""
+
+import contextlib
+import csv
+import importlib.util
+import io
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent.parent
+SCRIPT = ROOT / "scripts/ci-resource-sampler.py"
+SPEC = importlib.util.spec_from_file_location("ci_resource_sampler", SCRIPT)
+sampler = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(sampler)
+GIB = sampler.GIB
+
+# macOS 27 `vm_stat` output, shortened.
+VM_STAT = """Mach Virtual Memory Statistics: (page size of 16384 bytes)
+Pages free: 100000.
+Pages active: 200000.
+Pages inactive: 150000.
+Pages speculative: 5000.
+Pages wired down: 50000.
+Pages purgeable: 2000.
+"Translation faults": 9999999.
+File-backed pages: 120000.
+Anonymous pages: 230000.
+Pages occupied by compressor: 10000.
+"""
+PS = """ 1 0 0.0 512 /sbin/launchd
+ 100 1 12.5 204800 /usr/bin/swift-frontend
+ 200 150 250.0 4194304 /private/tmp/w/.build/debug/swiftpm-testing-helper
+ 150 1 0.0 512 /Applications/Xcode 27.app/usr/bin/my tool
+ garbage
+"""
+FOOTPRINT_TEXT = """\
+======================================================================
+swiftpm-testing-helper [200]: 64-bit Footprint: 9 GB (16384 bytes per page)
+======================================================================
+
+ Dirty Clean Reclaimable Regions Category
+ 6 GB 0 B 0 B 12 IOAccelerator (graphics)
+ 1 GB 0 B 0 B 800 MALLOC_LARGE
+"""
+
+
+def write_rows(directory, rows):
+ with open(directory / sampler.SAMPLES, "w", newline="") as handle:
+ writer = csv.DictWriter(handle, sampler.FIELDS)
+ writer.writeheader()
+ writer.writerows(rows)
+
+
+def row(
+ stamp, used, app, wired, cache, compressed, swap, pressure, busy, footprint, top
+):
+ return {
+ "time": stamp,
+ "used_bytes": used * GIB,
+ "app_bytes": app * GIB,
+ "wired_bytes": wired * GIB,
+ "file_bytes": cache * GIB,
+ "compressed_bytes": compressed * GIB,
+ "swap_bytes": swap * GIB,
+ "pressure": pressure,
+ "busy_vcpus": busy,
+ "footprint_bytes": "" if footprint is None else footprint * GIB,
+ "top_rss_bytes": GIB,
+ "top_command": "swiftpm-testing-helper",
+ "top_footprints": json.dumps(top) if top else "",
+ }
+
+
+class ParsingTests(unittest.TestCase):
+ def test_memory_counts_each_class_as_activity_monitor_does(self):
+ classes = sampler.memory(VM_STAT)
+ page = 16384
+ self.assertEqual(
+ classes,
+ {
+ "used_bytes": (228000 + 50000 + 10000) * page,
+ "app_bytes": 228000 * page,
+ "wired_bytes": 50000 * page,
+ "file_bytes": 122000 * page,
+ "compressed_bytes": 10000 * page,
+ },
+ )
+ with self.assertRaises(KeyError):
+ sampler.memory(VM_STAT.replace("Anonymous pages", "Anonymous"))
+
+ def test_swap_used_reads_each_unit(self):
+ self.assertEqual(
+ sampler.swap_used(
+ "total = 2048.00M used = 1536.50M free = 511.50M (encrypted)"
+ ),
+ int(1536.5 * 2**20),
+ )
+ self.assertEqual(
+ sampler.swap_used("total = 4.00G used = 1.50G free = 2.50G"),
+ int(1.5 * GIB),
+ )
+ self.assertEqual(
+ sampler.swap_used("total = 0.00M used = 0.00M free = 0.00M (encrypted)"),
+ 0,
+ )
+ with self.assertRaises(AttributeError):
+ sampler.swap_used("no swap")
+
+ def test_processes_keep_pid_parent_cpu_rss_and_the_command_name(self):
+ listed = sampler.processes(PS)
+ self.assertEqual(listed[1], (100, 1, 12.5, 204800 * 1024, "swift-frontend"))
+ self.assertEqual(listed[2][4], "swiftpm-testing-helper")
+ self.assertEqual(listed[3][4], "my tool")
+ self.assertEqual(len(listed), 4)
+
+ def test_busy_vcpus_from_tick_deltas_survive_a_counter_wrap(self):
+ self.assertAlmostEqual(sampler.busy_vcpus((100, 1000), (400, 1600), 12), 6.0)
+ self.assertAlmostEqual(
+ sampler.busy_vcpus((2**32 - 100, 2**32 - 50), (200, 550), 12), 6.0
+ )
+ self.assertIsNone(sampler.busy_vcpus((5, 9), (5, 9), 12))
+
+ def test_native_readers_refuse_outside_macos(self):
+ if sys.platform == "darwin":
+ self.skipTest("the native readers exist here")
+ with self.assertRaises(OSError):
+ sampler.footprints([1])
+ self.assertIsNone(sampler.Sampler(Path(".")).read_ticks())
+
+
+class AttributionTests(unittest.TestCase):
+ def test_active_marks_and_the_nearest_marked_ancestor_name_the_selection(self):
+ with tempfile.TemporaryDirectory() as work:
+ marks = Path(work) / sampler.MARKS
+ self.assertEqual(sampler.active_marks(marks), {})
+ marks.write_text(
+ "1.0,start,1-of-6,150\n2.0,start,2-of-6,160\n3.0,end,1-of-6,150\n"
+ "4.0,start,parallel,150\n5.0,end,1-of-6,160\nbroken\n"
+ "6.0,start,x,pid\n7.0,start,y,1.5\n"
+ "partial,start,z,170\n"
+ )
+ active = sampler.active_marks(marks)
+ # An end ends only the same label under the same pid; a row with a bad
+ # time or pid is skipped.
+ self.assertEqual(active, {150: "parallel", 160: "2-of-6"})
+ parents = {300: 200, 200: 160, 160: 1, 1: 0, 7: 8, 8: 7}
+ self.assertEqual(sampler.selection_of(300, parents, active), "2-of-6")
+ self.assertEqual(sampler.selection_of(150, parents, active), "parallel")
+ self.assertEqual(sampler.selection_of(999, parents, active), "")
+ self.assertEqual(sampler.selection_of(7, parents, active), "")
+
+ def test_mark_writes_only_in_a_sampled_job_and_defaults_to_its_caller(self):
+ with tempfile.TemporaryDirectory() as work:
+ with mock.patch.dict(os.environ, {}, clear=False):
+ os.environ.pop(sampler.ENVIRONMENT, None)
+ sampler.mark("start", "1-of-6")
+ self.assertFalse((Path(work) / sampler.MARKS).exists())
+ with mock.patch.dict(os.environ, {sampler.ENVIRONMENT: work}):
+ sampler.mark("start", "1-of-6")
+ sampler.mark("end", "1-of-6", 4242)
+ with self.assertRaises(ValueError):
+ sampler.mark("begin", "1-of-6", 1)
+ printed = io.StringIO()
+ with contextlib.redirect_stdout(printed):
+ self.assertEqual(sampler.main(["mark", "begin", "1-of-6"]), 0)
+ self.assertIn(
+ "::warning title=Resource sampler::ValueError", printed.getvalue()
+ )
+ rows = list(
+ csv.reader((Path(work) / sampler.MARKS).read_text().splitlines())
+ )
+ self.assertEqual(
+ [row[1:] for row in rows],
+ [["start", "1-of-6", str(os.getppid())], ["end", "1-of-6", "4242"]],
+ )
+
+
+class CaptureTests(unittest.TestCase):
+ def test_footprint_runs_on_each_new_high_and_at_most_twice(self):
+ with tempfile.TemporaryDirectory() as work:
+ directory = Path(work)
+ self.enterContext(mock.patch.object(sampler, "FOOTPRINT", "/bin/echo"))
+ capturing = sampler.Sampler(directory)
+ capturing.capture(200, GIB, "100") # Under the first step.
+ capturing.capture(200, 3 * GIB, "105")
+ capturing.capture(200, 4 * GIB, "110") # Not 2 GiB above the last capture.
+ capturing.capture(201, 5 * GIB, "115")
+ capturing.capture(202, 9 * GIB, "120") # Two captures already.
+ for _, child in capturing.captures:
+ child.wait(timeout=10)
+ self.assertEqual(
+ sorted(path.name for path in directory.glob("footprint-*")),
+ ["footprint-105-200.txt", "footprint-115-201.txt"],
+ )
+ self.assertEqual((directory / "footprint-115-201.txt").read_text(), "201\n")
+
+ def test_a_footprint_that_outlives_its_time_is_killed(self):
+ with tempfile.TemporaryDirectory() as work:
+ self.enterContext(mock.patch.object(sampler, "FOOTPRINT", "/bin/sleep"))
+ self.enterContext(mock.patch.object(sampler, "CAPTURE_SECONDS", -1))
+ capturing = sampler.Sampler(Path(work))
+ capturing.capture(30, 3 * GIB, "100")
+ capturing.reap()
+ _, child = capturing.captures[0]
+ self.assertLess(child.wait(timeout=10), 0)
+
+ def test_no_capture_without_the_tool(self):
+ with tempfile.TemporaryDirectory() as work:
+ self.enterContext(
+ mock.patch.object(sampler, "FOOTPRINT", str(Path(work) / "absent"))
+ )
+ capturing = sampler.Sampler(Path(work))
+ capturing.capture(200, 9 * GIB, "100")
+ self.assertEqual(capturing.captures, [])
+
+
+class SummaryTests(unittest.TestCase):
+ def test_summary_reports_each_class_the_top_processes_and_the_selection_at_the_peak(
+ self,
+ ):
+ with tempfile.TemporaryDirectory() as work:
+ directory = Path(work)
+ write_rows(
+ directory,
+ [
+ row(
+ "100",
+ 6,
+ 4,
+ 1,
+ 3,
+ 1,
+ 0,
+ 1,
+ 2.0,
+ 3,
+ [
+ [200, "swiftpm-testing-helper", 2 * GIB, 3 * GIB, "2-of-6"],
+ [100, "swift-frontend", GIB, GIB, ""],
+ ],
+ ),
+ row(
+ "105",
+ 10,
+ 5,
+ 4,
+ 2,
+ 1,
+ 1,
+ 2,
+ 24.0,
+ 9,
+ [
+ [200, "swiftpm-testing-helper", 8 * GIB, 9 * GIB, ""],
+ [300, "xctest", GIB, GIB, "3-of-6"],
+ ],
+ ),
+ row("110", 8, 3, 4, 5, 1, 0, 1, 6.0, None, None),
+ ],
+ )
+ (directory / sampler.MACHINE).write_text(f"12 {32 * GIB}\n")
+ (directory / sampler.MARKS).write_text(
+ "101.0,start,2-of-6,150\n102.0,start,3-of-6,160\n"
+ "104.0,end,3-of-6,160\n108.0,end,2-of-6,150\n"
+ "partial,start,3-of-6,170\n"
+ )
+ (directory / "footprint-105-200.txt").write_text(FOOTPRINT_TEXT)
+ (directory / "footprint-110-300.txt").write_text(
+ "footprint: insufficient privileges\n"
+ )
+ self.enterContext(
+ mock.patch.object(sampler, "FOOTPRINT", str(directory / "absent"))
+ )
+ lines = sampler.summary(directory)
+ facts = json.loads((directory / sampler.SUMMARY).read_text())
+ self.assertEqual(lines[0], "Machine: 12 vCPUs, 32.0 GiB.")
+ self.assertEqual(
+ lines[3],
+ "| 3 over 10 s | 10.00 | 5.00 | 4.00 | 5.00 | 1.00 | 1.00 | 2 | 10.67 "
+ "| 24.00 | 24.00 |",
+ )
+ self.assertIn("Peak used at 00:01:45 UTC, during: 2-of-6.", lines)
+ self.assertIn(
+ "| `swiftpm-testing-helper` | 200 | 9.00 | 2-of-6 | 00:01:45 |", lines
+ )
+ self.assertIn("| `swift-frontend` | 100 | 1.00 | - | 00:01:40 |", lines)
+ self.assertIn("| `xctest` | 300 | 1.00 | 3-of-6 | 00:01:45 |", lines)
+ self.assertTrue(any("their sum peaked at 9.00 GiB" in line for line in lines))
+ self.assertIn(
+ f"`{directory / 'absent'}`: absent, 2 captures in the samples artifact.",
+ lines,
+ )
+ self.assertIn(
+ "- `footprint-105-200.txt`: `swiftpm-testing-helper [200]: 64-bit "
+ "Footprint: 9 GB (16384 bytes per page)`; `6 GB 0 B 0 B "
+ " 12 IOAccelerator (graphics)`",
+ lines,
+ )
+ self.assertIn(
+ "- `footprint-110-300.txt`: `footprint: insufficient privileges`", lines
+ )
+ self.assertEqual(facts["peaks"]["file_bytes"], {"bytes": 5 * GIB, "time": 110})
+ self.assertEqual(
+ facts["peaks"]["footprint_bytes"], {"bytes": 9 * GIB, "time": 105}
+ )
+ self.assertEqual(facts["selections_at_peak_used"], ["2-of-6"])
+ self.assertEqual(facts["scaled_seconds"], {"4": 37.5, "8": 20.0})
+ self.assertEqual(facts["busy_vcpus"]["p95"], 24.0)
+ self.assertEqual(
+ [process["pid"] for process in facts["top_processes"]], [200, 100, 300]
+ )
+
+ def test_summary_without_footprints_marks_or_machine_still_reports(self):
+ with tempfile.TemporaryDirectory() as work:
+ directory = Path(work)
+ write_rows(
+ directory,
+ [
+ row("100", 6, 4, 1, 3, 1, 0, 1, 2.0, None, None),
+ row("105", 7, 4, 2, 3, 1, 0, 1, 1.0, None, None),
+ ],
+ )
+ lines = sampler.summary(directory)
+ facts = json.loads((directory / sampler.SUMMARY).read_text())
+ self.assertIn("Peak used at 00:01:45 UTC.", lines)
+ self.assertFalse(any(line.startswith("| Process") for line in lines))
+ self.assertIsNone(facts["peaks"]["footprint_bytes"])
+ self.assertNotIn("scaled_seconds", facts)
+
+
+class LifecycleTests(unittest.TestCase):
+ def test_report_never_fails_and_writes_the_step_summary(self):
+ with tempfile.TemporaryDirectory() as work:
+ summary = Path(work) / "summary"
+ self.enterContext(
+ mock.patch.dict(os.environ, {"GITHUB_STEP_SUMMARY": str(summary)})
+ )
+ printed = io.StringIO()
+ with contextlib.redirect_stdout(printed):
+ # No samples directory at all: a warning, never a failure.
+ self.assertEqual(
+ sampler.main(["report", str(Path(work) / "absent")]), 0
+ )
+ self.assertIn("::warning title=Resource sampler::", printed.getvalue())
+ directory = Path(work) / "empty"
+ directory.mkdir()
+ (directory / sampler.SAMPLES).write_text(",".join(sampler.FIELDS) + "\n")
+ (directory / sampler.PID).write_text("not a pid\n")
+ with contextlib.redirect_stdout(io.StringIO()):
+ self.assertEqual(sampler.main(["report", str(directory)]), 0)
+ self.assertIn("Resource sampler: no samples.", summary.read_text())
+
+ def test_start_runs_in_the_background_until_report_stops_it(self):
+ with tempfile.TemporaryDirectory() as work:
+ directory = Path(work) / "samples"
+ github_env = Path(work) / "github-env"
+ started = subprocess.run(
+ [
+ sys.executable,
+ str(SCRIPT),
+ "start",
+ str(directory),
+ "--interval",
+ "0.05",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ env={**os.environ, "GITHUB_ENV": str(github_env)},
+ )
+ self.assertEqual(started.returncode, 0, started.stdout + started.stderr)
+ # Later steps find the directory for their marks.
+ self.assertEqual(
+ github_env.read_text(), f"{sampler.ENVIRONMENT}={directory.resolve()}\n"
+ )
+ pid = int((directory / sampler.PID).read_text())
+ os.kill(pid, 0)
+ with contextlib.redirect_stdout(io.StringIO()):
+ self.assertEqual(sampler.main(["report", str(directory)]), 0)
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ break
+ time.sleep(0.05)
+ else:
+ self.fail(f"sampler {pid} still runs after the report")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git ml-explore/mlx/.github/scripts/test-runner-sizes.py Layr-Labs/mlx/.github/scripts/test-runner-sizes.py
new file mode 100755
index 0000000000000000000000000000000000000000..802ad54f3e021063d49c1c5b8758e040e17ba178
--- /dev/null
+++ Layr-Labs/mlx/.github/scripts/test-runner-sizes.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python3
+"""Every macOS job that runs on Darkbloom names a signed VM size.
+
+A Darkbloom macOS job without a size gets the size that the repository's
+approval pins. Each macOS job here names its own size instead: in its runner
+label (`darkbloom-macos-arm64-4x16`), or, for a lane of
+`darkbloom-route.yml`, in the lane's size column. This test fails when:
+
+- a job asks for a Darkbloom Mac without a size, or with a size that the
+ image pipeline does not sign (4x16, 4x24, 8x16 and 12x32);
+- a Linux route lane names a size (the route refuses one);
+- a job's size is not the size that SIZES gives it, or SIZES names a job
+ that no workflow has (so a size changes only on purpose);
+- `.github/actionlint.yaml` does not list a used label, or still lists the
+ label without a size.
+
+FORKDIFF.md (Job sizes) gives each size and the data behind it.
+
+Run: python3 .github/scripts/test-runner-sizes.py
+"""
+
+import re
+import unittest
+from pathlib import Path
+
+GITHUB = Path(__file__).resolve().parent.parent
+WORKFLOWS = GITHUB / "workflows"
+ACTIONLINT = GITHUB / "actionlint.yaml"
+SIGNED = {"4x16", "4x24", "8x16", "12x32"}
+MACOS = "darkbloom-macos-arm64"
+# (workflow, job) for a job, (workflow, "lane <name>") for a route lane: its size.
+SIZES = {
+ ("fork-tests.yml", "build-wheel"): "4x16",
+ ("fork-tests.yml", "build-cpp"): "4x16",
+ ("fork-tests.yml", "python-gpu"): "4x24",
+ ("fork-tests.yml", "python-cpu"): "12x32",
+ ("fork-tests.yml", "metal-build-and-test"): "4x16",
+}
+
+JOB = re.compile(r"(?m)^ ([A-Za-z0-9_-]+):[ \t]*(?:#.*)?\n")
+RUNS_ON = re.compile(r"(?m)^ runs-on:(.*)$")
+MACOS_LABELS = re.compile(
+ r"\[self-hosted, macOS, ARM64, " + MACOS + r"-([0-9]+x[0-9]+)\]"
+)
+ROUTE = " uses: ./.github/workflows/darkbloom-route.yml"
+LANES = re.compile(r"(?m)^ lanes: \|\n((?: .*\n|[ \t]*\n)*)")
+EXPRESSION = re.compile(r"\$\{\{.*?\}\}")
+
+
+def jobs(text):
+ """Return {job id: text} of a workflow's `jobs:` mapping (two-space job keys)."""
+ text = "\n" + text
+ if "\njobs:\n" not in text:
+ return {}
+ parts = JOB.split(text.split("\njobs:\n", 1)[1])
+ return dict(zip(parts[1::2], parts[2::2]))
+
+
+def lane_lines(job):
+ """Return the fields of each line of a route job's `lanes:` block.
+
+ A `${{ }}` expression counts as one field.
+ """
+ match = LANES.search(job)
+ if not match:
+ return []
+ return [
+ EXPRESSION.sub("EXPRESSION", line).split()
+ for line in match.group(1).splitlines()
+ if line.strip()
+ ]
+
+
+def macos_sizes(workflows):
+ """Return ({(workflow, job or "lane <name>"): size}, [errors]).
+
+ `workflows` is {workflow file name: text}.
+ """
+ sizes, errors = {}, []
+ for workflow, text in sorted(workflows.items()):
+ for name, job in jobs(text).items():
+ where = f"{workflow}: job {name}"
+ if ROUTE in job:
+ for fields in lane_lines(job):
+ lane, profile = fields[0], fields[1] if len(fields) > 1 else ""
+ size = fields[4] if len(fields) > 4 else None
+ if profile == "macos_arm64":
+ if size not in SIGNED:
+ errors.append(f"{where}: macOS lane {lane}: no signed size")
+ sizes[(workflow, f"lane {lane}")] = size
+ elif size is not None:
+ errors.append(f"{where}: lane {lane} is not macOS: no size")
+ runs_on = RUNS_ON.findall(job)
+ if not runs_on:
+ continue
+ value = runs_on[0].split(" #", 1)[0].strip()
+ if len(runs_on) > 1 or not value:
+ errors.append(f"{where}: write runs-on once, on one line")
+ continue
+ if MACOS not in value:
+ continue
+ match = MACOS_LABELS.fullmatch(value)
+ if not match:
+ errors.append(
+ f"{where}: runs-on {value} names no size; use [self-hosted, "
+ f"macOS, ARM64, {MACOS}-<size>], a size of {sorted(SIGNED)}"
+ )
+ continue
+ if match.group(1) not in SIGNED:
+ errors.append(f"{where}: size {match.group(1)} is not signed")
+ sizes[(workflow, name)] = match.group(1)
+ return sizes, errors
+
+
+def actionlint_labels():
+ text = ACTIONLINT.read_text()
+ return set(re.findall(r"(?m)^ - ([A-Za-z0-9._-]+)\s*$", text))
+
+
+class RunnerSizes(unittest.TestCase):
+ def setUp(self):
+ self.workflows = {
+ path.name: path.read_text() for path in sorted(WORKFLOWS.glob("*.yml"))
+ }
+
+ def test_every_macos_job_names_its_signed_size(self):
+ sizes, errors = macos_sizes(self.workflows)
+ self.assertEqual(errors, [])
+ self.assertLessEqual(set(SIZES.values()), SIGNED)
+ self.assertEqual(sizes, SIZES)
+
+ def test_actionlint_lists_the_sized_labels_only(self):
+ labels = actionlint_labels()
+ for size in sorted(set(SIZES.values())):
+ self.assertIn(f"{MACOS}-{size}", labels)
+ self.assertNotIn(MACOS, labels)
+
+ def test_an_unsized_or_unsigned_job_fails(self):
+ # The check must block, not only pass: each of these is refused.
+ job = "jobs:\n a:\n runs-on: [self-hosted, macOS, ARM64, {}]\n"
+ bare = job.format(MACOS)
+ unsigned = job.format(f"{MACOS}-6x12")
+ block = f"jobs:\n a:\n runs-on:\n - self-hosted\n - {MACOS}\n"
+ lane = (
+ "jobs:\n route:\n"
+ " uses: ./.github/workflows/darkbloom-route.yml\n"
+ " with:\n lanes: |\n"
+ " mac macos_arm64 xcode-27 ${{ inputs.mac && 1 || 0 }}\n"
+ " lin linux_arm64 ubuntu-24.04 1 4x16\n"
+ )
+ for text in (bare, unsigned, block):
+ with self.subTest(text=text):
+ self.assertNotEqual(macos_sizes({"x.yml": text})[1], [])
+ self.assertEqual(len(macos_sizes({"x.yml": lane})[1]), 2)
+ sized = job.format(f"{MACOS}-4x16")
+ self.assertEqual(macos_sizes({"x.yml": sized}), ({("x.yml", "a"): "4x16"}, []))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git ml-explore/mlx/.github/scripts/update-bypass-list.js Layr-Labs/mlx/.github/scripts/update-bypass-list.js
deleted file mode 100644
index 0f0f0817a88f71dc76f14b276d9ad510c675d594..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/scripts/update-bypass-list.js
+++ /dev/null
@@ -1,161 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * update-bypass-list.js
- *
- * Syncs a repo's PR interaction-limits bypass list with the current
- * set of eligible external contributors.
- *
- * Usage:
- * GITHUB_TOKEN=xxxx node update-bypass-list.js <owner> <repo> [--dry-run]
- */
-
-import { findEligibleContributors } from './find-eligible-contributors.js';
-
-const GITHUB_API = 'https://api.github.com';
-
-function authHeaders(token) {
- return {
- Authorization: `Bearer ${token}`,
- Accept: 'application/vnd.github+json',
- 'X-GitHub-Api-Version': '2026-03-10',
- 'User-Agent': 'update-bypass-list-script',
- 'Content-Type': 'application/json',
- };
-}
-
-function bypassListUrl(owner, repo) {
- return `${GITHUB_API}/repos/${owner}/${repo}/interaction-limits/pulls/bypass-list`;
-}
-
-async function fetchBypassList(owner, repo, token) {
- const url = bypassListUrl(owner, repo);
- const res = await fetch(url, { headers: authHeaders(token) });
-
- if (res.status === 404) {
- return new Set();
- }
-
- if (!res.ok) {
- const body = await res.text();
- throw new Error(`Failed to fetch bypass list (${res.status}): ${body}`);
- }
-
- const data = await res.json();
- const logins = data.map((user) => user?.login).filter(Boolean);
-
- return new Set(logins);
-}
-
-async function addUsersToBypassList(owner, repo, token, usernames) {
- if (usernames.length === 0) return;
-
- const res = await fetch(bypassListUrl(owner, repo), {
- method: 'PUT',
- headers: authHeaders(token),
- body: JSON.stringify({ users: usernames }),
- });
-
- if (!res.ok) {
- const body = await res.text();
- throw new Error(`Failed to add users [${usernames.join(', ')}] (${res.status}): ${body}`);
- }
-}
-
-async function removeUsersFromBypassList(owner, repo, token, usernames) {
- if (usernames.length === 0) return;
-
- const res = await fetch(bypassListUrl(owner, repo), {
- method: 'DELETE',
- headers: authHeaders(token),
- body: JSON.stringify({ users: usernames }),
- });
-
- if (!res.ok) {
- const body = await res.text();
- throw new Error(`Failed to remove users [${usernames.join(', ')}] (${res.status}): ${body}`);
- }
-}
-
-function diffLists(eligibleLogins, currentBypassLogins) {
- const toAdd = [...eligibleLogins].filter((login) => !currentBypassLogins.has(login));
- const toRemove = [...currentBypassLogins].filter((login) => !eligibleLogins.has(login));
- return { toAdd, toRemove };
-}
-
-/**
- * Update the bypass list to eligible contributors.
- *
- * @param {Object} params
- * @param {string} params.owner
- * @param {string} params.repo
- * @param {string} params.token
- * @param {boolean} [params.dryRun] - If true, only computes the diff, makes no API writes.
- */
-async function updateBypassList({ owner, repo, token, dryRun = false }) {
- console.error(`Getting eligible external contributors for ${owner}/${repo}...`);
- const eligibleLogins = new Set(await findEligibleContributors({ owner, repo, token }));
- console.error(`Found ${eligibleLogins.size} eligible user(s).`);
-
- console.error(`Fetching current bypass list...`);
- const currentBypassLogins = await fetchBypassList(owner, repo, token);
- console.error(`Current bypass list has ${currentBypassLogins.size} user(s).`);
-
- const { toAdd, toRemove } = diffLists(eligibleLogins, currentBypassLogins);
-
- console.error(`\nUsers to add (${toAdd.length}): ${toAdd.join(', ') || '(none)'}`);
- console.error(`Users to remove (${toRemove.length}): ${toRemove.join(', ') || '(none)'}`);
-
- if (dryRun) {
- console.error('\nDry run mode: no changes will be made.');
- return;
- }
-
- try {
- await addUsersToBypassList(owner, repo, token, toAdd);
- if (toAdd.length > 0) console.error(`Added ${toAdd.length} user(s) to bypass list.`);
- } catch (err) {
- console.error(`Error adding users: ${err.message}`);
- }
-
- try {
- await removeUsersFromBypassList(owner, repo, token, toRemove);
- if (toRemove.length > 0) console.error(`Removed ${toRemove.length} user(s) from bypass list.`);
- } catch (err) {
- console.error(`Error removing users: ${err.message}`);
- }
-}
-
-// ---- CLI entry point ----
-
-function isRunAsCLI() {
- return import.meta.url === `file://${process.argv[1]}`;
-}
-
-async function runCLI() {
- const args = process.argv.slice(2);
- const dryRun = args.includes('--dry-run');
- const [owner, repo] = args.filter((a) => !a.startsWith('--'));
-
- if (!owner || !repo) {
- console.error('Usage: node update-bypass-list.js <owner> <repo> [--dry-run]');
- process.exit(1);
- }
-
- const token = process.env.GITHUB_TOKEN;
- if (!token) {
- console.error('Error: set GITHUB_TOKEN environment variable with a valid GitHub token.');
- process.exit(1);
- }
-
- await updateBypassList({ owner, repo, token, dryRun });
-}
-
-if (isRunAsCLI()) {
- runCLI().catch((err) => {
- console.error('Fatal error:', err);
- process.exit(1);
- });
-}
-
-export { updateBypassList };
diff --git ml-explore/mlx/.github/workflows/build_and_test.yml Layr-Labs/mlx/.github/workflows/build_and_test.yml
index c50a39adb541a1d453c22fbdf4895ce23faf4b54..9152f611c9403b701fe4fcd7174fb4a859e86ac2 100644
--- ml-explore/mlx/.github/workflows/build_and_test.yml
+++ Layr-Labs/mlx/.github/workflows/build_and_test.yml
@@ -19,181 +19,37 @@
jobs:
check_lint:
name: Check Lint
- runs-on: ubuntu-22.04
- steps:
- - uses: actions/checkout@v7
- - uses: pre-commit/action@v3.0.1
-
- build_and_test:
- name: ${{ matrix.os }} (${{ matrix.toolkit }}, ${{ matrix.arch }})
- if: github.repository == 'ml-explore/mlx'
- needs: check_lint
- strategy:
- fail-fast: false
- matrix:
- os: ['Linux', 'Windows']
- arch: ['x86_64', 'aarch64']
- toolkit: ['cpu', 'cuda-12.6', 'cuda-12.9', 'cuda-13.0']
- exclude:
- # CUDA does not support Windows on arm.
- - os: 'Windows'
- arch: 'aarch64'
- toolkit: 'cuda-12.6'
- - os: 'Windows'
- arch: 'aarch64'
- toolkit: 'cuda-12.9'
- - os: 'Windows'
- arch: 'aarch64'
- toolkit: 'cuda-13.0'
- # CUDA 12.6 does not compile with CUTLASS on Windows.
- - os: 'Windows'
- arch: 'x86_64'
- toolkit: 'cuda-12.6'
- runs-on: |-
- ${{ case(matrix.os == 'Windows',
- case(matrix.arch == 'aarch64', 'windows-11-arm',
- startsWith(matrix.toolkit, 'cuda'), 'windows-2022-large',
- 'windows-2022'),
- case(matrix.arch == 'x86_64' && startsWith(matrix.toolkit, 'cuda'), 'gpu-t4-4-core',
- matrix.arch == 'aarch64', 'ubuntu-22.04-arm',
- 'ubuntu-22.04'))
- }}
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/setup
- id: setup
- with:
- toolkit: ${{ matrix.toolkit }}
- - uses: ./.github/actions/build
- with:
- cmake-args: ${{ steps.setup.outputs.cmake-args }}
- # For MSVC, Ninja/Release is the only config supported by ccache.
- debug: ${{ matrix.os != 'Windows' }}
- - name: Check generated Python stubs with ty
- if: matrix.os == 'Linux' && matrix.arch == 'x86_64' && matrix.toolkit == 'cpu'
- run: uvx ty check python/mlx/core
- - uses: ./.github/actions/test-linux
- if: matrix.os == 'Linux' && (matrix.toolkit == 'cpu' || matrix.arch == 'x86_64')
- - uses: ./.github/actions/test-windows
- if: matrix.os == 'Windows' && matrix.toolkit == 'cpu'
-
- mac_build:
- name: macOS (${{ matrix.macos-target }}, ${{ matrix.toolkit }})
- if: github.repository == 'ml-explore/mlx'
- strategy:
- fail-fast: false
- matrix:
- macos-target: ['14.0', '15.0', '26.2']
- toolkit: ['cpu', 'metal', 'jit']
- runs-on: macos-26-xlarge
- needs: check_lint
+ runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64]
+ timeout-minutes: 20
steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/setup
- id: setup
- with:
- toolkit: ${{ matrix.toolkit }}
- ccache-key: 'test-${{ matrix.macos-target }}'
- # Use the compile cache of metal build for all builds.
- ccache-save: ${{ matrix.toolkit == 'metal' }}
- ccache-toolkit: 'metal'
- - uses: ./.github/actions/build-macos
- with:
- cmake-args: ${{ steps.setup.outputs.cmake-args }}
- macos-target: ${{ matrix.macos-target }}
- - uses: ./.github/actions/test-macos
- if: matrix.toolkit == 'cpu'
- with:
- toolkit: 'cpu'
- - uses: actions/upload-artifact@v7
- if: matrix.toolkit != 'cpu'
- with:
- name: mlx-${{ matrix.toolkit }}-macos${{ matrix.macos-target }}
- path: |
- dist/mlx-*.whl
- build/mlx/backend/metal/kernels/mlx.metallib
- build/tests/tests
- if-no-files-found: error
-
- mac_test:
- name: Test macOS (${{ matrix.toolkit }})
- if: github.repository == 'ml-explore/mlx'
- runs-on: macos-26-xlarge
- needs: mac_build
- strategy:
- fail-fast: false
- matrix:
- toolkit: ['metal', 'jit']
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/setup
- with:
- toolkit: ${{ matrix.toolkit }}
- use-ccache: false
- - uses: actions/download-artifact@v8
- with:
- path: artifact
- pattern: mlx-${{ matrix.toolkit }}-*
- - run: ls -lhR artifact
- - uses: ./.github/actions/test-macos
- with:
- toolkit: ${{ matrix.toolkit }}
-
- array_api_test:
- name: Array API Tests (Metal)
- if: github.repository == 'ml-explore/mlx'
- needs: mac_build
- runs-on: macos-26-xlarge
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/setup
- with:
- toolkit: 'metal'
- use-ccache: false
- - uses: actions/download-artifact@v8
- with:
- path: artifact
- pattern: mlx-metal-*
- - name: Checkout array-api-tests
- uses: actions/checkout@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
- repository: data-apis/array-api-tests
- ref: 'ef5b39f1190d54dca0d9a12646033d2d123afdd5' # v2026.09.08
- submodules: 'true'
- path: 'array-api-tests'
- persist-credentials: false
- - name: Install dependencies
- shell: bash
+ python-version: "3.12"
+ - name: Install pre-commit
run: |
- uv pip install pytest-xdist -r array-api-tests/requirements.txt
- - name: Run the test suite
- shell: bash
- env:
- ARRAY_API_TESTS_MODULE: mlx.core
- ARRAY_API_TESTS_SKIP_DTYPES: 'float64,complex128'
- PYTHONWARNINGS: 'ignore::UserWarning::,ignore::DeprecationWarning::,ignore::RuntimeWarning::'
- METAL_DEBUG_ERROR_MODE: 0
- METAL_DEVICE_WRAPPER_TYPE: 1
+ python -m venv "$RUNNER_TEMP/lint-venv"
+ "$RUNNER_TEMP/lint-venv/bin/python" -m pip install pre-commit
+ "$RUNNER_TEMP/lint-venv/bin/python" -m pip freeze --local
+ echo "$RUNNER_TEMP/lint-venv/bin" >> "$GITHUB_PATH"
+ - name: Choose this job's Actions cache
run: |
- if [[ -d artifact ]] ; then
- for SUBDIR in artifact/*; do
- rm -rf build dist
- mv "$SUBDIR"/* .
- break
- done
+ if [[ ${RUNNER_NAME:-} == darkbloom-* && -z ${DARKBLOOM_CACHE_URL:-} ]]; then
+ echo "CI_ACTIONS_CACHE=off" >> "$GITHUB_ENV"
+ echo "::notice title=Actions cache::The plane gave this Darkbloom Sandbox no cache, so the cache step is skipped."
fi
- uv pip install dist/*.whl
- cd "${GITHUB_WORKSPACE}/array-api-tests"
- pytest array_api_tests -v -c pytest.ini -n 2 --max-examples=1000 --derandomize --disable-data-dependent-shapes --disable-deadline -o strict_xfail=False --xfails-file "${GITHUB_WORKSPACE}/python/tests/xp-tests/xfail.txt" --skips-file "${GITHUB_WORKSPACE}/python/tests/xp-tests/skips.txt"
-
- build_documentation:
- name: Build Documentation
- if: github.repository == 'ml-explore/mlx'
- runs-on: ubuntu-22.04
- needs: check_lint
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/build-docs
+ - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
+ if: env.CI_ACTIONS_CACHE != 'off'
+ with:
+ path: ~/.cache/pre-commit
+ key: pre-commit-3|${{ runner.os }}|${{ runner.arch }}|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }}
+ - name: Run pre-commit
+ run: pre-commit run --show-diff-on-failure --color=always --all-files
+ - name: Test the runner sizes and the resource sampler
+ # Fails when a macOS job names no signed VM size (FORKDIFF.md, Job sizes).
+ run: |
+ python3 .github/scripts/test-runner-sizes.py
+ python3 .github/scripts/test-ci-resource-sampler.py
linux_sanitizer_build_and_test:
name: Linux Sanitizer Tests (${{ matrix.sanitizer }})
@@ -204,49 +60,65 @@ matrix:
sanitizer: [ASAN, UBSAN]
# todo 12/16/2025: enable TSAN later + consider enabling ASAN for GPU backend tests.
# sanitizer: [ASAN, UBSAN, TSAN]
- runs-on: ubuntu-22.04-arm
+ runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64]
+ # ASAN takes about 22 minutes natively; a hung run must not hold a sandbox for GitHub's 6-hour default.
+ timeout-minutes: 60
steps:
- name: Checkout code
- uses: actions/checkout@v7
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- - name: Install Dependencies
+ - name: Check the native sanitizer image tools
run: |
- export DEBIAN_FRONTEND=noninteractive
- sudo apt-get update -y
- sudo apt-get install -y \
- build-essential \
- libblas-dev \
- liblapacke-dev \
- libopenblas-dev \
- cmake \
- clang \
- git
- sudo apt-get clean
- sudo rm -rf /var/lib/apt/lists/*
+ [[ "$RUNNER_NAME" == darkbloom-* ]]
+ [[ "$(uname -s)" == Linux && "$(uname -m)" == aarch64 ]]
+ cmake --version
+ cc --version
+ c++ --version
+ clang --version
+ make --version
+ git --version
- name: Linux Build and Test with ${{ matrix.sanitizer }}
run: |
bash .github/scripts/build-sanitizer-tests.sh ${{ matrix.sanitizer }}
- linux_fedora_build_cpp:
- name: Linux Fedora (${{ matrix.arch }})
+ linux_fedora_build_cpp_x86_64:
+ name: Linux Fedora (x86_64)
needs: check_lint
- strategy:
- fail-fast: false
- matrix:
- include:
- - host: ubuntu-22.04
- arch: x86_64
- - host: ubuntu-22.04-arm
- arch: aarch64
-
- runs-on: ${{ matrix.host }}
+ runs-on: ubuntu-22.04
container:
image: fedora:42
steps:
- name: Checkout code
- uses: actions/checkout@v7
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- name: CPP Build Test - No Release
run: |
bash ./.github/scripts/setup+build-cpp-linux-fedora-container.sh
+
+ linux_fedora_build_cpp_aarch64:
+ name: Linux Fedora (aarch64)
+ needs: check_lint
+ # The sandbox has no Docker: fedora_proot.py runs the same Fedora script in the archived
+ # Fedora 42 container rootfs under PRoot (built from pinned source). About 2.5 minutes.
+ runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64]
+ timeout-minutes: 45
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+
+ - name: Check the runner tools and test the Fedora PRoot helper
+ run: |
+ [[ "$RUNNER_NAME" == darkbloom-* ]]
+ [[ "$(uname -s)" == Linux && "$(uname -m)" == aarch64 ]]
+ cc --version
+ make --version
+ dpkg-deb --version
+ python3 --version
+ python3 -B .github/scripts/fedora-proot/test_fedora_proot.py
+
+ - name: CPP Build Test - No Release
+ run: |
+ python3 .github/scripts/fedora-proot/fedora_proot.py run --source "$GITHUB_WORKSPACE" --work "$RUNNER_TEMP/fedora-proot"
diff --git ml-explore/mlx/.github/workflows/codeql-native.yml Layr-Labs/mlx/.github/workflows/codeql-native.yml
new file mode 100644
index 0000000000000000000000000000000000000000..82c75ac91dcb605e07561b6b8bdb161c5dbe7a37
--- /dev/null
+++ Layr-Labs/mlx/.github/workflows/codeql-native.yml
@@ -0,0 +1,261 @@
+name: Native CodeQL
+
+# Enable only after the operator switches GitHub default setup to advanced setup.
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ schedule:
+ - cron: '15 5 * * 1'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: native-codeql-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ route:
+ if: ${{ vars.CODEQL_NATIVE == 'on' && (github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main') }}
+ uses: ./.github/workflows/darkbloom-route.yml
+ permissions: {}
+ with:
+ lanes: |
+ codeql linux_arm64 ubuntu-22.04-arm
+
+ scan:
+ needs: route
+ runs-on: ${{ fromJSON(needs.route.outputs.routes)['codeql'] }}
+ timeout-minutes: 45
+ permissions:
+ contents: read
+ steps:
+ - name: Require Linux ARM64
+ run: |
+ [[ "$(uname -s)" == Linux && "$(uname -m)" == aarch64 ]]
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - name: Check the artifact boundary
+ run: python3 .github/scripts/codeql_artifacts_test.py
+ - name: Download the qualified CodeQL 2.27.4 ARM64 bundle
+ run: |
+ set -euo pipefail
+ cd "$RUNNER_TEMP"
+ curl --fail --location --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 600 --output codeql.tar.zst https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.27.4/codeql-bundle-linux-arm64.tar.zst
+ echo '1c015b411c6e1c7f7e767eb8c9408fc6a2012d24d78b177cf22f29edc5772d10 codeql.tar.zst' | sha256sum --check
+ tar --zstd -xf codeql.tar.zst
+ "$RUNNER_TEMP/codeql/codeql" version --format=json
+ "$RUNNER_TEMP/codeql/codeql" resolve languages
+ - name: Run the existing language-default suites without a build
+ run: |
+ set -euo pipefail
+ codeql="$RUNNER_TEMP/codeql/codeql"
+ mkdir "$RUNNER_TEMP/codeql-dbs" "$RUNNER_TEMP/codeql-results"
+ for language in actions cpp python; do
+ "$codeql" database create "$RUNNER_TEMP/codeql-dbs/$language" --source-root="$GITHUB_WORKSPACE" --language="$language" --build-mode=none --threads=4 --ram=8192
+ "$codeql" database analyze "$RUNNER_TEMP/codeql-dbs/$language" --format=sarifv2.1.0 --output="$RUNNER_TEMP/codeql-results/$language.sarif" --threads=4 --ram=8192
+ done
+ - name: Bind fingerprinted SARIF to the exact workflow run
+ run: |
+ python3 .github/scripts/codeql_artifacts.py --checkout "$GITHUB_WORKSPACE" --results "$RUNNER_TEMP/codeql-results" --output "$RUNNER_TEMP/codeql-bundle"
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: codeql-native-${{ github.run_id }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/codeql-bundle/
+ if-no-files-found: error
+ retention-days: 3
+
+ publish:
+ needs: scan
+ if: ${{ vars.CODEQL_NATIVE == 'on' && needs.scan.result == 'success' }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 15
+ permissions:
+ actions: read
+ contents: read
+ security-events: write
+ steps:
+ # No checkout or repository code; native SARIF already has fingerprints.
+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
+ with:
+ name: codeql-native-${{ github.run_id }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/codeql-publish/
+ - name: Validate the exact run and bounded data-only bundle
+ id: validate
+ env:
+ BUNDLE: ${{ runner.temp }}/codeql-publish
+ run: |
+ python3 - <<'PYCODE'
+ import hashlib, json, os, re, urllib.parse
+ from pathlib import Path, PurePosixPath
+ LANGUAGES = {
+ "actions": "/language:actions",
+ "cpp": "/language:c-cpp",
+ "python": "/language:python",
+ }
+ CODEQL_VERSION = "2.27.4"
+ MAX_FILE = 16 * 1024 * 1024
+ MAX_BUNDLE = 64 * 1024 * 1024
+
+
+ def context():
+ return {
+ key: os.environ[env]
+ for key, env in {
+ "repository": "GITHUB_REPOSITORY",
+ "sha": "GITHUB_SHA",
+ "ref": "GITHUB_REF",
+ "run_id": "GITHUB_RUN_ID",
+ "attempt": "GITHUB_RUN_ATTEMPT",
+ }.items()
+ }
+
+
+ def relative_path(value):
+ if not isinstance(value, str) or not value or "\\" in value or "\x00" in value:
+ raise ValueError("invalid bundle path")
+ path = PurePosixPath(value)
+ if path.is_absolute() or any(part in ("..", ".git") for part in path.parts):
+ raise ValueError("bundle path escapes its data directory")
+ if path.as_posix() != value:
+ raise ValueError("bundle path is not canonical")
+ return path
+
+
+ def digest(path):
+ with path.open("rb") as source:
+ return hashlib.file_digest(source, "sha256").hexdigest()
+
+
+ def validate_sarif(sarif):
+ if sarif.get("version") != "2.1.0" or not sarif.get("runs"):
+ raise ValueError("invalid SARIF")
+ if not any(
+ run.get("tool", {}).get("driver", {}).get("rules") for run in sarif["runs"]
+ ):
+ raise ValueError("analysis has no rules")
+ for run in sarif["runs"]:
+ driver = run.get("tool", {}).get("driver", {})
+ if (
+ driver.get("name") != "CodeQL"
+ or driver.get("semanticVersion") != CODEQL_VERSION
+ ):
+ raise ValueError("SARIF was not produced by the qualified CodeQL version")
+ artifacts = run.get("artifacts", [])
+ for result in run.get("results", []):
+ locations = result.get("locations", [])
+ if not locations:
+ continue
+ primary = locations[0].get("physicalLocation", {})
+ location = primary.get("artifactLocation", {})
+ if "uri" not in location and "index" in location:
+ index = location["index"]
+ if type(index) is not int or not 0 <= index < len(artifacts):
+ raise ValueError("invalid artifact index")
+ location = artifacts[index]["location"]
+ uri = urllib.parse.urlsplit(location.get("uri", ""))
+ if uri.scheme or uri.netloc:
+ raise ValueError("source location is not repository relative")
+ relative_path(urllib.parse.unquote(uri.path))
+ if primary.get("region", {}).get("startLine") is not None:
+ fingerprint = result.get("partialFingerprints", {}).get(
+ "primaryLocationLineHash", ""
+ )
+ if not re.fullmatch(r"[0-9a-f]+:[1-9][0-9]*", fingerprint):
+ raise ValueError("source-line finding lacks a stable fingerprint")
+
+
+ def verify_bundle(root, expected):
+ root = root.resolve(strict=True)
+ manifest_file = root / "manifest.json"
+ if manifest_file.is_symlink() or manifest_file.stat().st_size > 256 * 1024:
+ raise ValueError("invalid manifest")
+ manifest = json.loads(manifest_file.read_text())
+ if manifest.get("context") != expected or manifest.get("version") != 1:
+ raise ValueError(
+ "scan belongs to another run, attempt, repository, ref or commit"
+ )
+ if (
+ manifest.get("codeql_version") != CODEQL_VERSION
+ or manifest.get("categories") != LANGUAGES
+ ):
+ raise ValueError("unexpected CodeQL recipe")
+ files = manifest.get("files")
+ if not isinstance(files, dict) or len(files) != 3:
+ raise ValueError("invalid file inventory")
+ required = {f"sarif/{language}.sarif" for language in LANGUAGES}
+ if not required.issubset(files):
+ raise ValueError("missing language")
+ actual = set()
+ total = 0
+ for path in root.rglob("*"):
+ if path.is_symlink():
+ raise ValueError("symlinks are not scan data")
+ if not path.is_file():
+ if path.is_dir():
+ continue
+ raise ValueError("only regular files are scan data")
+ rel = path.relative_to(root).as_posix()
+ if rel == "manifest.json":
+ continue
+ relative_path(rel)
+ if not path.resolve().is_relative_to(root):
+ raise ValueError("file escapes bundle")
+ spec = files.get(rel)
+ size = path.stat().st_size
+ if not isinstance(spec, dict) or not 0 <= size <= MAX_FILE:
+ raise ValueError("unexpected or oversized file")
+ if spec.get("size") != size or spec.get("sha256") != digest(path):
+ raise ValueError("scan data changed")
+ if rel not in required:
+ raise ValueError("only the three SARIF files may be supplied")
+ actual.add(rel)
+ total += size
+ if actual != set(files) or total > MAX_BUNDLE:
+ raise ValueError("file inventory differs or bundle exceeds limit")
+ for language in LANGUAGES:
+ sarif = json.loads((root / f"sarif/{language}.sarif").read_text())
+ validate_sarif(sarif)
+ # The official uploader falls back to event SHA/ref without a checkout.
+ # Native CodeQL already supplies every primary-line fingerprint.
+ empty_checkout = root / "empty-checkout"
+ empty_checkout.mkdir(exist_ok=True)
+ return empty_checkout
+
+
+ source = verify_bundle(Path(os.environ['BUNDLE']), context())
+ with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
+ out.write(f'checkout-path={source}\n')
+ PYCODE
+ - name: Upload actions analysis
+ uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
+ with:
+ sarif_file: ${{ runner.temp }}/codeql-publish/sarif/actions.sarif
+ checkout_path: ${{ steps.validate.outputs.checkout-path }}
+ category: /language:actions
+ ref: ${{ github.ref }}
+ sha: ${{ github.sha }}
+ wait-for-processing: true
+ - name: Upload cpp analysis
+ uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
+ with:
+ sarif_file: ${{ runner.temp }}/codeql-publish/sarif/cpp.sarif
+ checkout_path: ${{ steps.validate.outputs.checkout-path }}
+ category: /language:c-cpp
+ ref: ${{ github.ref }}
+ sha: ${{ github.sha }}
+ wait-for-processing: true
+ - name: Upload python analysis
+ uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
+ with:
+ sarif_file: ${{ runner.temp }}/codeql-publish/sarif/python.sarif
+ checkout_path: ${{ steps.validate.outputs.checkout-path }}
+ category: /language:python
+ ref: ${{ github.ref }}
+ sha: ${{ github.sha }}
+ wait-for-processing: true
diff --git ml-explore/mlx/.github/workflows/darkbloom-route.yml Layr-Labs/mlx/.github/workflows/darkbloom-route.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5f851bb394b2a61e83c3e922927265b95358654b
--- /dev/null
+++ Layr-Labs/mlx/.github/workflows/darkbloom-route.yml
@@ -0,0 +1,227 @@
+name: Darkbloom Route
+
+# Chooses a runner for each read-only CI lane: a Darkbloom Sandbox when the
+# plane grants one, otherwise the lane's fallback label. Callers run each job on
+# `fromJSON(needs.route.outputs.routes)['<lane>']`. Routing is off unless the
+# DARKBLOOM_ROUTING variable is exactly `on`; the plane can never fail this job.
+# DARKBLOOM_MACOS_LANES, when set, caps the macOS jobs one run asks for: lanes
+# are kept in the caller's order while they fit, and the others keep their
+# fallback without asking. A macOS lane can name a size. Sizes are sent only
+# when the DARKBLOOM_JOB_SHAPES variable is exactly `on`; otherwise the request
+# is the one without sizes, and a `required` lane keeps its fallback without
+# asking.
+on:
+ workflow_call:
+ inputs:
+ lanes:
+ description: >-
+ One lane per line: `<lane> <profile> <fallback-label> [count [size
+ [required]]]`. Profiles are linux_arm64 and macos_arm64. Count is the
+ number of jobs that will run (default 1); 0 keeps the fallback
+ without asking. Size, macOS only, is `<vCPUs>x<GiB>`, such as 4x24.
+ While sizes are off, a `required` lane keeps its fallback without
+ asking, and any other lane asks without its size.
+ type: string
+ required: true
+ outputs:
+ routes:
+ description: JSON object mapping every lane to its runs-on value.
+ value: ${{ jobs.select.outputs.routes }}
+
+permissions: {}
+
+jobs:
+ select:
+ name: Select Runners
+ runs-on: ubuntu-24.04
+ permissions: {}
+ timeout-minutes: 3
+ outputs:
+ routes: ${{ steps.route.outputs.routes }}
+ steps:
+ - name: Choose a Darkbloom or fallback runner for each lane
+ id: route
+ shell: bash
+ env:
+ LANES: ${{ inputs.lanes }}
+ ROUTING: ${{ vars.DARKBLOOM_ROUTING }}
+ MACOS_LANES: ${{ vars.DARKBLOOM_MACOS_LANES }}
+ JOB_SHAPES: ${{ vars.DARKBLOOM_JOB_SHAPES }}
+ PLANE_URL: ${{ vars.DARKBLOOM_SANDBOX_URL }}
+ REPOSITORY: ${{ github.repository }}
+ EVENT_NAME: ${{ github.event_name }}
+ HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}
+ RUN_ID: ${{ github.run_id }}
+ RUN_ATTEMPT: ${{ github.run_attempt }}
+ run: |
+ set -euo pipefail
+
+ # The only labels a lane can receive besides its fallback. A plane
+ # decision is used only when it repeats its profile's array exactly.
+ # For a lane sent with a size, the size qualifies the last label
+ # (darkbloom-macos-arm64-4x24).
+ profiles='{"linux_arm64":["self-hosted","linux","ARM64","darkbloom-linux-arm64"],"macos_arm64":["self-hosted","macOS","ARM64","darkbloom-macos-arm64"]}'
+ # Plane text is untrusted: keep it short, on one line, and free of
+ # Markdown, HTML and workflow-command syntax before printing it.
+ clean='def clean: tostring | gsub("[^A-Za-z0-9 _.,:;/=+()-]"; "?") | .[0:120];'
+
+ configuration_error() {
+ echo "::error title=Darkbloom route configuration::$1"
+ exit 1
+ }
+
+ configured='[]'
+ seen=' '
+ while read -r lane profile fallback count shape required extra; do
+ [ -n "$lane" ] || continue
+ count=${count:-1}
+ [ -z "$extra" ] || configuration_error "lane $lane has more than six fields"
+ [[ $lane =~ ^[A-Za-z0-9_-]+$ ]] || configuration_error "invalid lane name: $lane"
+ jq -e --arg profile "$profile" 'has($profile)' <<<"$profiles" >/dev/null \
+ || configuration_error "lane $lane has unknown profile: $profile"
+ [[ $fallback =~ ^[A-Za-z0-9._-]+$ ]] \
+ || configuration_error "lane $lane has invalid fallback label: $fallback"
+ [[ $count =~ ^(0|[1-9][0-9]?)$ ]] || configuration_error "lane $lane has invalid count: $count"
+ # The plane's size grammar: <vCPUs>x<GiB>, lowercase decimal, no leading zeros.
+ if [ -n "$shape" ]; then
+ [[ $shape =~ ^[1-9][0-9]*x[1-9][0-9]*$ ]] \
+ || configuration_error "lane $lane has invalid size: $shape (use <vCPUs>x<GiB>, such as 4x24)"
+ [ "$profile" = macos_arm64 ] || configuration_error "lane $lane has a size, but sizes are macOS only"
+ fi
+ [ -z "$required" ] || [ "$required" = required ] \
+ || configuration_error "lane $lane has an unknown sixth field: $required"
+ case $seen in *" $lane "*) configuration_error "lane $lane is listed twice" ;; esac
+ seen="$seen$lane "
+ configured=$(jq -c --arg lane "$lane" --arg profile "$profile" --arg fallback "$fallback" \
+ --argjson count "$count" --arg shape "$shape" --arg required "$required" \
+ '. + [{$lane, $profile, $fallback, $count,
+ shape: (if $shape == "" then null else $shape end), required: ($required != ""), held: false}]' \
+ <<<"$configured")
+ done <<<"${LANES:-}"
+ [ "$configured" != '[]' ] || configuration_error "no lanes are configured"
+
+ # Job sizes are a repository setting, off unless exactly `on`. While
+ # they are off, no size is sent, so the request is the request of a
+ # lane table without sizes. A `required` lane is then held: it keeps
+ # its fallback without asking and takes no place under the macOS cap.
+ shapes_note=""
+ if jq -e 'any(.[]; .shape != null)' <<<"$configured" >/dev/null; then
+ if [ "${JOB_SHAPES:-}" = on ]; then
+ shapes_note=" Job sizes are on: DARKBLOOM_JOB_SHAPES is 'on'."
+ else
+ shapes_note=" Job sizes are off: DARKBLOOM_JOB_SHAPES is not 'on'. No size was requested."
+ configured=$(jq -c 'map(.held = .required | .shape = null)' <<<"$configured")
+ fi
+ fi
+
+ # The macOS cap is a repository setting, not caller configuration: a
+ # value other than 0 to 99 asks for no macOS lane rather than failing.
+ macos_cap=${MACOS_LANES:-}
+ cap_note=""
+ if [ -n "$macos_cap" ] && ! [[ $macos_cap =~ ^(0|[1-9][0-9]?)$ ]]; then
+ cap_note=" DARKBLOOM_MACOS_LANES is not a number from 0 to 99, so no macOS lane was requested."
+ macos_cap=0
+ fi
+ configured=$(jq -c --arg cap "$macos_cap" '
+ reduce .[] as $entry ({used: 0, lanes: []};
+ if $entry.held then .lanes += [$entry + {capped: false}]
+ elif $cap != "" and $entry.profile == "macos_arm64" and $entry.count > 0
+ and .used + $entry.count > ($cap | tonumber)
+ then .lanes += [$entry + {capped: true}]
+ else .used += (if $entry.profile == "macos_arm64" then $entry.count else 0 end)
+ | .lanes += [$entry + {capped: false}]
+ end) | .lanes' <<<"$configured")
+ # A lane without a size is exactly {lane, profile, count}.
+ requested=$(jq -c '[.[] | select(.count > 0 and (.capped | not) and (.held | not))
+ | {lane, profile, count} + (if .shape != null then {shape} else {} end)]' <<<"$configured")
+
+ plane_url=${PLANE_URL:-https://api-sandbox.darkbloom.dev}
+ body=$(mktemp)
+ trap 'rm -f "$body"' EXIT
+ reply=/dev/null
+ fallback_reason=""
+ if [ "${ROUTING:-}" != on ]; then
+ fallback_reason="routing is off"
+ note="Routing is off: DARKBLOOM_ROUTING is not 'on'. No request was sent."
+ elif [[ ${EVENT_NAME:-} == pull_request* && ${HEAD_REPOSITORY:-} != "${REPOSITORY:-}" ]]; then
+ fallback_reason="pull request from a fork"
+ note="Pull requests from forks keep their fallback runners. No request was sent."
+ elif [ "$requested" = '[]' ]; then
+ note="No lane has jobs to run. No request was sent."
+ elif [[ $plane_url != https://* ]]; then
+ fallback_reason="plane URL is not https"
+ note="DARKBLOOM_SANDBOX_URL must start with https://. No request was sent."
+ elif ! [[ ${RUN_ID:-} =~ ^[0-9]+$ && ${RUN_ATTEMPT:-} =~ ^[0-9]+$ ]]; then
+ fallback_reason="run identity is unavailable"
+ note="The run ID or attempt is not numeric. No request was sent."
+ else
+ request=$(jq -n -c --arg repository "$REPOSITORY" --argjson run_id "$RUN_ID" \
+ --argjson run_attempt "$RUN_ATTEMPT" --argjson lanes "$requested" \
+ '{$repository, $run_id, $run_attempt, $lanes}')
+ # The request names only the repository, the run and the lanes.
+ echo "Request: $request"
+ # One attempt plus at most one retry after a transport failure,
+ # timeout or transient status; each attempt is bounded to 5 seconds.
+ for attempt in 1 2; do
+ status=$(curl --disable --silent --show-error --proto '=https' --max-time 5 \
+ --max-filesize 65536 --user-agent darkbloom-route/1 --request POST \
+ --header 'Content-Type: application/json' --header 'Accept: application/json' \
+ --data-binary @- --output "$body" --write-out '%{http_code}' \
+ "${plane_url%/}/v1/ci/routes" <<<"$request") || status=000
+ case $status in
+ 000|408|429|5??) [ "$attempt" = 2 ] || sleep 1 ;;
+ *) break ;;
+ esac
+ done
+ if [ "$status" != 200 ]; then
+ fallback_reason="plane request failed (HTTP $status)"
+ elif ! jq -e -s 'length == 1 and (.[0] | type == "object"
+ and (.route_id | type == "string" and length > 0)
+ and (.expires_at | type == "string")
+ and (.lanes | type == "object"))' "$body" >/dev/null 2>&1; then
+ fallback_reason="plane reply is malformed"
+ else
+ reply=$body
+ fi
+ if [ -n "$fallback_reason" ]; then
+ note="Asked $plane_url: $fallback_reason. Requested lanes keep their fallback runners."
+ else
+ note=$(jq -r --arg url "$plane_url" \
+ "$clean"'"Asked \($url): route \(.route_id | clean), expires \(.expires_at | clean)."' "$body")
+ fi
+ fi
+
+ decisions=$(jq -n -c --argjson configured "$configured" --argjson profiles "$profiles" \
+ --arg fallback_reason "$fallback_reason" --slurpfile reply "$reply" "$clean"'
+ ($reply[0].lanes // {}) as $plane_decisions
+ | [ $configured[]
+ | ($plane_decisions[.lane] | if type == "object" then . else {} end) as $decision
+ | (.shape as $shape | $profiles[.profile]
+ | if $shape == null then . else .[:-1] + [.[-1] + "-" + $shape] end) as $labels
+ | if .count == 0 then .target = "fallback" | .reason = "not requested"
+ elif $fallback_reason != "" then .target = "fallback" | .reason = $fallback_reason
+ elif .held then .target = "fallback" | .reason = "needs its size, and job sizes are off (DARKBLOOM_JOB_SHAPES)"
+ elif .capped then .target = "fallback" | .reason = "over the macOS lane cap (DARKBLOOM_MACOS_LANES)"
+ elif $decision.target == "darkbloom" and $decision.runs_on == $labels
+ then .target = "darkbloom" | .reason = "granted"
+ elif $decision.target == "fallback"
+ then .target = "fallback" | .reason = "plane: " + ($decision.reason // "no reason" | clean)
+ else .target = "fallback" | .reason = "plane decision is missing or invalid"
+ end
+ | .runs_on = (if .target == "darkbloom" then $decision.runs_on else .fallback end) ]')
+ routes=$(jq -c 'map({key: .lane, value: .runs_on}) | from_entries' <<<"$decisions")
+ echo "routes=$routes" >> "$GITHUB_OUTPUT"
+
+ note="$note$cap_note$shapes_note"
+ echo "$note"
+ jq -r '.[] | (if .shape == null then "" else "; size \(.shape)" end) as $size
+ | "\(.lane): \(.runs_on | if type == "array" then join(",") else . end) (\(.reason)\($size))"' <<<"$decisions"
+ {
+ echo "### Darkbloom runner routing"
+ echo
+ echo "$note"
+ echo
+ echo "| Lane | Profile | Jobs | Size | Runner | Decision |"
+ echo "| --- | --- | --- | --- | --- | --- |"
+ jq -r '.[] | "| `\(.lane)` | \(.profile) | \(.count) | \(.shape // "-") | `\(.runs_on | if type == "array" then join(", ") else . end)` | \(.target): \(.reason) |"' <<<"$decisions"
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git ml-explore/mlx/.github/workflows/darkbloom-watchdog.yml Layr-Labs/mlx/.github/workflows/darkbloom-watchdog.yml
new file mode 100644
index 0000000000000000000000000000000000000000..7f956baae416761a384b932b43784aa8cd5c6e89
--- /dev/null
+++ Layr-Labs/mlx/.github/workflows/darkbloom-watchdog.yml
@@ -0,0 +1,304 @@
+name: Darkbloom Watchdog
+
+# Rescues runs stranded on Darkbloom: a job routed to Darkbloom can only run
+# on a Darkbloom runner, so when one waits queued with no runner for
+# DARKBLOOM_WATCHDOG_MINUTES (default 30) since its own creation, and no
+# Darkbloom job of the run got a runner within that time, this cancels the
+# run and re-runs the route job and its dependents (the whole run when the
+# cancel interrupted other jobs), also when other Darkbloom jobs of the run
+# ran or still run. The new
+# attempt's route job then keeps its fallback labels: the plane unreachable,
+# or answering run_fallback_forced. It needs only GitHub and this
+# repository's GITHUB_TOKEN, so it works while Darkbloom's plane is down.
+# What it cannot see, it does not guess: GitHub shows no sign of a job that
+# waits by design, so a payer at its concurrency or resource limit (a sized
+# job waiting for room in its grant) looks like a fault to it once no runner
+# came for the whole wait. Set DARKBLOOM_WATCHDOG_MINUTES above such waits.
+# Darkbloom's own watchdog acts first (after 15 minutes, on the plane's
+# evidence) and marks the run with a `Darkbloom watchdog` check run, which
+# this leaves alone for 20 minutes. A run is rescued at most once, by either:
+# stranded again, it is only cancelled. Off when the repository variable
+# DARKBLOOM_WATCHDOG is `off`.
+#
+# Copy this file into the repository as .github/workflows/darkbloom-watchdog.yml,
+# beside darkbloom-route.yml, unchanged. See README.md.
+on:
+ schedule:
+ - cron: '*/10 * * * *'
+ workflow_dispatch:
+
+permissions: {}
+
+concurrency:
+ group: darkbloom-watchdog
+ cancel-in-progress: false
+
+jobs:
+ watch:
+ name: Rescue Stranded Runs
+ runs-on: ubuntu-24.04
+ # A minute of jitter, then at most two rescues of three minutes each.
+ timeout-minutes: 12
+ permissions:
+ actions: write
+ checks: write
+ steps:
+ - name: Cancel and re-run runs whose Darkbloom jobs are stranded
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ API_URL: ${{ github.api_url }}
+ REPOSITORY: ${{ github.repository }}
+ SELF_RUN_ID: ${{ github.run_id }}
+ WATCHDOG: ${{ vars.DARKBLOOM_WATCHDOG }}
+ MINUTES: ${{ vars.DARKBLOOM_WATCHDOG_MINUTES }}
+ ROUTE_JOB: ${{ vars.DARKBLOOM_ROUTE_JOB }}
+ APP_SLUG: ${{ vars.DARKBLOOM_APP_SLUG }}
+ run: |
+ set -euo pipefail
+ export LC_ALL=C
+ summary() { echo "$1"; echo "$1" >> "$GITHUB_STEP_SUMMARY"; }
+ configuration_error() {
+ echo "::error title=Darkbloom watchdog configuration::$1"
+ exit 1
+ }
+
+ if [ "${WATCHDOG:-}" = off ]; then
+ summary "The Darkbloom watchdog is off: DARKBLOOM_WATCHDOG is 'off'."
+ exit 0
+ fi
+ minutes=${MINUTES:-30}
+ if ! [[ $minutes =~ ^[0-9]{1,4}$ ]] || ((10#$minutes < 15 || 10#$minutes > 1440)); then
+ configuration_error "DARKBLOOM_WATCHDOG_MINUTES must be 15 to 1440"
+ fi
+ minutes=$((10#$minutes))
+ route_job=${ROUTE_JOB:-Select Runners}
+ api=${API_URL:-https://api.github.com}
+ [[ $api == https://* ]] || configuration_error "the API URL must start with https://"
+ [[ ${REPOSITORY:-} =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || configuration_error "no repository"
+ # A random delay, so that repositories and Darkbloom's rounds do not
+ # move in step. Tests set these.
+ jitter=${JITTER_SECONDS:-60}
+ poll=${POLL_SECONDS:-10}
+ cancel_wait=${CANCEL_WAIT_SECONDS:-120}
+ app=${APP_SLUG:-darkbloom-sandbox}
+ max_rescues=2
+ rerun_title="Cancelled to re-run on the fallback runners"
+ cancel_title="Cancelled: rescued once already, not re-run"
+ sleep $((RANDOM % (jitter + 1)))
+
+ tmp=$(mktemp -d)
+ trap 'rm -rf "$tmp"' EXIT
+ # One API call: sets STATUS (000 when the transport failed); the
+ # body is in $tmp/body.
+ request() { # method path [JSON body]
+ local method=$1 path=$2
+ if [ $# -ge 3 ]; then
+ set -- --header 'Content-Type: application/json' --data-binary "$3"
+ else
+ set --
+ fi
+ STATUS=$(curl --disable --silent --show-error --proto '=https' --max-time 20 \
+ --max-filesize 16777216 --user-agent darkbloom-watchdog/1 --request "$method" "$@" \
+ --header "Authorization: Bearer $GH_TOKEN" --header 'Accept: application/vnd.github+json' \
+ --header 'X-GitHub-Api-Version: 2022-11-28' --output "$tmp/body" --write-out '%{http_code}' \
+ "${api%/}/repos/$REPOSITORY/$path") || STATUS=000
+ }
+ # Large JSON never goes on jq's command line: one argument is at
+ # most 128 KiB on Linux, and a day of runs is more ("Argument list
+ # too long"). Pages go through files, the rest through stdin.
+ # The repository's runs with `status` created in the last day, as
+ # one JSON array, up to 1,000; fails when GitHub does.
+ runs_with() { # status
+ local page=1 count
+ : >"$tmp/run-pages"
+ while :; do
+ request GET "actions/runs?status=$1&created=%3E%3D$since&per_page=100&page=$page"
+ [ "$STATUS" = 200 ] || return 1
+ jq -c '.workflow_runs // []' "$tmp/body" >>"$tmp/run-pages"
+ count=$(jq '.workflow_runs // [] | length' "$tmp/body")
+ [ "$count" = 100 ] && [ "$page" -lt 10 ] || break
+ page=$((page + 1))
+ done
+ jq -cs 'add // []' "$tmp/run-pages"
+ }
+ # The run's jobs (filter latest or all) as one JSON array, up to
+ # 1,000; fails when GitHub does.
+ jobs_of() { # run filter
+ local page=1 count
+ : >"$tmp/job-pages"
+ while :; do
+ request GET "actions/runs/$1/jobs?filter=$2&per_page=100&page=$page"
+ [ "$STATUS" = 200 ] || return 1
+ jq -c '.jobs // []' "$tmp/body" >>"$tmp/job-pages"
+ count=$(jq '.jobs // [] | length' "$tmp/body")
+ [ "$count" = 100 ] && [ "$page" -lt 10 ] || break
+ page=$((page + 1))
+ done
+ jq -cs 'add // []' "$tmp/job-pages"
+ }
+ # Waits up to $2 seconds for GitHub to report the run completed.
+ completed() { # run seconds
+ local deadline=$((SECONDS + $2))
+ while :; do
+ request GET "actions/runs/$1"
+ [ "$STATUS" = 200 ] && [ "$(jq -r .status "$tmp/body")" = completed ] && return 0
+ [ "$SECONDS" -lt "$deadline" ] || return 1
+ sleep "$poll"
+ done
+ }
+ # Darkbloom's labels (self-hosted beside a darkbloom-* label), a
+ # GitHub time in Unix seconds (null when absent), a name safe to
+ # print (no workflow commands, no markup), and a marker check run.
+ # shellcheck disable=SC2016 # jq's variables
+ defs='def darkbloom: (.labels // [] | map(ascii_downcase))
+ | index("self-hosted") != null and any(.[]; startswith("darkbloom-"));
+ def at: if type == "string" then sub("[.][0-9]+Z$"; "Z") | fromdateiso8601 else null end;
+ def clean: tostring | gsub("[^A-Za-z0-9 ._()/,+-]"; "?") | .[0:80];
+ def marker($id): .check_runs[]? | select(.name == "Darkbloom watchdog" and .external_id == $id);'
+
+ # Re-runs run $1 after its cancel: the route job and its dependents,
+ # or the whole run when it has no single route job or the cancel
+ # interrupted a job that started before the route job completed (a
+ # route job's rerun would leave it cancelled). Prints what it re-ran.
+ rerun() { # run attempt
+ local jobs route
+ jobs=$(jobs_of "$1" latest) || return 1
+ route=$(jq -r --arg name "$route_job" --argjson attempt "$2" "$defs"'
+ [.[] | select((.name == $name or (.name | endswith(" / " + $name))) and .conclusion == "success")] as $r
+ | if ($r | length) != 1 then empty
+ else ($r[0].completed_at | at // 0) as $done
+ | if any(.[]; .run_attempt == $attempt and .conclusion == "cancelled" and (.runner_id // 0) != 0
+ and ((.started_at | at) // 1e12) < $done) then empty else $r[0].id end
+ end' <<<"$jobs")
+ if [ -n "$route" ]; then
+ request POST "actions/jobs/$route/rerun"
+ what="its route job and dependents"
+ else
+ request POST "actions/runs/$1/rerun"
+ what="the whole run"
+ fi
+ case $STATUS in
+ 201) echo "$what" ;;
+ 403) echo "nothing: it is re-running already" ;;
+ *) return 1 ;;
+ esac
+ }
+
+ now=$(date -u +%s)
+ since=$(date -u -d "@$((now - 86400))" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \
+ || date -u -r "$((now - 86400))" +%Y-%m-%dT%H:%M:%SZ)
+ before=$((now - minutes * 60))
+ failed=0
+ acted=0
+ : >"$tmp/runs"
+ for status in in_progress queued; do
+ runs_with "$status" >>"$tmp/runs" || { echo "::warning::Listing $status runs failed (HTTP $STATUS)"; exit 1; }
+ done
+ runs=$(jq -cs 'add // []' "$tmp/runs")
+
+ # Rescues this workflow cancelled and did not re-run (cut short
+ # between the two): cancelled runs changed in the last half hour
+ # whose current attempt carries this workflow's own marker.
+ cancelled=$(runs_with cancelled) || { echo "::warning::Listing cancelled runs failed (HTTP $STATUS)"; exit 1; }
+ resumable=$(jq -r --arg self "${SELF_RUN_ID:-0}" --argjson recent "$((now - 1800))" "$defs"'
+ .[] | select((.id | tostring) != $self and ((.updated_at | at) // 0) >= $recent)
+ | "\(.id) \(.run_attempt) \(.head_sha)"' <<<"$cancelled")
+ while read -r run attempt sha; do
+ [ -n "$run" ] || continue
+ request GET "commits/$sha/check-runs?check_name=Darkbloom%20watchdog&filter=all&per_page=100"
+ [ "$STATUS" = 200 ] || continue
+ jq -e --arg id "run:$run:$attempt" --arg title "$rerun_title" "$defs"'[marker($id)
+ | select(.app.slug == "github-actions" and .output.title == $title)] | length > 0' \
+ "$tmp/body" >/dev/null || continue
+ acted=1
+ if what=$(rerun "$run" "$attempt"); then
+ summary "Run $run attempt $attempt: resumed its rescue, re-ran $what."
+ else
+ echo "::warning::Run $run: re-running it failed (HTTP $STATUS)"
+ failed=1
+ fi
+ done <<<"$resumable"
+
+ # Runs whose attempt started before the wait, other than this.
+ candidates=$(jq -r --arg self "${SELF_RUN_ID:-0}" --argjson before "$before" "$defs"'
+ unique_by(.id) | .[] | select((.id | tostring) != $self)
+ | select((.run_started_at // .created_at | at) as $t | $t != null and $t <= $before)
+ | "\(.id) \(.run_attempt) \(.head_sha)"' <<<"$runs")
+ rescues=0
+ while read -r run attempt sha; do
+ [ -n "$run" ] || continue
+ jobs=$(jobs_of "$run" latest) || { echo "::warning::Run $run: listing its jobs failed"; failed=1; continue; }
+ # Stranded: a Darkbloom job of this attempt queued with no runner
+ # since before the wait, timed from its own creation (GitHub
+ # creates a job behind `needs:` once those are done), while no
+ # Darkbloom job of the run got a runner within the wait (runners
+ # still coming: a payer at its limit). Other Darkbloom jobs of the
+ # run that ran, or run still, do not hold it back.
+ stranded=$(jq -r --argjson before "$before" --argjson attempt "$attempt" "$defs"'
+ if any(.[]; darkbloom and (.runner_id // 0) != 0 and ((.started_at | at) // 0) > $before) then ""
+ else [.[] | select(.run_attempt == $attempt and .status == "queued" and (.runner_id // 0) == 0
+ and darkbloom and ((.created_at | at) // 1e12) <= $before) | .name | clean]
+ | join(", ") end' <<<"$jobs")
+ [ -n "$stranded" ] || continue
+ request GET "commits/$sha/check-runs?check_name=Darkbloom%20watchdog&filter=all&per_page=100"
+ [ "$STATUS" = 200 ] || { echo "::warning::Run $run: reading its checks failed (HTTP $STATUS)"; failed=1; continue; }
+ # Darkbloom's watchdog (its App) marked this attempt within 20
+ # minutes: it is rescuing it.
+ if jq -e --arg id "run:$run:$attempt" --arg app "$app" --argjson since "$((now - 1200))" "$defs"'
+ [marker($id) | select(.app.slug == $app and ((.started_at // .completed_at | at) // 0) >= $since)]
+ | length > 0' "$tmp/body" >/dev/null; then
+ summary "Run $run attempt $attempt: Darkbloom's watchdog is rescuing it."
+ continue
+ fi
+ # Rescued before, by either watchdog: a marker of an earlier
+ # attempt, or an earlier attempt's Darkbloom job cancelled with no
+ # runner after the whole wait. Then it is only cancelled.
+ marked=$(jq -r --arg run "run:$run:" --argjson attempt "$attempt" '[.check_runs[]?
+ | select(.name == "Darkbloom watchdog" and (.external_id // "" | startswith($run)))
+ | .external_id | ltrimstr($run) | tonumber? | select(. < $attempt)] | length > 0' "$tmp/body")
+ all=$(jobs_of "$run" all) || { echo "::warning::Run $run: listing its attempts failed"; failed=1; continue; }
+ once=$(jq -r --argjson attempt "$attempt" --argjson wait "$((minutes * 60))" --argjson marked "$marked" "$defs"'
+ $marked or any(.[]; .run_attempt < $attempt and .conclusion == "cancelled" and (.runner_id // 0) == 0
+ and darkbloom and ((.completed_at | at) // 0) - ((.created_at | at) // 1e12) >= $wait)' <<<"$all")
+ if [ "$rescues" -ge "$max_rescues" ]; then
+ summary "Run $run attempt $attempt: stranded; left for the next round ($max_rescues rescues a round)."
+ continue
+ fi
+ # Nobody re-ran it since it was listed.
+ request GET "actions/runs/$run"
+ [ "$STATUS" = 200 ] && [ "$(jq -r .run_attempt "$tmp/body")" = "$attempt" ] || continue
+ rescues=$((rescues + 1))
+ acted=1
+ # Marked first: a rescue cut short after the cancel resumes next time.
+ title=$rerun_title
+ [ "$once" != true ] || title=$cancel_title
+ mark=$(jq -cn --arg sha "$sha" --arg id "run:$run:$attempt" --arg title "$title" --arg jobs "$stranded" '{
+ name: "Darkbloom watchdog", head_sha: $sha, external_id: $id, status: "completed",
+ conclusion: "neutral", output: {title: $title,
+ summary: "A Darkbloom job of this run attempt got no runner (\($jobs)): the repository watchdog cancelled it."}}')
+ request POST check-runs "$mark"
+ [ "$STATUS" = 201 ] || { echo "::warning::Run $run: marking it failed (HTTP $STATUS)"; failed=1; continue; }
+ request POST "actions/runs/$run/cancel"
+ case $STATUS in
+ 202) ;;
+ 409) summary "Run $run attempt $attempt: someone else is cancelling it; not re-run."; continue ;;
+ *) echo "::warning::Run $run: cancelling it failed (HTTP $STATUS)"; failed=1; continue ;;
+ esac
+ if ! completed "$run" "$cancel_wait"; then
+ request POST "actions/runs/$run/force-cancel"
+ completed "$run" 60 || { echo "::warning::Run $run: GitHub did not cancel it"; failed=1; continue; }
+ fi
+ if [ "$once" = true ]; then
+ summary "Run $run attempt $attempt: cancelled ($stranded waited ${minutes}+ minutes for a Darkbloom runner); it was rescued once already, so it is not re-run again."
+ continue
+ fi
+ if what=$(rerun "$run" "$attempt"); then
+ summary "Run $run attempt $attempt: $stranded waited ${minutes}+ minutes for a Darkbloom runner; cancelled and re-ran $what on the fallback runners."
+ else
+ echo "::warning::Run $run: re-running it failed (HTTP $STATUS)"
+ failed=1
+ fi
+ done <<<"$candidates"
+ [ "$acted" = 1 ] || summary "No run is stranded on Darkbloom."
+ exit "$failed"
diff --git ml-explore/mlx/.github/workflows/documentation.yml Layr-Labs/mlx/.github/workflows/documentation.yml
deleted file mode 100644
index fad1647999807332410edc20de0a6254dd617b5b..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/workflows/documentation.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-name: Documentation
-
-on:
- workflow_dispatch:
-
-permissions:
- contents: read
-
-jobs:
- build:
- runs-on: ubuntu-22.04
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/build-docs
-
- deploy:
- needs: build
- permissions:
- pages: write
- id-token: write
- runs-on: ubuntu-latest
- environment:
- name: github-pages
- url: ${{ steps.deployment.outputs.page_url }}
- steps:
- - name: Deploy to GitHub Pages
- id: deployment
- uses: actions/deploy-pages@v5
diff --git ml-explore/mlx/.github/workflows/release.yml Layr-Labs/mlx/.github/workflows/release.yml
deleted file mode 100644
index 0a03b429ac9dd649b8f7fda836eedd264927385f..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/workflows/release.yml
+++ /dev/null
@@ -1,321 +0,0 @@
-name: 'Release build'
-description: 'Build Python wheels for nightly or offical releases'
-
-on:
- push:
- tags:
- - 'v*'
- workflow_dispatch:
- inputs:
- publish:
- description: 'Publish to PyPI'
- required: false
- type: boolean
- dev-release:
- description: 'Development release (DEV_RELEASE=1)'
- required: false
- type: boolean
- schedule:
- - cron: 33 6 * * *
-
-# In jobs we must use |*publish| instead of |inputs.publish| because we can not
-# set default value for workflow_dispatch inputs reliably.
-env:
- publish: &publish ${{ inputs.publish || github.event_name == 'push' }}
- pypi-env: &pypi-env ${{ (inputs.publish || github.event_name == 'push') && 'pypi' || 'dry-run' }}
-
-permissions:
- contents: read
-
-jobs:
- build_documentation:
- name: Build documentation
- if: github.repository == 'ml-explore/mlx'
- runs-on: ubuntu-22.04
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/build-docs
-
- deploy_documentation:
- name: Deploy documentation
- if: *publish
- needs: build_documentation
- permissions:
- pages: write
- id-token: write
- runs-on: ubuntu-latest
- environment:
- name: github-pages
- url: ${{ steps.deployment.outputs.page_url }}
- steps:
- - name: Deploy to GitHub Pages
- id: deployment
- uses: actions/deploy-pages@v5
-
- build_frontend:
- name: ${{ matrix.os }} (python-${{ matrix.python-version }}, ${{ matrix.arch }})
- strategy:
- matrix:
- os: ['Linux', 'Windows']
- arch: ['x86_64', 'aarch64']
- python-version: &pyver ['3.10', '3.11', '3.12', '3.13', '3.13t', '3.14', '3.14t', '3.15', '3.15t']
- # There is no cp310 binary for Windows on arm.
- exclude:
- - os: 'Windows'
- arch: 'aarch64'
- python-version: '3.10'
- runs-on: |-
- ${{ case(matrix.os == 'Windows',
- case(matrix.arch == 'aarch64', 'windows-11-arm',
- 'windows-2022'),
- case(matrix.arch == 'aarch64', 'ubuntu-22.04-arm',
- 'ubuntu-22.04'))
- }}
- env: &build-env
- PYPI_RELEASE: 1
- DEV_RELEASE: ${{ inputs.dev-release && 1 || 0 }}
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/setup
- id: setup
- with:
- python-version: ${{ matrix.python-version }}
- ccache-key: 'release'
- ccache-save: false
- - uses: ./.github/actions/build-wheel
- with:
- cmake-args: ${{ steps.setup.outputs.cmake-args }}
- build-backend: false
- - run: unzip -l wheelhouse/*.whl
- - uses: actions/upload-artifact@v7
- with:
- name: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ matrix.python-version }}
- path: wheelhouse/mlx-*.whl
- if-no-files-found: error
-
- build_backend:
- name: ${{ matrix.os }} (${{ matrix.toolkit }}, ${{ matrix.arch }})
- if: github.repository == 'ml-explore/mlx'
- strategy:
- matrix:
- os: ['Linux', 'Windows']
- arch: ['x86_64', 'aarch64']
- toolkit: ['cpu', 'cuda-12.9', 'cuda-13.0']
- exclude:
- # CUDA does not support Windows on arm.
- - os: 'Windows'
- arch: 'aarch64'
- toolkit: 'cuda-12.9'
- - os: 'Windows'
- arch: 'aarch64'
- toolkit: 'cuda-13.0'
- runs-on: |-
- ${{ case(matrix.os == 'Windows',
- case(matrix.arch == 'aarch64', 'windows-11-arm',
- 'windows-2022-large'),
- case(matrix.arch == 'aarch64', 'ubuntu-22-large-arm',
- 'ubuntu-22-large'))
- }}
- env: *build-env
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/setup
- id: setup
- with:
- toolkit: ${{ matrix.toolkit }}
- ccache-key: 'release'
- - uses: ./.github/actions/build-wheel
- with:
- cmake-args: ${{ steps.setup.outputs.cmake-args }}
- build-frontend: false
- - run: unzip -l wheelhouse/*.whl
- - uses: actions/upload-artifact@v7
- with:
- name: backend-${{ matrix.toolkit }}-${{ runner.os }}-${{ runner.arch }}
- path: wheelhouse/*.whl
- if-no-files-found: ignore
-
- build_mac_wheels:
- name: macOS (python-${{ matrix.python-version }})
- if: github.repository == 'ml-explore/mlx'
- strategy:
- matrix:
- python-version: *pyver
- runs-on: 'macos-26-xlarge'
- env: *build-env
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/setup
- id: setup
- with:
- toolkit: 'metal'
- python-version: ${{ matrix.python-version }}
- ccache-key: 'release'
- ccache-save: ${{ matrix.python-version == '3.10' }}
- - name: Build macOS 14 package
- uses: ./.github/actions/build-wheel
- with:
- macos-target: '14.0'
- cmake-args: ${{ steps.setup.outputs.cmake-args }}
- build-backend: ${{ matrix.python-version == '3.10' }}
- - name: Build macOS 15 package
- uses: ./.github/actions/build-wheel
- with:
- macos-target: '15.0'
- cmake-args: ${{ steps.setup.outputs.cmake-args }}
- build-backend: ${{ matrix.python-version == '3.10' }}
- - name: Build macOS 26 package
- uses: ./.github/actions/build-wheel
- with:
- macos-target: '26.2'
- cmake-args: ${{ steps.setup.outputs.cmake-args }}
- build-backend: ${{ matrix.python-version == '3.10' }}
- - name: Display content of the wheels
- run: for WHEEL in wheelhouse/*.whl; do unzip -l $WHEEL; echo; done
- - name: Upload frontend packages
- uses: actions/upload-artifact@v7
- with:
- name: frontend-${{ runner.os }}-${{ runner.arch }}-py${{ matrix.python-version }}
- path: wheelhouse/mlx-*.whl
- if-no-files-found: error
- - name: Upload backend packages
- if: matrix.python-version == '3.10'
- uses: actions/upload-artifact@v7
- with:
- name: backend-metal-${{ runner.os }}-${{ runner.arch }}
- path: wheelhouse/mlx_metal-*.whl
- if-no-files-found: error
-
- test_wheel:
- name: Test (${{ matrix.os }}, ${{ matrix.toolkit }}, ${{ matrix.arch }})
- if: github.repository == 'ml-explore/mlx'
- needs: [build_frontend, build_backend, build_mac_wheels]
- strategy:
- matrix:
- os: ['Linux', 'Windows']
- arch: ['aarch64']
- toolkit: ['cpu']
- include:
- - os: 'Linux'
- arch: 'x86_64'
- toolkit: 'cpu'
- - os: 'Linux'
- arch: 'x86_64'
- toolkit: 'cuda-12.9'
- - os: 'Linux'
- arch: 'x86_64'
- toolkit: 'cuda-13.0'
- - os: 'Windows'
- arch: 'x86_64'
- toolkit: 'cpu'
- - os: 'macOS'
- arch: 'aarch64'
- toolkit: 'metal'
- runs-on: |-
- ${{ case(matrix.os == 'Windows', case(matrix.arch == 'aarch64', 'windows-11-arm',
- 'windows-2022'),
- matrix.os == 'macOS', 'macos-26-xlarge',
- case(matrix.arch == 'x86_64' && startsWith(matrix.toolkit, 'cuda'), 'gpu-t4-4-core',
- matrix.arch == 'aarch64', 'ubuntu-22.04-arm',
- 'ubuntu-22.04'))
- }}
- steps:
- - uses: actions/checkout@v7
- - uses: ./.github/actions/setup
- with:
- toolkit: ${{ matrix.toolkit }}
- use-ccache: false
- - uses: ./.github/actions/test-wheel
- with:
- toolkit: ${{ matrix.toolkit }}
-
- pypi-publish-frontend:
- name: Publish mlx to PyPI
- runs-on: ubuntu-latest
- needs: [test_wheel]
- permissions:
- id-token: write
- environment:
- name: *pypi-env
- url: https://pypi.org/p/mlx
- steps:
- - uses: actions/download-artifact@v8
- with:
- pattern: frontend-*
- merge-multiple: true
- path: dist
- - name: Display structure of downloaded files
- run: du -ah dist
- - name: Publish package distributions to PyPI
- if: *publish
- uses: pypa/gh-action-pypi-publish@release/v1
- with:
- repository-url: https://upload.pypi.org/legacy/
-
- pypi-publish-cuda:
- name: Publish mlx-cuda to PyPI
- runs-on: ubuntu-latest
- needs: [test_wheel]
- permissions:
- id-token: write
- environment:
- name: *pypi-env
- url: https://pypi.org/p/mlx-cuda
- steps:
- - uses: actions/download-artifact@v8
- with:
- pattern: backend-cuda*
- merge-multiple: true
- path: dist
- - name: Display structure of downloaded files
- run: du -ah dist
- - name: Publish package distributions to PyPI
- if: *publish
- uses: pypa/gh-action-pypi-publish@release/v1
- with:
- repository-url: https://upload.pypi.org/legacy/
-
- pypi-publish-cpu:
- name: Publish mlx-cpu to PyPI
- runs-on: ubuntu-latest
- needs: [test_wheel]
- permissions:
- id-token: write
- environment:
- name: *pypi-env
- url: https://pypi.org/p/mlx-cpu
- steps:
- - uses: actions/download-artifact@v8
- with:
- pattern: backend-cpu-*
- merge-multiple: true
- path: dist
- - name: Display structure of downloaded files
- run: du -ah dist
- - name: Publish package distributions to PyPI
- if: *publish
- uses: pypa/gh-action-pypi-publish@release/v1
- with:
- repository-url: https://upload.pypi.org/legacy/
-
- pypi-publish-metal:
- name: Publish mlx-metal to PyPI
- runs-on: ubuntu-latest
- needs: [test_wheel]
- permissions:
- id-token: write
- environment:
- name: *pypi-env
- url: https://pypi.org/p/mlx-metal
- steps:
- - uses: actions/download-artifact@v8
- with:
- pattern: backend-metal-*
- path: dist
- - name: Display structure of downloaded files
- run: du -ah dist
- - name: Publish package distributions to PyPI
- if: *publish
- uses: pypa/gh-action-pypi-publish@release/v1
- with:
- repository-url: https://upload.pypi.org/legacy/
diff --git ml-explore/mlx/.github/workflows/update_bypass_list.yml Layr-Labs/mlx/.github/workflows/update_bypass_list.yml
deleted file mode 100644
index f5ecb25f7ae679693e7f14158b9da0b929494780..0000000000000000000000000000000000000000
--- ml-explore/mlx/.github/workflows/update_bypass_list.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-name: 'Update bypass list'
-description: 'Update interaction-limits bypass list with eligible contributors'
-
-on:
- workflow_dispatch:
- push:
- branches:
- - main
- schedule:
- - cron: 33 6 * * *
-
-permissions:
- contents: write
-
-jobs:
- update_bypass_list:
- name: 'Update bypass list'
- if: github.repository == 'ml-explore/mlx'
- runs-on: ubuntu-22.04
- steps:
- - uses: actions/checkout@v7
- - env:
- # Can only use PAT with permissions: admin:org_hook, public_repo
- GITHUB_TOKEN: ${{ secrets.ZCBENZ_TOKEN_UPDATE_BYPASS_LIST }}
- run: node .github/scripts/update-bypass-list.js ml-explore mlx
diff --git ml-explore/mlx/AGENTS.md Layr-Labs/mlx/AGENTS.md
index 969236055007943976cf084a87730644ed20c59f..06ca2579b7b97c1f0ad224c3ebab6311c7f01ecf 100644
--- ml-explore/mlx/AGENTS.md
+++ Layr-Labs/mlx/AGENTS.md
@@ -1,5 +1,13 @@
# Instructions for MLX
+## Working in our MLX forks
+
+The Layr-Labs MLX forks, including Darkbloom, Darkbloom Sandboxes, and related
+work, are our repositories. In them, agents MAY work directly: write commit
+messages and PR descriptions, run `git push`, create PRs and issues, and reply
+to review comments on the user's behalf. The upstream rules below remain in
+force for upstream contributions.
+
## Agent rules
- Reject vague instructions when user does not show understands of the code
diff --git ml-explore/mlx/CMakeLists.txt Layr-Labs/mlx/CMakeLists.txt
index 3f2330483dc85d5b9607c9dc7a25327c02c0dd8e..47b4d608a02e12b44e8a6cb9e79ccdfa1b079cd3 100644
--- ml-explore/mlx/CMakeLists.txt
+++ Layr-Labs/mlx/CMakeLists.txt
@@ -228,7 +228,11 @@ endif()
set(METAL_CPP_URL
https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip)
- FetchContent_Declare(metal_cpp URL ${METAL_CPP_URL})
+ FetchContent_Declare(
+ metal_cpp
+ URL ${METAL_CPP_URL}
+ URL_HASH
+ SHA256=4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4)
FetchContent_MakeAvailable(metal_cpp)
target_include_directories(
mlx PUBLIC $<BUILD_INTERFACE:${metal_cpp_SOURCE_DIR}>
diff --git ml-explore/mlx/FORKDIFF.md Layr-Labs/mlx/FORKDIFF.md
new file mode 100644
index 0000000000000000000000000000000000000000..4cf57c0adf81c87a5804acd527b17692cbb0dda7
--- /dev/null
+++ Layr-Labs/mlx/FORKDIFF.md
@@ -0,0 +1,147 @@
+# Fork diff: what this fork changes, and keeping that page honest
+
+This repository is a fork of [`ml-explore/mlx`](https://github.com/ml-explore/mlx).
+Everything it changes relative to upstream is published as a browsable page:
+
+**https://layr-labs.github.io/mlx/**
+
+The page is rendered by [`protolambda/forkdiff`](https://github.com/protolambda/forkdiff)
+from [`fork.yaml`](fork.yaml) at the repo root, in the style of
+[op-geth's go-ethereum fork diff](https://op-geth.optimism.io/). `fork.yaml`
+groups the changed files into sections with a paragraph each, names the exact
+upstream commit the fork is based on (`base.hash`), and lists files that are
+not code (`ignore`). Every push to `main` re-renders and redeploys it
+(`.github/workflows/forkdiff-pages.yml`).
+
+**One-time setup.** GitHub Pages has to be switched on by a repo admin:
+Settings → Pages → Source: **GitHub Actions**. The workflow token cannot do
+this itself. Until it's done the deploy workflow still builds the page (kept
+as a run artifact, `forkdiff-page`) and exits with a notice instead of failing.
+
+## Native CI
+
+The Linux lint job, ASAN/UBSAN tests, fork-diff check and page renderer use only
+Darkbloom Linux ARM64 runners. All eight Mac jobs in `fork-tests.yml` use only
+Darkbloom macOS ARM64 runners. Each names its VM size ([Job sizes](#job-sizes)).
+They keep their original steps, tests and job timeouts.
+The sanitizer jobs use the qualified image's compilers and dependencies, with a
+tool preflight in place of installing packages through sudo, and are capped
+at 60 minutes. When compatible capacity is busy they wait; these jobs have no GitHub-hosted or Blacksmith
+fallback. The current profile qualification lifetime is one hour, and the
+existing watchdog can cancel or retry a job after its 30-minute wait threshold.
+The watchdog can rerun a stranded workflow once, then cancel another stranded
+attempt. These jobs keep native labels on a rerun; the watchdog cannot send them
+to hosted runners. These bounds are not a promise of a 24-hour native queue.
+The `DARKBLOOM_ROUTING` variable controls the separate dynamic route workflow;
+it does not turn off these native-only jobs.
+
+The Fedora aarch64 job runs the unchanged Fedora script on a Darkbloom Linux
+ARM64 runner. The sandbox has no Docker, so `.github/scripts/fedora-proot/`
+unpacks the archived Fedora 42 container rootfs (pinned by digest) and runs the
+script under PRoot, built from pinned source with its missing ARM64 `faccessat2`
+entry added. PRoot fakes root through ptrace and is not an isolation boundary;
+the job VM is. The Fedora x86_64 job keeps its hosted runner: emulating x86 on
+ARM was not qualified. The GitHub-hosted Pages job still packages and publishes
+the rendered artifact through its protected environment. If its first deploy
+fails before it creates a deployment (the packaged artifact is not listed yet),
+it waits 20 seconds and tries once more. The disabled native CodeQL workflow keeps its separate routing
+and activation rules.
+
+### Job sizes
+
+Each Darkbloom macOS job names its VM size in its runner label, for example
+`darkbloom-macos-arm64-4x16` (4 vCPUs, 16 GiB). A job without a size gets the
+size that the approval pins (12 vCPUs, 32 GiB). The image pipeline signs
+4x16, 4x24, 8x16 and 12x32. A job gets the smallest signed size that has 30%
+headroom over its measured memory peak. A job that took less than 10 minutes
+must stay under 10 minutes.
+
+The peak of a job is the larger of two sampler figures: used memory (app +
+wired + compressed) and the sum of the lifetime peak footprints of the
+runner user's processes. The second matters where memory is compressed:
+used memory counts compressed pages at their compressed size. The idle VM
+uses about 6 GiB. Pull request runs 44750715218 and 44754340762 measured
+every job.
+
+| Job | Size | Wall time on 12 vCPUs (runs 43368507444 to 43569480732) | Hosted 3 vCPUs, 7 GiB | Measured (size: wall time, peak) |
+|---|---|---|---|---|
+| `build-wheel` | 4x16 | 153 to 354 s | 575 s (run 43120201853, `macos-26`) | 4x16: 230 and 242 s, 10.65 GiB |
+| `build-cpp` | 4x16 | 277 to 620 s; p90 about 480 s. The slow runs spend up to 190 s in the build cache action. | 940 s, of which the compile is 632 s (run 43120201853) | 8x16: 302 s, 10.42 GiB; 4x16: 374 s, 10.56 GiB |
+| `python-gpu` (2 shards) | 4x24 | 171 to 541 s | 297 to 635 s (run 43531506709, `xcode-27`) | 4x16: 182 to 307 s. Shard 1 used 11.65 GiB with 4.1 GiB compressed; its processes' footprints sum to 13.21 GiB. 16 GiB is less than 1.3 times that. |
+| `python-cpu` (3 shards) | 12x32 | 152 to 444 s | 279 to 546 s | 4x16: 190 to 258 s, 13.20 GiB used with 7.1 GiB compressed, memory pressure at warning. 4x24: 163 to 273 s, 19.26 GiB used (footprints 17.89 GiB). 24 GiB is less than 1.3 times 19.26 GiB, and 12x32 is the next signed size with more memory. |
+| `metal-build-and-test` | 4x16 | 34 to 190 s | 20 to 23 s | 4x16: 36 and 38 s, 6.07 GiB |
+
+`test_init_reduce_large_output` needs a 4 GiB Metal buffer on the GPU and a
+`memory_size` of 16 GiB on the CPU. The GPU shards (a Metal buffer can have
+half of the VM's memory) and the CPU shards give both, so the test still
+runs. Runs 44750715218 and 44754340762 ran it on both.
+
+Every macOS job runs `.github/scripts/ci-resource-sampler.py`, a copy of the
+sampler of Layr-Labs/d-inference (wrapped to this repository's ruff rules), from
+its checkout on. Its last step,
+"Report the resource samples", prints the memory peak of each class, the
+three largest processes, the busy vCPUs and the sampled time scaled to 4 and
+8 vCPUs. Use these numbers to change a size. Check Lint runs
+`.github/scripts/test-runner-sizes.py`. It fails when a macOS job names no
+size, a size that is not signed, or a size other than the one its table
+gives.
+
+## The gate
+
+A fork-diff page is only useful while it is true, and two things make it go
+stale silently. `scripts/check_forkdiff.py` runs on every PR and on every push
+to `main` (`.github/workflows/forkdiff-check.yml`) and fails on both:
+
+| Drift | Check | Why it matters |
+|-------|-------|----------------|
+| **Merge of newer upstream** | `base.hash` must equal `git merge-base HEAD upstream/main` and be an ancestor of upstream `main` | After a merge the old base makes upstream's own commits look like fork changes: thousands of files, none of them ours. |
+| **New fork change nobody described** | every path in `git diff --name-only base.hash HEAD` must match a section glob or a global `ignore` | An undescribed file is a change the page can't explain. |
+| **Section describing code we no longer carry** | every glob must match at least one changed path | Stale sections are as misleading as missing ones. |
+
+The check also renders the page, so a `fork.yaml` that forkdiff itself rejects
+cannot merge. The deploy workflow runs the same check before publishing, so a
+stale analysis is never served.
+
+## Day to day
+
+**Adding or changing fork files in a PR.** If the check lists uncovered files,
+add each to the section that explains it in `fork.yaml` (or start a new
+section with a short description). Files that are not code go under the
+top-level `ignore`. Keep globs specific: a `mlx/**` catch-all would swallow
+upstream's changes after a bad rebase and defeat the gate.
+
+**Upstream sync policy (2026-10-22).** The fork merges upstream `main` when
+David directs it. Use a merge commit. Do not rebase. Each merge does these steps:
+
+1. Set `base.hash` to the new merge-base, `git merge-base HEAD upstream/main`.
+2. Read each `fork.yaml` section again. Remove a section when upstream now has
+ the same change. Change a section when the merge changed the fork code.
+3. Delete again the upstream workflows and actions that the fork removes. The
+ "Fork tooling" section lists them.
+4. Run the check below until it passes.
+
+Between merges, port an upstream fix that the fork needs as its own commit.
+Describe the port in its own `fork.yaml` section. The check compares the fork
+with `base.hash`:
+
+```
+python3 -m pip install pyyaml
+python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main
+```
+
+**Previewing the page locally** (Go 1.21+):
+
+```
+go run github.com/protolambda/forkdiff@v0.1.1 -repo . -fork fork.yaml -out tmp/index.html
+open tmp/index.html
+```
+
+## Design notes
+
+- `base.hash` is a full 40-hex commit id, never a branch name: a symbolic base
+ would move underneath the page and the gate alike.
+- Section `ignore` lists count as coverage (forkdiff still lists those files,
+ grayed out); the top-level `ignore` is for things that aren't code at all.
+- The glob semantics are forkdiff's: `*` and `?` stop at `/`, `**` spans
+ directories (and may match none), `[!x]` negates a class.
+- The check is pure git + PyYAML so the same command runs locally and in CI.
diff --git ml-explore/mlx/README.md Layr-Labs/mlx/README.md
index fb30a24f2ce87d6f81822fc51e01c9fb6d38de28..b316d5a61bb3f321fc5befe81bc75ae2969875ad 100644
--- ml-explore/mlx/README.md
+++ Layr-Labs/mlx/README.md
@@ -6,6 +6,8 @@ [**Examples**](#examples)
[](https://circleci.com/gh/ml-explore/mlx)
+> **This is a fork.** `Layr-Labs/mlx` tracks [`ml-explore/mlx`](https://github.com/ml-explore/mlx) and carries the kernel, allocator and Metal-runtime work behind Layr-Labs' Apple-silicon inference stack (`mlx` → `mlx-c` → `mlx-swift` → `mlx-swift-lm`). Everything changed relative to upstream is published as a fork diff at **https://layr-labs.github.io/mlx/**, described in [`fork.yaml`](fork.yaml) and kept honest by CI — see [FORKDIFF.md](FORKDIFF.md).
+
MLX is an array framework for machine learning on Apple silicon,
brought to you by Apple machine learning research.
diff --git ml-explore/mlx/docs/ci-codeql-native.md Layr-Labs/mlx/docs/ci-codeql-native.md
new file mode 100644
index 0000000000000000000000000000000000000000..8128ab3e03efa2583d682e1ce82cfffd57e6b7e9
--- /dev/null
+++ Layr-Labs/mlx/docs/ci-codeql-native.md
@@ -0,0 +1,55 @@
+# Native CodeQL activation
+
+`codeql-native.yml` is inactive unless the repository variable `CODEQL_NATIVE`
+is exactly `on`. Merging the workflow does not switch GitHub's default setup or
+change its security coverage. The operator must review that switch separately.
+
+The scan job has `contents: read` only. It runs the pinned CodeQL2.27.4 ARM64
+bundle against the Actions event commit, without building repository code. It
+uses the same default query suites for Actions, C/C++ and Python. The Darkbloom
+route has one `codeql` Linux ARM64 lane; hosted fallback is also ARM64.
+
+The separate GitHub-hosted upload job has only `contents: read`, `actions: read`
+and `security-events: write`. It does not check out or run repository code. Its
+only inputs are the same run's three SARIF files and a bounded manifest, checked
+against the event repository, commit, ref, run and attempt. Unexpected files,
+symlinks, changed hashes, different tools and missing fingerprints are refused.
+The official pinned uploader preserves these categories:
+
+- `/language:actions`
+- `/language:c-cpp`
+- `/language:python`
+
+Native CodeQL already records the primary-line fingerprints. The uploader gets
+an empty directory as `checkout_path`; it preserves the supplied fingerprints
+and uses the Actions event SHA/ref. No source files are transferred to this job.
+GitHub permits code-scanning uploads for `pull_request` runs, including runs with
+read-only token scopes. The uploader ignores ref/SHA overrides for fork PRs.
+
+## Operator gates
+
+1. Keep `CODEQL_NATIVE` unset/off while reviewing and merging this source. Verify
+ default setup remains enabled and its three analyses are current. Record its
+ settings and latest successful analysis IDs for rollback.
+2. Approve the single `codeql` lane for the reviewed Linux image and its existing
+ network template. Confirm the image/worker and capacity before switching.
+3. Switch GitHub from default to advanced setup with admin authorization. Default
+ setup blocks CodeQL API uploads, so it must not remain the active uploader.
+ Ensure the new workflow is enabled, then set `CODEQL_NATIVE=on` and dispatch
+ `main`. The weekly schedule and subsequent main pushes/PRs use this workflow.
+4. Require successful native compute, all three processed GitHub analyses on the
+ expected commit/categories, and physical runner retirement. Also qualify a
+ fork PR upload using its merge ref and unprivileged PR token. An artifact-only
+ scan does not prove the upload/alert integration.
+5. After the new analyses are healthy, review any stale default-setup analysis
+ configuration before removing it; category names alone do not merge distinct
+ workflow configurations. Never delete the last working coverage first.
+
+Rollback: turn `CODEQL_NATIVE` off, restore the recorded default-setup settings,
+and require its three initial analyses to succeed. Do not leave both modes active.
+
+References:
+
+- [Default versus advanced setup](https://docs.github.com/en/code-security/reference/code-scanning/troubleshoot-analysis-errors/results-different-than-expected)
+- [PR uploads with read-only scopes](https://docs.github.com/en/enterprise-cloud@latest/code-security/reference/code-scanning/troubleshoot-analysis-errors/resource-not-accessible)
+- [Pinned uploader inputs](https://github.com/github/codeql-action/blob/33d7b85da1a04171e211befe2c739303b9a4c066/upload-sarif/action.yml)
diff --git ml-explore/mlx/python/tests/test_conv.py Layr-Labs/mlx/python/tests/test_conv.py
index 24ec142180bf4def0e34965def2ef03e430e38af..8ec1b054a3a673d1629f69701ebca2f3704c30da 100644
--- ml-explore/mlx/python/tests/test_conv.py
+++ Layr-Labs/mlx/python/tests/test_conv.py
@@ -1438,6 +1438,11 @@ self.assertTrue(mx.allclose(g_gpu, g_cpu, atol=1e-4))
@unittest.skipIf(not mx.metal.is_available(), "requires Metal")
def test_conv2d_winograd_batch_tiling(self):
+ # Winograd and its batch tiling exist only in the Metal backend. On
+ # the CPU every run takes the same path, so the fallback checks
+ # cannot tell the paths apart.
+ if mx.default_device() != mx.gpu:
+ self.skipTest("Winograd batch tiling is specific to the GPU device")
# Use envs to test tiling without allocating large buffers.
tile_key = "MLX_CONV_WINOGRAD_TILE_BATCH"
ws_key = "MLX_CONV_WINOGRAD_WORKING_SET"
@@ -1516,6 +1521,10 @@ self.assertTrue(np.allclose(capped, cpu_ref, atol=1e-3))
@unittest.skipIf(not mx.metal.is_available(), "requires Metal")
def test_conv2d_winograd_disable(self):
+ # Winograd exists only in the Metal backend. On the CPU every run
+ # takes the same path, so the check cannot tell the paths apart.
+ if mx.default_device() != mx.gpu:
+ self.skipTest("Winograd is specific to the GPU device")
# N * iH * iW >= 4096 selects Winograd only from a batch of 3.
np.random.seed(0)
x = mx.array(np.random.normal(size=(1, 40, 40, 128)).astype(np.float32))
diff --git ml-explore/mlx/python/tests/test_fft.py Layr-Labs/mlx/python/tests/test_fft.py
index 0e410c7c59e283655ad7d6606b08f7dc219e230c..cd19165f268643539d1a0933c3d13b79bd39b310 100644
--- ml-explore/mlx/python/tests/test_fft.py
+++ Layr-Labs/mlx/python/tests/test_fft.py
@@ -226,6 +226,9 @@ @unittest.skipIf(
not mx.metal.is_available(), "the size limit is specific to the Metal FFT plan"
)
def test_fft_too_large(self):
+ # The CPU FFT has no size limit, so this runs only on the GPU device.
+ if mx.default_device() != mx.gpu:
+ self.skipTest("the size limit is specific to the GPU device")
# Larger than the four step plan can decompose, so it has to throw
# rather than run a kernel that silently returns the wrong answer.
# CUDA hands this to cuFFT instead and has no such limit.
diff --git ml-explore/mlx/python/tests/test_reduce.py Layr-Labs/mlx/python/tests/test_reduce.py
index b46dcee1e2231ae62e305869ebca23af7535d229..71f7476b1a6ef1fb68bd94059cdb0fb28255d53f 100644
--- ml-explore/mlx/python/tests/test_reduce.py
+++ Layr-Labs/mlx/python/tests/test_reduce.py
@@ -163,6 +163,16 @@ z = np.array(x).sum((0, 2, 3))
self.assertTrue(np.all(z == y))
def test_zero_size(self):
+ for op in ["all", "any"]:
+ for shape, axis in [((0,), None), ((0, 3), 0), ((3, 0), 1), ((0, 3), 1)]:
+ with self.subTest(op=op, shape=shape, axis=axis):
+ a_np = np.zeros(shape, dtype=np.bool_)
+ expected = getattr(np, op)(a_np, axis=axis)
+ actual = getattr(mx, op)(mx.array(a_np), axis=axis)
+ mx.eval(actual)
+ self.assertEqual(actual.shape, expected.shape)
+ self.assertEqual(actual.tolist(), expected.tolist())
+
# max and min have no identity, so they are only undefined when an axis
# being reduced is itself empty. An array that is empty because of some
# other axis reduces into an empty result.
@@ -363,6 +373,16 @@ self.assertFalse(x.all().item())
@unittest.skipIf(not mx.metal.is_available(), "requires Metal")
def test_init_reduce_large_output(self):
+ # The output is 4 GiB. The macOS runners of the fork CI have a 3.5 GiB
+ # Metal buffer limit and 7 GB of memory, so skip where it cannot fit.
+ size = 4 * 2**30
+ info = mx.device_info(mx.gpu)
+ if mx.default_device() == mx.gpu:
+ fits = info["max_buffer_length"] >= size
+ else:
+ fits = info["memory_size"] >= 4 * size
+ if not fits:
+ self.skipTest("the 4 GiB output does not fit on this device")
out = mx.all(mx.zeros((0, 4, 2**30), dtype=mx.bool_), axis=0)
mx.eval(out)
self.assertTrue(mx.all(out).item())
diff --git ml-explore/mlx/scripts/check_forkdiff.py Layr-Labs/mlx/scripts/check_forkdiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ff1210829d3f70c873b34ef337041c3078af290
--- /dev/null
+++ Layr-Labs/mlx/scripts/check_forkdiff.py
@@ -0,0 +1,267 @@
+#!/usr/bin/env python3
+"""Gate: ``fork.yaml`` must describe this fork as it is *now*.
+
+The fork-diff page (rendered with protolambda/forkdiff and published on GitHub
+Pages) is only useful while it is true. Two things make it go stale silently:
+
+1. **A rebase onto newer upstream.** ``base.hash`` still points at the old
+ upstream commit, so the page shows upstream's own changes as if the fork
+ made them. This script requires ``base.hash`` to equal
+ ``git merge-base HEAD <upstream>``; a rebase moves the merge-base, and the
+ gate stays red until the hash is bumped.
+2. **A new fork change nobody described.** Every path in
+ ``git diff --name-only base.hash HEAD`` must match a glob in some section
+ (or a global ``ignore``), and every glob must still match something — a
+ section describing code the fork no longer carries is as misleading as a
+ missing one.
+
+Both are pure git + YAML, so the same check runs locally::
+
+ python3 scripts/check_forkdiff.py # coverage only
+ python3 scripts/check_forkdiff.py --upstream-ref upstream/main
+
+Exit status is non-zero on any violation. ``--review-status-out`` writes the
+JSON the CI comment synthesizer consumes (same shape as history-check).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import subprocess
+import sys
+from pathlib import Path
+from typing import Iterable
+
+import yaml
+
+GLOB_CLASS_RE = re.compile(r"\[([^\]]*)\]")
+
+
+def glob_to_regex(glob: str) -> re.Pattern[str]:
+ """Translate a forkdiff glob into a regex over the repo-relative path.
+
+ Semantics follow the doublestar rules forkdiff uses: ``*`` and ``?`` never
+ cross a ``/``; ``**`` matches any number of directories (``a/**/b`` also
+ matches ``a/b``); ``[...]`` character classes pass through, with a leading
+ ``!`` meaning negation.
+ """
+ out: list[str] = []
+ i = 0
+ while i < len(glob):
+ c = glob[i]
+ if c == "*":
+ if glob.startswith("**", i):
+ if glob.startswith("**/", i):
+ out.append("(?:.*/)?")
+ i += 3
+ continue
+ out.append(".*")
+ i += 2
+ continue
+ out.append("[^/]*")
+ elif c == "?":
+ out.append("[^/]")
+ elif c == "[":
+ end = glob.find("]", i + 1)
+ if end == -1:
+ out.append(re.escape(c))
+ else:
+ cls = glob[i + 1 : end]
+ if cls.startswith("!"):
+ cls = "^" + cls[1:]
+ out.append("[" + cls + "]")
+ i = end + 1
+ continue
+ else:
+ out.append(re.escape(c))
+ i += 1
+ return re.compile("^" + "".join(out) + "$")
+
+
+def collect_globs(node: dict, path: str = "def") -> list[tuple[str, str]]:
+ """Every glob in the section tree as ``(section path, glob)``.
+
+ A section's ``ignore`` list counts as coverage too: forkdiff still lists
+ those files under the section (grayed out), so they are described.
+ """
+ found: list[tuple[str, str]] = []
+ title = node.get("title") or "(untitled)"
+ here = f"{path} › {title}" if path != "def" else title
+ for g in node.get("globs") or []:
+ found.append((here, str(g)))
+ for g in node.get("ignore") or []:
+ found.append((here, str(g)))
+ for child in node.get("sub") or []:
+ found.extend(collect_globs(child, here))
+ return found
+
+
+def git(*args: str, cwd: Path) -> str:
+ result = subprocess.run(
+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=False
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"git {' '.join(args)} failed: {result.stderr.strip()}")
+ return result.stdout.strip()
+
+
+def changed_paths(repo: Path, base: str, head: str) -> list[str]:
+ out = git("diff", "--name-only", f"{base}..{head}", cwd=repo)
+ return [line for line in out.splitlines() if line]
+
+
+def check_coverage(
+ paths: Iterable[str], globs: list[tuple[str, str]]
+) -> tuple[list[str], list[tuple[str, str]], dict[str, int]]:
+ """Return ``(uncovered paths, stale globs, matches per glob)``."""
+ compiled = [(section, g, glob_to_regex(g)) for section, g in globs]
+ hits: dict[str, int] = {g: 0 for _, g in globs}
+ uncovered: list[str] = []
+ for p in paths:
+ matched = False
+ for _, g, rx in compiled:
+ if rx.match(p):
+ hits[g] += 1
+ matched = True
+ if not matched:
+ uncovered.append(p)
+ stale = [(section, g) for section, g in globs if hits[g] == 0]
+ return uncovered, stale, hits
+
+
+def check_base(repo: Path, base: str, head: str, upstream_ref: str | None) -> list[str]:
+ problems: list[str] = []
+ if not re.fullmatch(r"[0-9a-f]{40}", base):
+ problems.append(
+ f"base.hash must be a full 40-hex commit id, got {base!r} — a short or "
+ "symbolic ref would silently move under the page."
+ )
+ return problems
+ try:
+ git("cat-file", "-e", f"{base}^{{commit}}", cwd=repo)
+ except RuntimeError:
+ problems.append(
+ f"base.hash {base[:12]} is not present in this repository. The fork must "
+ "sit on top of it (fetch upstream if the clone is shallow)."
+ )
+ return problems
+ if upstream_ref is None:
+ return problems
+ try:
+ git("merge-base", "--is-ancestor", base, upstream_ref, cwd=repo)
+ except RuntimeError:
+ problems.append(
+ f"base.hash {base[:12]} is not an ancestor of {upstream_ref} — it must "
+ "name a commit on upstream main, not a fork commit."
+ )
+ merge_base = git("merge-base", head, upstream_ref, cwd=repo)
+ if merge_base != base:
+ problems.append(
+ f"base.hash {base[:12]} != merge-base({head}, {upstream_ref}) = "
+ f"{merge_base[:12]}. The fork was rebased onto newer upstream; update "
+ "fork.yaml's base.hash and re-describe the sections (see docs/forkdiff.md)."
+ )
+ return problems
+
+
+def review_status(problems: list[str], detail: str) -> list[dict]:
+ if not problems:
+ return []
+ return [
+ {
+ "source": "fork diff analysis",
+ "results": [
+ {
+ "kind": "action_required",
+ "title": "fork.yaml no longer describes the fork",
+ "summary": (
+ problems[0]
+ if len(problems) == 1
+ else f"{len(problems)} issues: {problems[0]}"
+ ),
+ "detail": detail,
+ "how_to_fix": (
+ "See FORKDIFF.md. After an upstream merge: set base.hash "
+ "to `git merge-base HEAD upstream/main`. For new files: add "
+ "them to the section that explains them (or to a global "
+ "`ignore` if they are not code). Then run "
+ "`python3 scripts/check_forkdiff.py "
+ "--upstream-ref upstream/main` locally."
+ ),
+ }
+ ],
+ }
+ ]
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ ap.add_argument("--repo", default=".", help="path to the fork checkout")
+ ap.add_argument("--fork", default="fork.yaml", help="fork page definition")
+ ap.add_argument("--head", default="HEAD", help="the fork revision to describe")
+ ap.add_argument(
+ "--upstream-ref",
+ default=None,
+ help="a ref holding upstream main (e.g. refs/remotes/upstream/main); "
+ "enables the merge-base check",
+ )
+ ap.add_argument(
+ "--review-status-out", default=None, help="write review-status JSON here"
+ )
+ args = ap.parse_args(argv)
+
+ repo = Path(args.repo).resolve()
+ fork_path = repo / args.fork
+ spec = yaml.safe_load(fork_path.read_text(encoding="utf-8")) or {}
+ base = str((spec.get("base") or {}).get("hash") or "").strip()
+ problems: list[str] = []
+ lines: list[str] = []
+
+ problems += check_base(repo, base, args.head, args.upstream_ref)
+
+ globs = collect_globs(spec.get("def") or {})
+ globs += [("(global ignore)", str(g)) for g in spec.get("ignore") or []]
+
+ paths: list[str] = []
+ if re.fullmatch(r"[0-9a-f]{40}", base):
+ try:
+ paths = changed_paths(repo, base, args.head)
+ except RuntimeError as exc:
+ problems.append(str(exc))
+
+ uncovered, stale, hits = check_coverage(paths, globs)
+ if uncovered:
+ problems.append(
+ f"{len(uncovered)} changed file(s) are not described by any fork.yaml "
+ "section"
+ )
+ lines.append("Uncovered files (add each to the section that explains it):")
+ lines += [f" - {p}" for p in uncovered]
+ if stale:
+ problems.append(f"{len(stale)} glob(s) match nothing the fork changes")
+ lines.append("Stale globs (the fork no longer changes anything they name):")
+ lines += [f" - {g} [{section}]" for section, g in stale]
+
+ covered = len(paths) - len(uncovered)
+ print(
+ f"fork.yaml: base {base[:12]} head {args.head} changed files {len(paths)} "
+ f"described {covered} sections+ignores {len(globs)}"
+ )
+ if args.upstream_ref is None:
+ print(" (no --upstream-ref: merge-base check skipped)")
+ for line in lines:
+ print(line)
+ for p in problems:
+ print(f"::error::{p}")
+
+ if args.review_status_out:
+ Path(args.review_status_out).write_text(
+ json.dumps(review_status(problems, "\n".join(lines))), encoding="utf-8"
+ )
+ return 1 if problems else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())