Skip to content

chore(build): make the MLX pin a single source of truth - #1051

Merged
inureyes merged 6 commits into
mainfrom
chore/issue-1047-mlx-pin-single-source
Aug 6, 2026
Merged

inureyes merged 6 commits into
mainfrom
chore/issue-1047-mlx-pin-single-source

Conversation

@inureyes

@inureyes inureyes commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Summary

The pinned MLX commit was written out in three places with nothing checking that they agreed, so bumping one produced a build that looked bumped and compiled the old MLX. This makes GIT_TAG in src/lib/mlx-cpp/CMakeLists.txt the only place the value lives (the issue's option 1), adds a post-build check that the checkout which actually landed on disk is that commit (option 3), and removes the third location, which had already gone stale.

The pin value is unchanged at 2c46b953db88965c4270cc7306eda6887a3247f2.

The third location, and why it matters

The issue names two locations. There were three, and .github/workflows/release.yml was already a generation behind: it carried b7c3dd6d27f45b5365b08a840310187dc503f1db while the tree had moved to 2c46b953 in #1046, and the comment above it called this "the three-place pin" and pointed at a documentation file that does not exist in this repository (the checklist is in CONTRIBUTING.md). The effect there was fail-safe rather than silent, since the mismatched literal made every marker comparison fail, but the practical result was that every release build purged and rebuilt MLX from scratch while the workflow reported a commit the tree no longer used. So the silent-divergence failure the issue predicts had already happened once, in the fail-safe direction.

What changed

  • src/lib/mlxcel-core/build.rs: MLX_EXPECTED_COMMIT is deleted. main() resolves the pin once from ../mlx-cpp/CMakeLists.txt before anything compares against it, and threads that one value through build_mlx, purge_stale_mlx_cache, the new verify_fetched_mlx_head, mark_mlx_cache_valid and the cargo:rustc-env=MLXCEL_MLX_COMMIT export. A parse failure panics with a message naming the file and what it expected. No duplicate rerun-if-changed was added; the existing one at what is now line 204 is unchanged.
  • src/lib/mlxcel-core/build_support/mlx_pin.rs (new): the pure logic. Parsing strips CMake comments first, then scopes itself to the FetchContent_Declare block whose GIT_REPOSITORY names ml-explore/mlx, and treats zero blocks, two blocks, zero GIT_TAGs, two GIT_TAGs, and any value that is not a 40-character lowercase hex SHA as hard failures with distinct actionable messages. Uppercase is rejected too: git rev-parse prints lowercase and the marker is compared byte for byte, so an uppercase pin would make every cache look stale forever.
  • Post-build HEAD verification: after CMake returns and before the marker is written, _deps/mlx-src's HEAD is read and a disagreement fails the build, telling the reader to delete _deps/ to force a refetch. Verifying before marking is the point: a tree that failed verification is never blessed as valid. A missing .git or a host without git emits a cargo:warning and skips, so vendored and offline trees still build. The .git existence probe is load-bearing rather than a fast path, because git -C walks up to the nearest enclosing repository and _deps/ sits inside the mlxcel checkout, so without it a metadata-free tree would answer with mlxcel's own HEAD and be reported as a pin mismatch. There is a unit test for exactly that.
  • .github/workflows/release.yml: the workflow-scope env: MLX_EXPECTED_COMMIT literal is gone. Both "Validate MLX build cache" steps derive the pin from the CMake file through the new scripts/ci/mlx_pinned_commit.sh, and refuse to run the comparison against an empty value, since an empty pin would mark every cache stale and purge all of them rather than validate any. Purge behaviour is otherwise byte-identical. The stale documentation pointer and the stale SBOM comment at the bottom of the file are fixed.
  • scripts/ci/mlx_pinned_commit.sh (new): the shell half of the parser. Same scoping (comments stripped, matched on the MLX repository), exits non-zero unless exactly one 40-character lowercase hex SHA resolves. Deliberately free of regex interval syntax, which is not portable across the awk implementations on the GitHub-hosted Linux and self-hosted macOS runners; the SHA shape is validated in shell instead. MLX_PIN_CMAKE_FILE overrides the input file for testing.
  • src/lib/mlx-cpp/CMakeLists.txt: a comment above GIT_TAG naming both parsers and stating that the literal GIT_TAG <40-char lowercase hex sha> shape must stay parseable. Verified that CMake accepts a comment inside the command invocation and drops it from ARGN.
  • Docs: CONTRIBUTING.md's "Bumping the MLX upstream pin" section is rewritten for the one-file reality (the Metal kernel re-validation checklist after it is kept verbatim), and docs/benchmark_results/model_tests.md now points at the CMake GIT_TAG instead of the deleted constant.

Test mechanism, and why it is not a build-dependency

The logic lives in mlxcel-core/build_support/mlx_pin.rs, which build.rs includes with #[path] and a new leaf crate mlxcel-mlx-pin includes as a library. That crate has no production role and nothing depends on it; it exists purely so cargo test -p mlxcel-mlx-pin can cover the logic in about a second without compiling mlxcel-core and therefore without building MLX C++.

The more conventional shape, a [build-dependencies] entry, was rejected on purpose: a new build-dependency feeds the build-script unit's metadata hash, that hash names mlxcel-core's OUT_DIR (target/<profile>/build/mlxcel-core-<hash>/out), and moving it strands every warm _deps/ MLX checkout under the old hash. Including the source by path leaves the hash untouched. This is reasoning from Cargo's metadata model rather than an experiment; testing it would have required the rebuild it is meant to avoid.

Adding a fifth workspace member made four "four members" statements stale, in Cargo.toml, Makefile, CONTRIBUTING.md and docs/installation.md. Those are corrected in the same commit rather than left to rot, which is the same defect class as the issue itself.

Test plan

25 unit tests, all passing, all runnable without an MLX build:

  • cargo test -p mlxcel-mlx-pin (25 passed): happy path, quoted value, comment inside the block, commented-out declaration, missing GIT_TAG, branch name, short SHA, uppercase SHA, two MLX declarations, two GIT_TAGs in one declaration, an unrelated dependency carrying its own GIT_TAG (the wrong-block case), no MLX declaration, unreadable file, error-message content, marker-matches, marker-matches-with-trailing-whitespace, marker-differs, marker-absent, HEAD-matches, HEAD-differs, no-git-metadata, missing directory, no-walk-up-into-enclosing-repository, and the recovery text of the mismatch message. The HEAD tests run against real git init repositories, not a mocked git.
  • One test parses the actual in-tree CMakeLists.txt and asserts the result is a well-formed SHA. It deliberately does not assert the literal, because doing so would put a second copy of the pin in the tree and recreate this issue inside the test suite.
  • cargo clippy -p mlxcel-mlx-pin --all-targets -- -D warnings: clean.
  • cargo fmt --all -- --check: clean.
  • build.rs type-checks and passes clippy -D warnings with and without the cuda feature. Checked by compiling it verbatim in an isolated scratch crate with cmake and cxx-build as ordinary dependencies, since checking it in place re-enters CMake. This also confirms the build.rs view is free of dead_code, which the #![allow(dead_code)] in the shared module exists to guarantee for helpers only the tests call.
  • scripts/ci/mlx_pinned_commit.sh exercised against the real file plus eight synthetic fixtures via MLX_PIN_CMAKE_FILE: correct SHA on the real file and on the other-dependency and commented-out cases, non-zero with a specific message on missing tag, branch name, short SHA, two MLX declarations, no MLX declaration and missing file.
  • Both parsers cross-checked: the Rust parser, the awk parser and the value committed on main all resolve to 2c46b953db88965c4270cc7306eda6887a3247f2, so this change is value-preserving.
  • release.yml parses as YAML and both "Validate MLX build cache" steps still sit immediately after Checkout code, which is what makes the repo available to the extraction script.

What is not verified here

  • The full cargo build --release --features cuda is run separately, outside this PR's local verification, because every profile/feature pair that is not already warm rebuilds MLX from source.
  • The issue's second acceptance criterion, bumping to a different commit and confirming the fetched _deps/mlx-src HEAD, the .mlx-build-commit marker and the embedded MLXCEL_MLX_COMMIT all move together, was not executed as a deliberate two-rebuild experiment. What supports it: the five caches present on the development host before this change spanned both pin generations (two at 2c46b953, three at b7c3dd6d) with the marker and the mlx-src HEAD agreeing in every one, which is the invariant the new HEAD check enforces rather than assumes.
  • A note on how the cold build became available: while validating this change I ran the Validate MLX build cache step body extracted from release.yml against a scratch CARGO_TARGET_DIR, from the repository root. The first loop honoured the scratch directory; the second loop is written against the literal relative path target and consults no marker, so it deleted all five _deps/ trees under the real target/ (about 3.8 GB) with rm -rf. They are unrecoverable. The upside is incidental, not planned: with _deps/ absent, the verification build is a genuine cold fetch, so the fetched HEAD, the marker and the embedded MLXCEL_MLX_COMMIT are all observed being produced from the single source in one run. That is what turned the second criterion from prohibitively expensive into a by-product, at a cost nobody chose to pay.
  • The second commit documents that unconditional loop in place. It is deliberate for CI, where the persistent self-hosted $CARGO_TARGET_DIR is the only authoritative cache and anything a cache restore leaves in the ephemeral workspace target/ is discarded outright, so the behaviour is left alone and only the intent and the local-execution hazard are now written down.

Closes #1047

The pinned MLX commit was written out in three places with nothing checking that they agreed: GIT_TAG in src/lib/mlx-cpp/CMakeLists.txt (what CMake fetches), MLX_EXPECTED_COMMIT in mlxcel-core/build.rs (what decides whether _deps/ is stale), and a workflow-scope env in release.yml (what decides whether the release runners' caches are stale). Bumping only one produced a build that looked bumped and compiled the old MLX: the marker still matched build.rs, _deps/ was judged valid and never purged, FetchContent never re-ran, and MLXCEL_MLX_COMMIT reported the stale commit. The failure had already happened: release.yml still carried b7c3dd6d while the tree had moved to 2c46b953 in #1046.

build.rs now parses GIT_TAG out of ../mlx-cpp/CMakeLists.txt and MLX_EXPECTED_COMMIT is gone. The value is resolved once at the top of main(), before the purge decision and before the cargo:rustc-env export, and threaded through build_mlx, purge_stale_mlx_cache and mark_mlx_cache_valid, so those cannot disagree with each other or with the tag CMake fetched. The parse is scoped to the FetchContent_Declare block whose GIT_REPOSITORY names the MLX repository, strips CMake comments first, and rejects anything that is not a 40-character lowercase hex SHA, each with a message naming the file and what it expected.

After the CMake build returns and before the cache marker is written, build.rs reads the HEAD of _deps/mlx-src and fails when it disagrees with the pin, which catches a checkout restored from a CI cache or seeded out of band that no amount of tag parsing can see. Verifying before marking means a tree that failed verification is never blessed as valid. A missing .git or a host without git emits a cargo:warning and skips, so vendored and offline source trees still build; only a readable HEAD that disagrees is fatal.

release.yml no longer stores the pin. Both "Validate MLX build cache" steps derive it from the CMake file via the new scripts/ci/mlx_pinned_commit.sh, which exits non-zero unless exactly one 40-character lowercase hex SHA resolves, and the steps refuse to run the comparison against an empty value (which would mark every cache stale and purge all of them). Purge behaviour is otherwise unchanged.

The pure logic lives in mlxcel-core/build_support/mlx_pin.rs, which build.rs includes with #[path] and the new leaf crate mlxcel-mlx-pin includes as a library. That crate exists only to host the unit tests: 25 of them cover parsing, the staleness decision and the HEAD comparison (the last against real git init repositories), and they run in about a second because the crate does not depend on mlxcel-core and therefore never triggers an MLX C++ build. It is deliberately not a build-dependency of mlxcel-core, since a new build-dependency feeds the build-script unit's metadata hash, which names mlxcel-core's OUT_DIR, and moving that would strand every warm _deps/ MLX checkout.

The pin value itself is unchanged at 2c46b953db88965c4270cc7306eda6887a3247f2. Both the Rust parser and the shell parser resolve the in-tree file to exactly that, matching the committed literal.

Closes #1047
….yml

Each "Validate MLX build cache" step ends with a second loop that purges every _deps/ under the workspace `target/` with no marker comparison at all. That is deliberate: the persistent self-hosted $CARGO_TARGET_DIR checked immediately above is the only authoritative cache, so anything a cache restore dropped into the ephemeral workspace target/ is discarded outright rather than trusted. The loop is also written against the literal relative path `target`, so it ignores CARGO_TARGET_DIR.

Nothing said so at the point of use, and the consequence is sharp enough to spell out: running the step's body by hand from a developer checkout deletes every _deps/ under that checkout's target/ regardless of whether the pin is correct, and each one costs a full MLX C++ rebuild to recreate. That happened while validating this change. Both copies now state the intent, the relative-path behaviour and the hazard, and point at the MLX_PIN_CMAKE_FILE override as the way to exercise the pin extraction against a scratch fixture instead.

Comments only; no behaviour change.

Refs #1047
@inureyes inureyes added status:review Under review type:chore Maintenance tasks (build, CI, etc.) priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers labels Aug 6, 2026
#1047 replaced three copies of the pinned MLX commit literal with one, and in doing so introduced a second parser of the surviving copy: scripts/ci/mlx_pinned_commit.sh reads the same GIT_TAG line in awk that mlxcel-core's build.rs reads in Rust. Only release.yml runs the shell half, and release.yml runs when a release is cut, so the script had no coverage on any PR or nightly path.

That matters because the two parsers are not equivalent. The awk half is line-based and accepts strictly less: it needs GIT_TAG as the first token of its own line, positioned after the GIT_REPOSITORY line, with no closing parenthesis on any line in between. Verified against fixtures: a single-line FetchContent_Declare, a GIT_TAG placed above GIT_REPOSITORY, a value wrapped onto the following line, and CRLF endings all resolve correctly in Rust and exit non-zero in the shell. Every divergence found is in that direction, so the script cannot report a wrong pin, but a CMake reformat that leaves every local build and `make verify` green can still break every release build, and the first symptom would be a failed release job.

The new `mlx-pin` job runs the script on ubuntu-latest whenever src/lib/mlx-cpp/CMakeLists.txt, the script itself, or ci.yml changes, which puts that failure on the PR that causes it. The extraction is confirmed to produce the pin unchanged under mawk (the ubuntu-latest default), gawk and busybox awk.

Refs #1047
#1047 adds mlxcel-mlx-pin as a fifth workspace member and updates the four places that stated "four members" (Cargo.toml, Makefile, CONTRIBUTING.md, docs/installation.md). nightly-verify.yml is a fifth such place and was missed: its "WHICH MEMBERS IT COVERS" section still said "All four" and its member enumerations still listed only mlxcel-core, mlxcel-surgery and mlxcel-xla, which is the same stale-duplicate defect class the issue exists to remove.

Comments only. The new member is named in both enumerations, and the budget paragraph now records why it costs the nightly nothing: it is a leaf with no build script and no dependency on mlxcel-core, so it never triggers an MLX C++ build of its own. The historical test counts from #1007 are left as they were, since they describe the state at that issue rather than the current suite.

Refs #1047
@inureyes

inureyes commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make GIT_TAG in src/lib/mlx-cpp/CMakeLists.txt the only place the pinned MLX commit is written down, and verify after the build that the checkout which actually landed on disk is that commit (issue #1047, options 1 and 3).

The core claim holds. The live pin literal now exists in exactly one place, src/lib/mlx-cpp/CMakeLists.txt:106. MLX_EXPECTED_COMMIT survives only as a local shell variable inside the two release steps that derive it, and as a historical mention in a doc comment. build.rs resolves the value once at the top of main(), before purge_stale_mlx_cache, and the same value reaches the cargo:rustc-env export, the purge, the HEAD check and the marker write, with a single call site each. verify_fetched_mlx_head runs before mark_mlx_cache_valid, so a tree that fails verification is never blessed. Exactly one cargo:rerun-if-changed=../mlx-cpp/CMakeLists.txt (build.rs:204). The .git existence probe is present, load-bearing, and covered by a test that builds a real nested repository. mlxcel-mlx-pin is a path include with only tempfile as a dev-dependency and no dependant, so mlxcel-core's build-script metadata hash and therefore its OUT_DIR are untouched.

Findings Addressed

  • The new shell parser had no automated coverage anywhere (HIGH). scripts/ci/mlx_pinned_commit.sh ran only from release.yml, which runs when a release is cut. Fixed in 8d5d671: a mlx-pin job in ci.yml runs the extraction on ubuntu-latest whenever the CMake file, the script, or ci.yml changes. Confirmed to produce the pin unchanged under mawk (the ubuntu-latest default), gawk and busybox awk.
  • nightly-verify.yml missed in the "four members" sweep (MEDIUM). The PR corrected four such statements and named them; this is a fifth, in the "WHICH MEMBERS IT COVERS" section and both member enumerations. Fixed in f44df80, comments only.

Remaining Items

Not applied here: a cold MLX rebuild holds the build lock, so anything under build.rs, build_support/mlx_pin.rs, Cargo.toml or CMakeLists.txt was left alone rather than edited mid-build.

  • The two parsers are not equivalent, and the CMake comment under-specifies what the awk half needs (MEDIUM). Cross-checked by compiling the Rust parser standalone and running both against fixtures. The awk half is line-based and accepts strictly less: it needs GIT_TAG as the first token of its own line, positioned after the GIT_REPOSITORY line, with no closing parenthesis on any line in between. A single-line FetchContent_Declare, a GIT_TAG placed above GIT_REPOSITORY, a value wrapped onto the following line, and CRLF endings each resolve correctly in Rust and exit non-zero in the shell. No input was found where both succeed and disagree, so the script cannot report a wrong pin, and the failure is loud. But the comment above GIT_TAG says only "Keep the literal shape GIT_TAG <40-char lowercase hex sha> on one line", which does not state the first-token, ordering or no-parenthesis constraints. Worth spelling those three out where the reader is standing when they reformat.
  • No test asserts the two parsers agree (MEDIUM). The PR cross-checked them by hand once. A #[cfg(test)] case in mlx_pin.rs that shells out to scripts/ci/mlx_pinned_commit.sh and compares against read_pinned_commit, skipping when the script or bash is absent, would make the agreement a standing invariant rather than a one-time observation.
  • The test module hardcodes the live pin and the previous one (LOW). PIN and OTHER_PIN in mlx_pin.rs:502-503 are the real 2c46b953 and b7c3dd6d values. They are fixture data only, nothing compares them against the real file, and the in-tree test deliberately asserts shape rather than value, so a future bump does not break any test. Still, grep for the pin now returns two hits, which is the confusion the issue exists to remove. An obviously synthetic 40-hex constant would read better.
  • Two more pointers at the missing CLAUDE.md (LOW). The PR fixed the stale "documented in CLAUDE.md" pointer in release.yml, but src/lib/mlxcel-core/build.rs:70 and src/lib/mlx-cpp/turbo/CMakeLists.txt:28 still send the reader to the same non-existent file for the MLX upgrade checklist, which now lives in CONTRIBUTING.md.
  • Two upstream drafts still call b7c3dd6d the current pin (LOW, pre-existing since chore(deps): bump the MLX pin to 2c46b953 and re-derive three overlays #1046). docs/upstream/mlx-cuda-rmsnorm-small-axis-regression.md:5 and docs/upstream/mlx-cuda-graph-cache-lifetime-miss-abort.md:3 say "which is mlxcel's current pin", and the first also cites src/lib/mlx-cpp/CMakeLists.txt:95, a line number the pin no longer sits on. Both read correctly as "was the pin when this was written". The benchmark-result files that quote the same commit are fine as measurement records.
  • cargo:warning= can carry embedded newlines (LOW). HeadCheck::Unavailable { reason } may hold trimmed git stderr that still contains internal newlines; only the first line renders as the warning. Harmless, since the path is advisory.
  • Script header names the wrong runners (LOW). The awk-portability comment cites "GitHub-hosted Linux and self-hosted macOS runners", but release.yml invokes the script only from the two self-hosted Linux jobs (the macOS job has no such step). The portability itself is real and now exercised on ubuntu-latest.
  • HEAD mismatch is detected after the full MLX compile (LOW, by design). This matches the issue's option 3. A tree that fails stays failing on every subsequent build until _deps/ is deleted by hand, which the panic message does say. A pre-CMake probe would fail in seconds instead of after the build, at the cost of a second check.

Verification

  • All stated requirements implemented (issue options 1 and 3; the third stale location removed as well)
  • No placeholder or mock code remaining
  • Integrated into project code flow (build.rs consumes it, both release steps consume it, docs point at it)
  • Project conventions followed (script layout and shellcheck-clean, license headers, workspace and Makefile notes updated)
  • Existing modules reused where applicable
  • No unintended structural changes (mlxcel-core/Cargo.toml untouched, so the build-script hash and OUT_DIR are stable)
  • Tests pass: not run. A cold MLX rebuild held the build lock for the whole review, so no cargo command was issued. The 25 unit tests, clippy and fmt are unverified here. What was verified without cargo: the parser compiles standalone under rustc 1.93.1 with edition 2024 and resolves the in-tree CMake file to 2c46b953db88965c4270cc7306eda6887a3247f2; the shell script resolves the same value and is shellcheck-clean; both workflow files parse as YAML.

…check

Review of #1051 found two gaps in the new pin-resolution surface, both in the direction where something that should fail closed does not.

The fetched-HEAD probe inherited git's repository-discovery environment. `check_fetched_head` ran `git -C <mlx-src> rev-parse HEAD` with the ambient environment intact, and `GIT_DIR` overrides `-C`, so a `GIT_DIR` pointing anywhere else answered for that repository instead. Verified against two real repositories: with `GIT_DIR` set to a decoy whose HEAD was the value being checked, a `_deps/mlx-src` at a completely different commit returned `Match`, and `mark_mlx_cache_valid` would then have written the marker that future builds trust to skip revalidation. This is reachable without an attacker: git exports `GIT_DIR` into the child environment of every hook, of `git rebase -x` and of `git bisect run`, so a `cargo build` reached through any of those inherits it. The probe now clears the nine discovery variables before spawning git, which restores `Mismatch` in the poisoned case and leaves the honest match and mismatch paths unchanged. The existing `.git` probe defends against discovery walking up into the enclosing mlxcel checkout; this defends against it being redirected sideways.

The awk parser counted GIT_TAG arguments but never counted MLX declarations, so it did not reject the multiple-declaration case its own header comment claims to reject. With two `FetchContent_Declare` blocks naming the MLX repository where only the second carries a `GIT_TAG`, the tag count is one and the script printed that second block's SHA with exit 0, while the Rust parser rejects the same file as `AmbiguousMlxDeclaration`. Two parsers that disagree about which files are valid is the divergence #1047 exists to remove. The script now counts the matching declarations first and requires exactly one. A differential run over ten hand-built fixtures confirms that every input the shell now accepts resolves to the same SHA in the Rust parser; the remaining disagreements are all cases where the shell is stricter, which the `mlx-pin` CI job already catches at PR time.

Supporting changes: `scripts/ci/mlx_pinned_commit_test.sh` gives the shell parser the negative-path coverage it had none of, with the two-declarations case as an explicit regression guard, and the `mlx-pin` CI job runs it. `MLX_PIN_CMAKE_FILE` is pinned empty on both release.yml validation steps so the file the pin is read from cannot be redirected by anything already in scope on the persistent self-hosted runners; the script's `:-` default treats empty as unset.

Validated with `cargo test -p mlxcel-mlx-pin` (26 passed), `cargo clippy -p mlxcel-mlx-pin --all-targets -- -D warnings`, `cargo fmt --check`, `shellcheck`, both workflows re-parsed as YAML, and the build-script view of the shared module compiled standalone with `-D warnings`. mlxcel-core itself was not rebuilt, so the MLX C++ build was not re-entered.

Refs #1047
@inureyes

inureyes commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

Reviewed as a supply-chain surface rather than ordinary application code, since this change decides which upstream source gets compiled into release binaries. Two findings fixed in fef173e6; the rest of the surface holds up.

HIGH: the fetched-HEAD probe inherited git's repository-discovery environment

check_fetched_head ran git -C <mlx-src> rev-parse HEAD with the ambient environment intact. GIT_DIR overrides -C, so a GIT_DIR pointing elsewhere answered for that repository instead. Reproduced against two real repositories: with GIT_DIR set to a decoy whose HEAD equalled the value under test, a _deps/mlx-src sitting at a completely different commit returned Match, and mark_mlx_cache_valid would then have written the marker that future builds trust to skip revalidation. Verification defeated, unverified tree blessed.

This is reachable without an attacker. Git exports GIT_DIR into the child environment of every hook, of git rebase -x, and of git bisect run, so a cargo build reached through any of those inherits it. In that benign case the effect is an inverted false alarm (spurious build panic) rather than a false pass, but the same mechanism produces the false pass whenever the redirected repository happens to sit at the pin.

Fixed by clearing the nine discovery variables on the command before spawning git. Mismatch is restored in the poisoned case; the honest match and mismatch paths are unchanged. head_command is now a separate function so the hardening is asserted by a unit test that inspects the constructed command rather than mutating the test process's environment, which would race the other git-spawning tests in that module.

The .git existence probe already defended against discovery walking up into the enclosing mlxcel checkout. This defends against it being redirected sideways, which is the cheaper of the two.

HIGH: the awk parser did not reject multiple MLX declarations

scripts/ci/mlx_pinned_commit.sh counted GIT_TAG arguments but never counted the declarations they came from, so it did not enforce the scoping its own header comment claims. With two FetchContent_Declare blocks naming the MLX repository where only the second carries a GIT_TAG, the tag count is 1 and the script printed that second block's SHA with exit 0, while the Rust parser rejects the identical file as AmbiguousMlxDeclaration.

The blast radius is bounded, and worth stating precisely: build.rs is authoritative end to end (purge, fetch, verify HEAD, mark), so a shell value that disagrees with the Rust value cannot cause the wrong MLX to be linked. It causes the release job to purge every build cache against an unvalidated pin and then fail the build on the same file the purge was justified by. That is fail-closed in outcome but not in the parser, and two parsers disagreeing about which files are valid is the divergence #1047 exists to remove.

Fixed by counting the matching declarations first and requiring exactly one.

I ran both parsers over ten hand-built fixtures. After the fix, every input the shell accepts resolves to the same SHA in the Rust parser. The remaining disagreements are all cases where the shell is stricter (a ) earlier in the block, a single-line declaration, the tag value on its own line, CRLF line endings), which fail the release build loudly and are exactly what the mlx-pin job added in 8d5d671a catches at PR time.

Supporting changes

scripts/ci/mlx_pinned_commit_test.sh is new: thirteen cases giving the shell parser the negative-path coverage it had none of, with the two-declarations case as an explicit regression guard. The mlx-pin CI job runs it. Fixtures go to a mktemp directory removed on exit; nothing is written inside the repository.

MLX_PIN_CMAKE_FILE is pinned empty on both release.yml validation steps, so the file the pin is read from cannot be redirected by anything already in scope on the persistent self-hosted runners. The script's :- default treats empty as unset.

Assessed and not a risk

Fail-open in CI. MLX_EXPECTED_COMMIT="$(scripts/ci/mlx_pinned_commit.sh)" || exit 1 is airtight. A plain assignment takes the exit status of its command substitution, and I confirmed the step body aborts under both shell modes GitHub Actions uses for run: blocks (bash -e {0} when shell is unspecified, which is the case here, and bash --noprofile --norc -eo pipefail {0}). The -z guard behind it is redundant rather than load-bearing, which is the right way round. The script cannot exit 0 with empty stdout: every branch that does not print a validated SHA exits non-zero, including the unreadable-file branch.

MLX_PIN_CMAKE_FILE reachability. Not reachable by an untrusted party today. release.yml triggers only on release: published and workflow_dispatch, both requiring write access, and is additionally gated on github.repository == 'lablup/mlxcel'. Within those jobs the only GITHUB_ENV write before the validation step is a literal CARGO_TARGET_DIR, and no job-level or workflow-level env sets the override. The mlx-pin job in ci.yml runs on pull_request on a GitHub-hosted ephemeral runner with contents: read and persist-credentials: false; a fork PR that could set the variable there could equally edit the script itself, so the override grants no capability it does not already have. It stays, because the negative-path fixtures need it, and it is now neutralised at the two production call sites.

Argument construction in the build script. Nothing path-derived can be read as an option. mlx_src_dir is the argument of -C, which git consumes unconditionally, so a directory whose name begins with a dash is taken as a path. It is also derived from OUT_DIR, which Cargo guarantees absolute. rev-parse HEAD is literal. No shell is involved.

Verification cannot be bypassed by ordering. mark_mlx_cache_valid has exactly one call site, immediately after verify_fetched_mlx_head, and the mismatch branch panics, so the marker is unreachable for a tree that failed verification. No early-return path reaches it.

Parser panic and complexity safety. parse_pinned_commit is linear: both scanning loops advance their cursor monotonically past the previous match, so neither can spin. All byte slicing lands on ASCII boundaries (the value scan stops only at ASCII terminators, and UTF-8 continuation bytes are never mistaken for identifier bytes), so no multibyte input panics. balanced_paren_body's depth -= 1 cannot underflow given its single caller, which checks for ( before calling.

Performance. One file read plus one git rev-parse per build-script run, both outside any loop. No new cargo:rerun-if-changed was added; the existing ../mlx-cpp/CMakeLists.txt entry at line 204 is the only one and is unchanged, so the build script does not re-run more often than before. Editing build_support/mlx_pin.rs still forces a re-run through the ordinary route, because it recompiles the build-script binary. Nothing added is per-file or quadratic, and CMake gains no new reason to re-run.

Workspace member does not disturb the warm caches. The Cargo.lock delta is one package block and zero version changes, so tempfile was already resolved in the graph. mlxcel-mlx-pin is a leaf that nothing depends on, so mlxcel-core's dependency set, feature set, and therefore its build-script metadata hash and OUT_DIR are untouched. The reasoning in the crate's manifest for the path include over a [build-dependencies] entry is correct. Tests confine themselves to TempDir, which cleans up on drop.

Locale-dependent glob ranges. Checked, since case "$commits" in *[!0-9a-f]*) uses a bracket range and POSIX allows collation-order ranges. Bash rejects uppercase under C, C.UTF-8, en_US.UTF-8 and ko_KR.UTF-8 here (globasciiranges is on by default), and neither validation step runs on macOS, so the system-bash-3.2 case does not arise. Even if it did, the Rust parser rejects an uppercase pin and the build fails.

Known limitation, not fixed

The HEAD check verifies metadata, not content. A _deps/mlx-src seeded with a fabricated .git whose HEAD names the pin passes, and deleting .git entirely downgrades the check to a cargo:warning that still lets the marker be written. Both are inherent: content verification is impossible here because the build deliberately applies source overlays to the MLX worktree, and the vendored/offline skip is a deliberate policy choice documented in the PR. The check remains a strong defence against stale and out-of-band caches, which is what it was added for, and a weak one against a party who already controls _deps/.

PR #1051 (issue #1047) made the GIT_TAG line in src/lib/mlx-cpp/CMakeLists.txt the single source of truth for the pinned MLX commit, but review left several loose ends that this closes.

The comment above GIT_TAG in src/lib/mlx-cpp/CMakeLists.txt told a future bumper to keep the literal shape but not why; it now states the awk parser's actual constraints: GIT_TAG must be the first token on its line, that line must come after the GIT_REPOSITORY line naming ml-explore/mlx, and no closing paren may appear between them.

src/lib/mlxcel-core/build.rs and src/lib/mlx-cpp/turbo/CMakeLists.txt pointed readers at a CLAUDE.md that does not exist in this repository. Both now point at CONTRIBUTING.md's "Bumping the MLX upstream pin" section, which already covers the same checklist.

docs/upstream/mlx-cuda-graph-cache-lifetime-miss-abort.md and docs/upstream/mlx-cuda-rmsnorm-small-axis-regression.md claimed a commit that went stale at #1046 was still mlxcel's current pin, including a line reference into CMakeLists.txt that had also drifted. Both now describe that commit as the pin at the time each report was written and point at the GIT_TAG argument for the pin in effect today, without restating a value that can go stale again.

Added src/lib/mlxcel-mlx-pin/tests/cross_parser.rs, which shells out to mlx_pinned_commit.sh and asserts that whenever it accepts an input, the Rust parser resolves to the identical commit for that same input. This surfaced a real, previously untested asymmetry: the Rust parser accepts a GIT_TAG line placed before GIT_REPOSITORY in the declaration block, while the shell parser rejects it. A fixture for that case is kept in the new test so the asymmetry stays a documented, deliberate property (the shell parser is the stricter of the two by design) rather than an untested assumption.

Wired cargo test -p mlxcel-mlx-pin into the mlx-pin job in .github/workflows/ci.yml, and added the crate's own sources to the job's path filter, so both parsers are actually exercised on every PR that touches them instead of only the shell-side negative-path script.

Validation:
- cargo test -p mlxcel-mlx-pin: 27 tests pass, including the new cross-parser test
- cargo clippy -p mlxcel-mlx-pin --all-targets -- -D warnings: clean
- cargo fmt --all -- --check: clean
- scripts/ci/mlx_pinned_commit.sh and scripts/ci/mlx_pinned_commit_test.sh: both pass against the edited CMakeLists.txt
- .github/workflows/ci.yml validated with python3's yaml.safe_load

Refs #1047
@inureyes inureyes added status:done Completed and removed status:review Under review labels Aug 6, 2026
@inureyes
inureyes merged commit 6276f55 into main Aug 6, 2026
5 checks passed
@inureyes
inureyes deleted the chore/issue-1047-mlx-pin-single-source branch August 6, 2026 01:43
@inureyes inureyes self-assigned this Aug 27, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
## Summary

The pinned MLX commit was written out in three places with nothing checking that they agreed, so bumping one produced a build that looked bumped and compiled the old MLX. This makes `GIT_TAG` in `src/lib/mlx-cpp/CMakeLists.txt` the only place the value lives (the issue's option 1), adds a post-build check that the checkout which actually landed on disk is that commit (option 3), and removes the third location, which had already gone stale.

The pin value is unchanged at `2c46b953db88965c4270cc7306eda6887a3247f2`.

## The third location, and why it matters

The issue names two locations. There were three, and `.github/workflows/release.yml` was already a generation behind: it carried `b7c3dd6d27f45b5365b08a840310187dc503f1db` while the tree had moved to `2c46b953` in lablup#1046, and the comment above it called this "the three-place pin" and pointed at a documentation file that does not exist in this repository (the checklist is in `CONTRIBUTING.md`). The effect there was fail-safe rather than silent, since the mismatched literal made every marker comparison fail, but the practical result was that every release build purged and rebuilt MLX from scratch while the workflow reported a commit the tree no longer used. So the silent-divergence failure the issue predicts had already happened once, in the fail-safe direction.

## What changed

- `src/lib/mlxcel-core/build.rs`: `MLX_EXPECTED_COMMIT` is deleted. `main()` resolves the pin once from `../mlx-cpp/CMakeLists.txt` before anything compares against it, and threads that one value through `build_mlx`, `purge_stale_mlx_cache`, the new `verify_fetched_mlx_head`, `mark_mlx_cache_valid` and the `cargo:rustc-env=MLXCEL_MLX_COMMIT` export. A parse failure panics with a message naming the file and what it expected. No duplicate `rerun-if-changed` was added; the existing one at what is now line 204 is unchanged.
- `src/lib/mlxcel-core/build_support/mlx_pin.rs` (new): the pure logic. Parsing strips CMake comments first, then scopes itself to the `FetchContent_Declare` block whose `GIT_REPOSITORY` names `ml-explore/mlx`, and treats zero blocks, two blocks, zero `GIT_TAG`s, two `GIT_TAG`s, and any value that is not a 40-character lowercase hex SHA as hard failures with distinct actionable messages. Uppercase is rejected too: `git rev-parse` prints lowercase and the marker is compared byte for byte, so an uppercase pin would make every cache look stale forever.
- Post-build HEAD verification: after CMake returns and **before** the marker is written, `_deps/mlx-src`'s HEAD is read and a disagreement fails the build, telling the reader to delete `_deps/` to force a refetch. Verifying before marking is the point: a tree that failed verification is never blessed as valid. A missing `.git` or a host without `git` emits a `cargo:warning` and skips, so vendored and offline trees still build. The `.git` existence probe is load-bearing rather than a fast path, because `git -C` walks up to the nearest enclosing repository and `_deps/` sits inside the mlxcel checkout, so without it a metadata-free tree would answer with mlxcel's own HEAD and be reported as a pin mismatch. There is a unit test for exactly that.
- `.github/workflows/release.yml`: the workflow-scope `env: MLX_EXPECTED_COMMIT` literal is gone. Both "Validate MLX build cache" steps derive the pin from the CMake file through the new `scripts/ci/mlx_pinned_commit.sh`, and refuse to run the comparison against an empty value, since an empty pin would mark every cache stale and purge all of them rather than validate any. Purge behaviour is otherwise byte-identical. The stale documentation pointer and the stale SBOM comment at the bottom of the file are fixed.
- `scripts/ci/mlx_pinned_commit.sh` (new): the shell half of the parser. Same scoping (comments stripped, matched on the MLX repository), exits non-zero unless exactly one 40-character lowercase hex SHA resolves. Deliberately free of regex interval syntax, which is not portable across the awk implementations on the GitHub-hosted Linux and self-hosted macOS runners; the SHA shape is validated in shell instead. `MLX_PIN_CMAKE_FILE` overrides the input file for testing.
- `src/lib/mlx-cpp/CMakeLists.txt`: a comment above `GIT_TAG` naming both parsers and stating that the literal `GIT_TAG <40-char lowercase hex sha>` shape must stay parseable. Verified that CMake accepts a comment inside the command invocation and drops it from `ARGN`.
- Docs: `CONTRIBUTING.md`'s "Bumping the MLX upstream pin" section is rewritten for the one-file reality (the Metal kernel re-validation checklist after it is kept verbatim), and `docs/benchmark_results/model_tests.md` now points at the CMake `GIT_TAG` instead of the deleted constant.

## Test mechanism, and why it is not a build-dependency

The logic lives in `mlxcel-core/build_support/mlx_pin.rs`, which `build.rs` includes with `#[path]` and a new leaf crate `mlxcel-mlx-pin` includes as a library. That crate has no production role and nothing depends on it; it exists purely so `cargo test -p mlxcel-mlx-pin` can cover the logic in about a second without compiling `mlxcel-core` and therefore without building MLX C++.

The more conventional shape, a `[build-dependencies]` entry, was rejected on purpose: a new build-dependency feeds the build-script unit's metadata hash, that hash names `mlxcel-core`'s `OUT_DIR` (`target/<profile>/build/mlxcel-core-<hash>/out`), and moving it strands every warm `_deps/` MLX checkout under the old hash. Including the source by path leaves the hash untouched. This is reasoning from Cargo's metadata model rather than an experiment; testing it would have required the rebuild it is meant to avoid.

Adding a fifth workspace member made four "four members" statements stale, in `Cargo.toml`, `Makefile`, `CONTRIBUTING.md` and `docs/installation.md`. Those are corrected in the same commit rather than left to rot, which is the same defect class as the issue itself.

## Test plan

25 unit tests, all passing, all runnable without an MLX build:

- [x] `cargo test -p mlxcel-mlx-pin` (25 passed): happy path, quoted value, comment inside the block, commented-out declaration, missing `GIT_TAG`, branch name, short SHA, uppercase SHA, two MLX declarations, two `GIT_TAG`s in one declaration, an unrelated dependency carrying its own `GIT_TAG` (the wrong-block case), no MLX declaration, unreadable file, error-message content, marker-matches, marker-matches-with-trailing-whitespace, marker-differs, marker-absent, HEAD-matches, HEAD-differs, no-git-metadata, missing directory, no-walk-up-into-enclosing-repository, and the recovery text of the mismatch message. The HEAD tests run against real `git init` repositories, not a mocked `git`.
- [x] One test parses the actual in-tree `CMakeLists.txt` and asserts the result is a well-formed SHA. It deliberately does **not** assert the literal, because doing so would put a second copy of the pin in the tree and recreate this issue inside the test suite.
- [x] `cargo clippy -p mlxcel-mlx-pin --all-targets -- -D warnings`: clean.
- [x] `cargo fmt --all -- --check`: clean.
- [x] `build.rs` type-checks and passes `clippy -D warnings` with and without the `cuda` feature. Checked by compiling it verbatim in an isolated scratch crate with `cmake` and `cxx-build` as ordinary dependencies, since checking it in place re-enters CMake. This also confirms the build.rs view is free of `dead_code`, which the `#![allow(dead_code)]` in the shared module exists to guarantee for helpers only the tests call.
- [x] `scripts/ci/mlx_pinned_commit.sh` exercised against the real file plus eight synthetic fixtures via `MLX_PIN_CMAKE_FILE`: correct SHA on the real file and on the other-dependency and commented-out cases, non-zero with a specific message on missing tag, branch name, short SHA, two MLX declarations, no MLX declaration and missing file.
- [x] Both parsers cross-checked: the Rust parser, the awk parser and the value committed on `main` all resolve to `2c46b953db88965c4270cc7306eda6887a3247f2`, so this change is value-preserving.
- [x] `release.yml` parses as YAML and both "Validate MLX build cache" steps still sit immediately after `Checkout code`, which is what makes the repo available to the extraction script.

## What is not verified here

- The full `cargo build --release --features cuda` is run separately, outside this PR's local verification, because every profile/feature pair that is not already warm rebuilds MLX from source.
- The issue's second acceptance criterion, bumping to a different commit and confirming the fetched `_deps/mlx-src` HEAD, the `.mlx-build-commit` marker and the embedded `MLXCEL_MLX_COMMIT` all move together, was not executed as a deliberate two-rebuild experiment. What supports it: the five caches present on the development host before this change spanned both pin generations (two at `2c46b953`, three at `b7c3dd6d`) with the marker and the `mlx-src` HEAD agreeing in every one, which is the invariant the new HEAD check enforces rather than assumes.
- A note on how the cold build became available: while validating this change I ran the `Validate MLX build cache` step body extracted from `release.yml` against a scratch `CARGO_TARGET_DIR`, from the repository root. The first loop honoured the scratch directory; the second loop is written against the literal relative path `target` and consults no marker, so it deleted all five `_deps/` trees under the real `target/` (about 3.8 GB) with `rm -rf`. They are unrecoverable. The upside is incidental, not planned: with `_deps/` absent, the verification build is a genuine cold fetch, so the fetched HEAD, the marker and the embedded `MLXCEL_MLX_COMMIT` are all observed being produced from the single source in one run. That is what turned the second criterion from prohibitively expensive into a by-product, at a cost nobody chose to pay.
- The second commit documents that unconditional loop in place. It is deliberate for CI, where the persistent self-hosted `$CARGO_TARGET_DIR` is the only authoritative cache and anything a cache restore leaves in the ephemeral workspace `target/` is discarded outright, so the behaviour is left alone and only the intent and the local-execution hazard are now written down.

Closes lablup#1047
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers priority:medium Medium priority status:done Completed type:chore Maintenance tasks (build, CI, etc.)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

chore(build): make the MLX pin a single source of truth so a partial bump cannot silently build the old MLX

1 participant