diff --git ml-explore/mlx-c/.github/actionlint.yaml Layr-Labs/mlx-c/.github/actionlint.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2a752e0747ab15399f1dd557d8b546f8131523cf
--- /dev/null
+++ Layr-Labs/mlx-c/.github/actionlint.yaml
@@ -0,0 +1,3 @@
+self-hosted-runner:
+ labels:
+ - darkbloom-linux-arm64
diff --git ml-explore/mlx-c/.github/scripts/codeql_artifacts.py Layr-Labs/mlx-c/.github/scripts/codeql_artifacts.py
new file mode 100644
index 0000000000000000000000000000000000000000..dacee361744f10718b59c8234eee408850b2f725
--- /dev/null
+++ Layr-Labs/mlx-c/.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-c/.github/scripts/codeql_artifacts_test.py Layr-Labs/mlx-c/.github/scripts/codeql_artifacts_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..dae67fdb562a158678506c9eb45b38ffa8c5768c
--- /dev/null
+++ Layr-Labs/mlx-c/.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-c/.github/workflows/codeql-native.yml Layr-Labs/mlx-c/.github/workflows/codeql-native.yml
new file mode 100644
index 0000000000000000000000000000000000000000..82c75ac91dcb605e07561b6b8bdb161c5dbe7a37
--- /dev/null
+++ Layr-Labs/mlx-c/.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-c/.github/workflows/darkbloom-route.yml Layr-Labs/mlx-c/.github/workflows/darkbloom-route.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f3cbd667cb26f368c1c47d1087d5d5c943085201
--- /dev/null
+++ Layr-Labs/mlx-c/.github/workflows/darkbloom-route.yml
@@ -0,0 +1,166 @@
+# Copied verbatim from Layr-Labs/d-inference@6ffeaf06c2e9541fa095f4b8194b527c93458523
+# (.github/workflows/darkbloom-route.yml, blob 4528c2c7184e156c418054521c1421a95e188c29,
+# last changed there in 11bb2d18cef808014736213502755b6b6074eed6, #1619). Keep the
+# lines below this header identical to that file; change d-inference first.
+
+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.
+on:
+ workflow_call:
+ inputs:
+ lanes:
+ description: >-
+ One lane per line: `<lane> <profile> <fallback-label> [count]`.
+ Profiles are linux_arm64 and macos_arm64. Count is the number of jobs
+ that will run (default 1); 0 keeps the fallback without asking.
+ 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 }}
+ 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.
+ 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 extra; do
+ [ -n "$lane" ] || continue
+ count=${count:-1}
+ [ -z "$extra" ] || configuration_error "lane $lane has more than four 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"
+ 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" '. + [{$lane, $profile, $fallback, $count}]' <<<"$configured")
+ done <<<"${LANES:-}"
+ [ "$configured" != '[]' ] || configuration_error "no lanes are configured"
+ requested=$(jq -c '[.[] | select(.count > 0) | {lane, profile, count}]' <<<"$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}')
+ # 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
+ | if .count == 0 then .target = "fallback" | .reason = "not requested"
+ elif $fallback_reason != "" then .target = "fallback" | .reason = $fallback_reason
+ elif $decision.target == "darkbloom" and $decision.runs_on == $profiles[.profile]
+ 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 $profiles[.profile] else .fallback end) ]')
+ routes=$(jq -c 'map({key: .lane, value: .runs_on}) | from_entries' <<<"$decisions")
+ echo "routes=$routes" >> "$GITHUB_OUTPUT"
+
+ echo "$note"
+ jq -r '.[] | "\(.lane): \(.runs_on | if type == "array" then join(",") else . end) (\(.reason))"' <<<"$decisions"
+ {
+ echo "### Darkbloom runner routing"
+ echo
+ echo "$note"
+ echo
+ echo "| Lane | Profile | Jobs | Runner | Decision |"
+ echo "| --- | --- | --- | --- | --- |"
+ jq -r '.[] | "| `\(.lane)` | \(.profile) | \(.count) | `\(.runs_on | if type == "array" then join(", ") else . end)` | \(.target): \(.reason) |"' <<<"$decisions"
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git ml-explore/mlx-c/.github/workflows/forkdiff-check.yml Layr-Labs/mlx-c/.github/workflows/forkdiff-check.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d834baf2170d7bd588a7a76104c22cba1e363775
--- /dev/null
+++ Layr-Labs/mlx-c/.github/workflows/forkdiff-check.yml
@@ -0,0 +1,76 @@
+name: Fork Diff Check
+
+# Fails a PR whose `fork.yaml` no longer describes this fork.
+#
+# The fork-diff page (https://layr-labs.github.io/mlx-c/, rendered by
+# protolambda/forkdiff from `fork.yaml`, deployed by forkdiff-pages.yml) is
+# only useful while it is true, and two things make it go stale silently:
+#
+# 1. A rebase onto newer upstream. `base.hash` keeps pointing at the old
+# upstream commit, so the page shows upstream's own changes as the fork's.
+# `scripts/check_forkdiff.py` requires base.hash == merge-base(HEAD,
+# upstream/main); a rebase moves the merge-base and the gate stays red
+# until the hash — and the sections — are brought up to date.
+# 2. A fork change nobody described. Every file in the base..HEAD diff must
+# match a section glob (or a global ignore), and every glob must still
+# match something.
+#
+# The page is also rendered here so a fork.yaml that forkdiff itself rejects
+# cannot merge.
+
+on:
+ pull_request:
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ analysis-up-to-date:
+ name: fork.yaml describes the fork
+ runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64]
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 0 # full history: merge-base with upstream, and forkdiff diffs against base.hash
+
+ - name: Fetch upstream main
+ run: |
+ git fetch --no-tags --quiet https://github.com/ml-explore/mlx-c.git \
+ main:refs/remotes/upstream/main
+ echo "upstream/main = $(git rev-parse --short refs/remotes/upstream/main)"
+ echo "merge-base = $(git merge-base HEAD refs/remotes/upstream/main | cut -c1-12)"
+
+ - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
+ with:
+ python-version: "3.12"
+
+ - name: Verify fork.yaml against the real diff
+ run: |
+ python3 -m pip install --quiet pyyaml
+ python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main
+
+ - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
+ with:
+ go-version: "1.24"
+ cache: false
+
+ - name: Render the fork-diff page
+ # fork.yaml names refs/heads/main; on a PR the checkout is a detached
+ # merge commit, so point the local branch at what we are checking.
+ run: |
+ git update-ref refs/heads/main HEAD
+ mkdir -p tmp/pages
+ go run github.com/protolambda/forkdiff@v0.1.1 \
+ -repo . -fork fork.yaml -out tmp/pages/index.html
+ echo "rendered $(wc -c < tmp/pages/index.html) bytes"
+
+ - name: Upload rendered page
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+ with:
+ name: forkdiff-page
+ path: tmp/pages/index.html
+ retention-days: 7
diff --git ml-explore/mlx-c/.github/workflows/forkdiff-pages.yml Layr-Labs/mlx-c/.github/workflows/forkdiff-pages.yml
new file mode 100644
index 0000000000000000000000000000000000000000..3d854f689e12cf14961a865e7afa1301d55373db
--- /dev/null
+++ Layr-Labs/mlx-c/.github/workflows/forkdiff-pages.yml
@@ -0,0 +1,132 @@
+name: Deploy Fork Diff
+
+# Renders `fork.yaml` with protolambda/forkdiff and publishes the result as the
+# repository's GitHub Pages site — the same setup ethereum-optimism/op-geth
+# uses for its go-ethereum fork diff. Runs the analysis gate first, so a page
+# that lies about the fork is never published.
+
+on:
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: "pages"
+ cancel-in-progress: true
+
+jobs:
+ render:
+ name: Render fork diff
+ runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64]
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 0 # forkdiff diffs against base.hash, deep in history
+
+ - name: Fetch upstream main
+ run: |
+ git fetch --no-tags --quiet https://github.com/ml-explore/mlx-c.git \
+ main:refs/remotes/upstream/main
+
+ - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
+ with:
+ python-version: "3.12"
+
+ - name: Refuse to publish a stale analysis
+ run: |
+ python3 -m pip install --quiet pyyaml
+ python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main
+
+ - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
+ with:
+ go-version: "1.24"
+ cache: false
+
+ - name: Build forkdiff
+ run: |
+ git update-ref refs/heads/main HEAD
+ mkdir -p tmp/pages
+ go run github.com/protolambda/forkdiff@v0.1.1 \
+ -repo . -fork fork.yaml -out tmp/pages/index.html
+
+ - name: Keep the rendered page as an artifact
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+ with:
+ name: forkdiff-page
+ path: tmp/pages/index.html
+ retention-days: 30
+
+ deploy:
+ name: Deploy fork diff
+ needs: render
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url || steps.deployment-retry.outputs.page_url }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ permissions:
+ contents: read
+ pages: write
+ id-token: write
+ steps:
+ - name: Is GitHub Pages enabled?
+ # Pages must be switched on once by a repo admin (Settings → Pages →
+ # Source: "GitHub Actions"). The workflow token cannot do that itself
+ # (`configure-pages` enablement needs an admin PAT), so until then the
+ # page is built and kept as an artifact but not deployed — a notice,
+ # not a red run.
+ id: pages
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ if gh api "repos/${GITHUB_REPOSITORY}/pages" --silent 2>/dev/null; then
+ echo "enabled=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "enabled=false" >> "$GITHUB_OUTPUT"
+ echo "::notice::GitHub Pages is not enabled for ${GITHUB_REPOSITORY}; built the page but skipped the deploy. Enable it once under Settings → Pages (Source: GitHub Actions) and re-run this workflow."
+ fi
+
+ - name: Setup Pages
+ if: steps.pages.outputs.enabled == 'true'
+ uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5.0.0
+
+ - name: Download rendered page
+ if: steps.pages.outputs.enabled == 'true'
+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
+ with:
+ name: forkdiff-page
+ path: tmp/pages
+
+ - name: Prepare Pages artifact
+ if: steps.pages.outputs.enabled == 'true'
+ run: touch tmp/pages/.nojekyll
+
+ - name: Upload Pages artifact
+ if: steps.pages.outputs.enabled == 'true'
+ uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
+ with:
+ path: tmp/pages
+
+ # deploy-pages looks the github-pages artifact up in this run's artifact
+ # list as soon as it starts, and that list can lag the upload above: the
+ # first try then fails with "No artifacts named github-pages were found"
+ # (seen on 2026-11-14). Only when the first try failed before it created a
+ # deployment (no page_url), wait and try once more.
+ - name: Deploy to GitHub Pages
+ if: steps.pages.outputs.enabled == 'true'
+ id: deployment
+ continue-on-error: true
+ uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
+
+ - name: Wait before the second try
+ if: steps.pages.outputs.enabled == 'true' && steps.deployment.outcome == 'failure' && steps.deployment.outputs.page_url == ''
+ run: sleep 20
+
+ - name: Deploy to GitHub Pages (second try)
+ if: steps.pages.outputs.enabled == 'true' && steps.deployment.outcome == 'failure' && steps.deployment.outputs.page_url == ''
+ id: deployment-retry
+ uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
diff --git ml-explore/mlx-c/fork.yaml Layr-Labs/mlx-c/fork.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5cbc3fb837c6e2b2a9bef8c23c753a2d511168f3
--- /dev/null
+++ Layr-Labs/mlx-c/fork.yaml
@@ -0,0 +1,218 @@
+title: "Layr-Labs/mlx-c - MLX C fork diff overview"
+footer: |
+ Fork-diff overview of [`Layr-Labs/mlx-c`](https://github.com/Layr-Labs/mlx-c), a fork of
+ [`ml-explore/mlx-c`](https://github.com/ml-explore/mlx-c) · the C bridge in Layr-Labs'
+ Apple-silicon inference stack ([`mlx`](https://github.com/Layr-Labs/mlx) →
+ [`mlx-c`](https://github.com/Layr-Labs/mlx-c) → [`mlx-swift`](https://github.com/Layr-Labs/mlx-swift) →
+ [`mlx-swift-lm`](https://github.com/Layr-Labs/mlx-swift-lm)) · created with
+ [Forkdiff](https://github.com/protolambda/forkdiff)
+base:
+ name: ml-explore/mlx-c
+ url: https://github.com/ml-explore/mlx-c
+ # The last upstream commit merged into this fork. CI (`scripts/check_forkdiff.py`)
+ # requires this to equal `git merge-base HEAD upstream/main`. Each upstream merge
+ # moves this hash and re-validates every section below.
+ # Upstream main as of 2026-10-22 (57731b0, bindings for MLX 0.32.4).
+ hash: 57731b00e8bed710e0750e7356da9f18f8eb3e20
+fork:
+ name: Layr-Labs/mlx-c
+ url: https://github.com/Layr-Labs/mlx-c
+ ref: refs/heads/main
+def:
+ title: "Layr-Labs/mlx-c"
+ description: |
+ This is an overview of the changes in [`Layr-Labs/mlx-c`](https://github.com/Layr-Labs/mlx-c),
+ a fork of [`ml-explore/mlx-c`](https://github.com/ml-explore/mlx-c).
+
+ MLX C is the C boundary between the MLX core and every other language binding. Layr-Labs
+ runs an LLM/VLM serving stack on Apple silicon — continuous batching, paged KV caches,
+ MoE and quantized kernels — built as [`mlx-swift-lm`](https://github.com/Layr-Labs/mlx-swift-lm)
+ on [`mlx-swift`](https://github.com/Layr-Labs/mlx-swift), which links a forked
+ [`mlx`](https://github.com/Layr-Labs/mlx) core through this fork. Every change here is a
+ **carry-patch**: a thin C wrapper over a function the forked core added, so Swift can reach
+ it. The upstream API and ABI are left untouched; the fork only adds entry points, and pins
+ the core it builds against to the Layr-Labs revision that provides them.
+
+ Downstream consumers are named per section so a change here can be traced to the Swift
+ symbol that needs it.
+ sub:
+ - title: "Core pin"
+ description: |
+ `CMakeLists.txt` fetches the MLX core from `Layr-Labs/mlx` at an exact commit instead of
+ an upstream release tag. The C functions below wrap core functions that only exist on the
+ fork, so the pin is what makes them link; it is bumped together with the header changes
+ each time the core gains a new entry point.
+ The current pin is `ea318ee0`, the core that Layr-Labs/mlx-swift builds for the cluster
+ stack. It contains main's previous pin `ff4bb35b` and the sealed reduce-scatter and
+ all-gather (`360d11b9`) that `distributed_sealed.cpp` calls.
+ The current pin also preserves 512- and 1024-thread custom Metal launch geometry
+ while retrying an insufficient pipeline with its explicit compiler capacity,
+ orders the fast-synch GPU wait after every pending pass on its queue (a CPU-stream
+ collective between two GPU passes could otherwise leave the GPU spinning forever),
+ and carries 1 MiB JACCL frames, batched buffer retention, a cached custom-kernel
+ source per kernel (host time only), the streamed sealed all-sum (per-piece
+ AES-256-GCM over a two-rank JACCL exchange), opt-in fused fence updates and
+ fenced custom-kernel inputs, and cheaper custom-kernel launches and graph
+ bookkeeping (host time only), and the thread-scoped command-buffer commit limits. The
+ page-backed footprint change is reverted, as on the single-Mac stack.
+ globs:
+ - "CMakeLists.txt"
+ - title: "Memory: allocator observability and footprint policy"
+ description: |
+ The Swift admission code decides whether a request fits by asking the allocator, and the
+ upstream C API only offered independent counters. The fork adds, in order of arrival:
+
+ - `mlx_get_num_resources` / `mlx_get_resource_limit` — the live Metal buffer *count* and
+ its hard ceiling, the quantity behind the `[metal::malloc] Resource limit exceeded`
+ crash (consumed as `Memory.numResources` / `Memory.resourceLimit` in mlx-swift).
+ - `mlx_get_memory_snapshot` — one coherent active/cache/peak observation instead of three
+ separate calls that can straddle an allocation.
+ - `mlx_get_allocation_footprint_policy` and its checked `_bound` / `_maximum_extra`
+ helpers — the allocator's immutable rounding geometry (alignment, rounding threshold,
+ minimum allocation, power-of-two cut-off, cache page size) so callers can compute the
+ real footprint of a requested size without allocating; bound helpers return 1 on an
+ invalid policy or overflow without raising through the error callback.
+ - `mlx_get_allocation_size_upper_bound` — the same bound for the current policy.
+
+ The generator override in `python/mlxhooks.py` keeps `mlx_get_memory_snapshot` intact
+ when the bindings are regenerated from the core headers.
+ globs:
+ - "mlx/c/memory.h"
+ - "mlx/c/memory.cpp"
+ - "python/mlxhooks.py"
+ - title: "Memory: optional process allocation cap"
+ description: |
+ `mlx_install_process_allocation_cap` installs the core's install-once Metal backing cap
+ and `mlx_get_process_allocation_cap_snapshot` reads its ledger (limit, fixed heap, live,
+ cached, pending, unreclaimed, charged and peak bytes). Both forward to the matching core
+ accounting and report failures through the error handler; CPU and CUDA builds refuse.
+ The standalone example checks that interface. Consumed as
+ `Memory.installProcessAllocationCap` / `Memory.processAllocationCapSnapshot` in mlx-swift.
+ globs:
+ - "mlx/c/memory_cap.cpp"
+ - "examples/cap-tests/memory_cap.cpp"
+ - title: "Array: buffer metadata and constant-cache identity"
+ description: |
+ Two non-evaluating inspections the quantized-inference path in mlx-swift relies on:
+
+ - `mlx_array_get_buffer_info` — backing metadata (allocated bytes, data offset, element
+ count, row-contiguity, uniqueness) for an *already evaluated* array. Unavailable backing
+ is reported as `available=false` rather than forcing an eval or a stream sync; views may
+ report shared backing and the fields confer no ownership.
+ `unique` comes from `array::is_uniquely_referenced()` in the Layr-Labs/mlx core: no other
+ array references the array or its data. It does not require MLX to own the buffer, so a
+ wrapped external buffer can be unique (upstream #4634 made `is_donatable()` require
+ ownership).
+ - `_mlx_array_constant_cache_identity` — the backing descriptor's identity plus a
+ transform-safety predicate, so a Swift constant cache can reuse an unchanged constant's
+ exact cast across calls without mistaking a mutated array for its former contents. It
+ refuses compile/autodiff tracing and retained graphs, and never evaluates, hashes, or
+ reads data back. Marked internal: the caller must retain the source descriptor while
+ the identity is cached.
+ globs:
+ - "mlx/c/array.h"
+ - "mlx/c/array.cpp"
+ - title: "Fast: mutable and fenced inputs and per-kernel math modes"
+ description: |
+ - `mlx_fast_metal_kernel_new_mutable` — a second constructor for custom Metal kernels
+ that declares which caller-owned input buffers the kernel writes (the core's
+ mutable-input contract, used for in-place paged KV updates). The existing constructor
+ and its read-only ABI are unchanged.
+ - `mlx_fast_metal_kernel_new_fenced` — the same with fenced inputs: inputs that can come
+ from a CPU stream in the same eval, which the kernel waits for itself (core
+ `metal_kernel_with_fenced_inputs`, opt-in `MLX_METAL_FENCED_INPUTS=1`).
+ - `mlx_fast_metal_kernel_new_with_options` adds an explicit safe, relaxed or fast
+ compiler math mode for one custom kernel, including mutable-input metadata.
+ Legacy constructors remain unchanged; this does not alter process-wide defaults.
+ Non-safe modes require operation-specific numerical and platform qualification.
+ The generator extension retains `new_mutable` and `new_with_options` when bindings
+ regenerate. It does not yet emit `new_fenced` or the prepared-launch functions, so a
+ regeneration must carry those hand edits over.
+ - `mlx_fast_metal_kernel_launch_new` / `_apply` / `_free` — a prepared launch: a kernel
+ bound once to a copied config and applied to new inputs without rebuilding the
+ config (host time only). The kernel must outlive the launch.
+ `MLX_C_BUILD_TESTS` enables constructor/error-contract tests without GPU execution.
+ globs:
+ - "mlx/c/fast.h"
+ - "mlx/c/fast.cpp"
+ - "python/metal_kernel_options.py"
+ - "tests/metal_kernel_options.cpp"
+ - "docs/src/fast.rst"
+ - title: "Stream: cross-thread default streams"
+ description: |
+ MLX 0.32 made the default stream's Metal command encoder thread-local, so a graph built
+ on one thread and evaluated on another — Swift `async/await` continuations, actor
+ executors — aborts with `There is no Stream(gpu, N) in current thread`.
+ `mlx_thread_unsafe_cpu_stream_new` / `mlx_thread_unsafe_gpu_stream_new` expose the
+ core's `new_thread_unsafe_stream`, whose encoder is registered globally, letting
+ mlx-swift restore a single process-wide default stream. "Thread-unsafe" means the caller
+ serializes submission; it is not locked for concurrent multi-thread use.
+ Upstream now binds the same core function as `mlx_stream_new_thread_unsafe(dev)`.
+ The fork keeps its two no-argument names because the Layr-Labs/mlx-swift `Stream`
+ code calls them. Remove them when mlx-swift calls the upstream name.
+ globs:
+ - "mlx/c/stream.h"
+ - "mlx/c/stream.cpp"
+ - title: "Fork tooling"
+ description: |
+ The gate that keeps this page honest: `check_forkdiff.py` fails CI when `base.hash`
+ is not the merge-base with upstream, or when a file the fork changes is not described
+ by a section above. `FORKDIFF.md` explains the day-to-day; the README links the page.
+
+ The fork-diff check and Pages renderer run only on Darkbloom Linux ARM64
+ runners, waiting for compatible capacity instead of using a hosted fallback.
+ Both retain the upstream checks, rendering steps and 20-minute job limits.
+ The protected Pages publication job stays on GitHub-hosted runners.
+ `FORKDIFF.md` documents the queue and qualification limits.
+
+ The disabled native CodeQL workflow scans Actions, C/C++ and Python with
+ the pinned CodeQL 2.27.4 ARM64 bundle and their existing default suites.
+ It requires `CODEQL_NATIVE=on` after an operator switches default setup
+ to advanced setup. The separate GitHub-hosted publisher validates the
+ same run's bounded, fingerprinted SARIF bundle, then uploads the original
+ category identities without checking out or executing repository code.
+ `docs/ci-codeql-native.md` records activation and rollback gates.
+ globs:
+ - ".github/actionlint.yaml"
+ - ".github/workflows/forkdiff-check.yml"
+ - ".github/workflows/forkdiff-pages.yml"
+ - ".github/scripts/codeql_artifacts.py"
+ - ".github/scripts/codeql_artifacts_test.py"
+ - ".github/workflows/codeql-native.yml"
+ - "docs/ci-codeql-native.md"
+ - "scripts/check_forkdiff.py"
+ - "FORKDIFF.md"
+ - "README.md"
+
+ - title: "Cluster bootstrap and sealed collectives"
+ description: |
+ The feature branch carries the bounded owner-provided bootstrap exchange,
+ sealed two-rank all-sum bridge (whole-frame and streamed per-piece codec
+ callbacks, `mlx_distributed_set_streamed_seal_codec`), and the sealed two-rank
+ reduce-scatter and all-gather (`mlx_distributed_reduce_scatter_sealed`,
+ `mlx_distributed_all_gather_sealed`) on the same codec and counter.
+ Bootstrap validates dimensions and sequences but its owner authenticates
+ the channel. Sealed collective callbacks retain their existing no-reentry
+ contract. These
+ pre-existing feature changes remain present when adding startup waits.
+ globs:
+ - "mlx/c/distributed_bootstrap.cpp"
+ - "mlx/c/private/distributed_bootstrap.h"
+ - "mlx/c/distributed_group.h"
+ - "mlx/c/distributed_sealed.cpp"
+ - title: "Distributed: bounded one-shot startup readiness"
+ description: |
+ The begin/end startup-wait C entry points validate group handles and
+ finite 1..900000 ms bounds, then forward to the matching core Group API.
+ Exceptions report through the existing error handler and return failure.
+ The embedding runtime drains work, serializes transitions and retains
+ cancellation, authentication and memory safeguards. CPU-only standalone
+ tests cover argument refusal, forwarding and unsupported backends.
+ globs:
+ - "mlx/c/distributed_group.cpp"
+ - "tests/standalone/*"
+
+# ignored globally, does not count towards line count
+ignore:
+ - "fork.yaml"
+ - ".github/**"