Skip to content

fix(test): skip partial Muse Glimmer checkpoints instead of panicking - #1173

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-1161-pinned-checkpoint-skip-guard
Aug 15, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-1161-pinned-checkpoint-skip-guard

Conversation

@inureyes

@inureyes inureyes commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

Post-merge correction (2026-08-16). This body was corrected after merge. As originally written it justified the file split with a "500-line limit" that is not this repository's convention, and its test counts and run results described only the first of the four commits on this branch. The squash commit on main (0adb53c5) still carries the original wording, since commit messages cannot be edited after merge; where the two disagree, this body is the accurate one. The threshold question is tracked in #1178, and the incorrect rationale is also recorded in TECHNICAL_REPORTS/1173-pinned-checkpoint-skip-guard-20260816.en.md.

Summary

pinned_post_tower_weight_roots_and_shapes_match_published_contract skipped gracefully only when model.safetensors.index.json was absent. With the index present but anything else it reads missing or corrupt, the shape an interrupted hf download or mlxcel download leaves behind, it unwrapped its way to an opaque panic instead of skipping with a reason. This adds an availability pre-check that names the offending file, while leaving every contract assertion able to fail exactly as before.

Implementation choice

The issue offered two options; this is the hybrid the brief recommended. Option 1 alone (a pure existence pre-check) cannot detect a shard that exists but whose header was truncated mid-download, and option 2 alone (converting each unwrap into a skip) reads the index twice, which the issue explicitly asked to avoid. The hybrid gets both: load_pinned_checkpoint parses the index once and hands the parsed weight_map to the assertion body, and safetensors_shape returns a Result so header corruption is covered too.

How the correctness boundary is kept

The skip is deliberately narrow, and the split is enforced by construction rather than by convention.

  • Only availability and readability may skip: an absent file, an unreadable file, JSON that does not parse, a truncated or unparseable safetensors header. load_pinned_checkpoint returns Err for exactly these, and read_checkpoint_file distinguishes "not present" from "could not be read" so the message names the path either way.
  • Contract violations still fail. The assert_eq! calls are untouched and are not wrapped in any skip path. load_pinned_checkpoint is structured so it cannot swallow one: a weight_map that is absent or non-object yields an empty map (which drives the weight-root assertion to fail, not to skip), and a pinned key absent from an otherwise well-formed weight_map is skipped over by the shard loop with a comment saying why, so the weight-root assertion is what reports it.
  • config.json is parsed as plain JSON only in the pre-check, so a truncated config still skips, while deserializing into MuseGlimmerConfig happens next to validate() in the assertion body, where a schema mismatch panics. A config that parses but does not fit the schema means the pinned directory holds a wrong or drifted model, which is a contract violation rather than an availability problem. This was corrected in review; the first commit deserialized in the pre-check and therefore skipped on schema drift.
  • Inside safetensors_shape, a header that parses but does not describe the key as a shaped tensor panics rather than returning Err, following the issue's "if unsure whether it is missing or wrong, it is wrong" rule.
  • The contract assertions moved into assert_post_tower_contract, which takes an already-validated PinnedCheckpoint. It holds one skip branch only, for a shard header that cannot be read, which is scoped to availability by construction because those are the only conditions under which safetensors_shape returns Err. That split is what makes the four should_panic tests below possible.

What changed

  • src/vision/encoders/muse_glimmer_fusion_pinned_tests.rs (new, 603 lines): the pinned-checkpoint contract check, the load_pinned_checkpoint availability pre-check, a Result-returning safetensors_shape, and synthetic partial-checkpoint coverage. safetensors_shape bounds the declared header length twice before allocating: against an absolute MAX_SAFETENSORS_HEADER_BYTES ceiling of 256 MiB, mirroring the guard the production reader already applies in src/lib/mlxcel-core/src/weights.rs:196, and against the file's own size. The absolute ceiling was added in review: the file-relative bound alone permits a declared header as large as the whole file, and the pinned shards are 50 GB and 9.6 GB, so a corrupt eight-byte prefix could have reached an uncatchable allocation abort.
  • src/vision/encoders/muse_glimmer_fusion_tests.rs: the pinned block and its now-unused imports removed, leaving 196 lines of fusion-math tests.
  • src/vision/encoders/muse_glimmer_fusion.rs: attaches pinned_tests as a second #[cfg(test)] module, the same pattern src/vision/mod.rs already uses. The split separates disk-reading contract checks from fusion math and follows the established #[cfg(test)] #[path] sibling-module convention. Both files sit under the repository's actual 800-line single-file guideline (.claude/skills/mlxcel-code-structure/SKILL.md), at 196 and 603 lines.

Test-only change. No production loading path is touched, and src/loading/vlm_muse_glimmer_tests.rs is untouched as the issue required.

Synthetic-checkpoint tests

The real pinned checkpoint is either complete or absent, so the partial cases cannot be exercised against it, and nothing under models/ may be moved or truncated to fake one. All seventeen new tests build throwaway checkpoints in tempfile::tempdir() (already a dev-dependency, no new dependency added). The pinned module now holds 18 tests in total, the eighteenth being the pre-existing contract check that moved here.

Pre-check names the specific missing or unreadable file: pinned_precheck_names_an_absent_index, pinned_precheck_names_a_missing_config, pinned_precheck_names_a_missing_shard (index present naming a shard that does not exist), pinned_precheck_names_an_unparseable_index, pinned_precheck_names_an_unparseable_config, and pinned_precheck_accepts_a_complete_synthetic_checkpoint as the negative control.

Pre-check refuses to swallow contract violations: pinned_precheck_leaves_a_missing_weight_root_to_the_contract_assertion, pinned_precheck_leaves_an_absent_weight_map_to_the_contract_assertion, and pinned_precheck_leaves_a_schema_mismatched_config_to_the_contract_assertion each assert the pre-check returns Ok, so the violation reaches the assertion.

Contract violations still fail, proven executably rather than by reading the diff. Four #[should_panic] tests run assert_post_tower_contract over complete-but-wrong synthetic checkpoints: contract_assertion_still_fails_on_a_missing_weight_root, contract_assertion_still_fails_on_an_absent_weight_map, contract_assertion_still_fails_on_a_schema_mismatched_config, and contract_assertion_still_fails_on_a_wrong_recorded_shape. The last one expects the failed: prefix that assert_eq! emits before its custom message, so it can only pass on the shape assertion itself; a bare key name would also match the weight-root assertion and the "must name a shard" panic, letting it pass for the wrong reason.

Header handling: safetensors_shape_reads_a_well_formed_header, safetensors_shape_reports_a_truncated_header, safetensors_shape_reports_an_unparseable_header, and safetensors_shape_refuses_a_header_over_the_allocation_ceiling, which declares u64::MAX in a tiny temp file so the test itself allocates nothing large.

Optional env var

MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 is implemented. It is read inside skip_or_fail_pinned_checkpoint under crate::test_support::env_lock::env_lock(), held for the duration of the read and dropped before the assertion, because this crate is edition 2024 and src/server/muse_glimmer_startup_guard_tests.rs mutates the process environment with unsafe set_var under that same lock; an unlocked read is the same class of race being fixed elsewhere in this chain. Only the exact value 1 enables it.

It also turned out to be the cleanest way to prove acceptance criterion 2 on this machine: with skips disabled, the pinned test passing is positive evidence that it read the real checkpoint rather than silently skipping.

Follow-up #1177 tracks extending this gate to the loading-side sibling guard, which does not yet honor it, and documenting the variable in docs/environment-variables.md.

Test plan

Results below are for the merged branch tip, all four commits.

  • cargo test --lib vision::encoders::muse_glimmer_fusion on a machine holding the real pinned checkpoint: 23 passed; 0 failed (18 in the pinned module, 5 fusion-math).
  • MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 cargo test --lib vision::encoders::muse_glimmer_fusion: 23 passed; 0 failed. Since any skip is a hard failure under this variable, this confirms the full pinned checkpoint still validates the weight-root and shape contract for real (criterion 2).
  • Test binary run from a directory containing no models/: skips with Skipping pinned_post_tower_weight_roots_and_shapes_match_published_contract: models/mlx/muse-glimmer-30b/model.safetensors.index.json is not present (criterion 3, behavior unchanged).
  • Same run with MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1: fails with MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 but the pinned Muse Glimmer checkpoint is not usable: ... is not present (criterion 4).
  • cargo clippy --lib --tests -- -D warnings: clean.
  • cargo check --lib --tests: clean.
  • cargo fmt --check: clean.
  • Nothing under models/ or /home/inureyes/models was moved, renamed, deleted, truncated, or written to; both 50 GB and 9.6 GB shards verified present afterwards with their original timestamps.

Closes #1161

`pinned_post_tower_weight_roots_and_shapes_match_published_contract` skipped gracefully only when `model.safetensors.index.json` was absent. With the index present but anything else it reads missing or corrupt, the shape an interrupted `hf download` or `mlxcel download` leaves behind, it unwrapped its way to an opaque panic: `config.json`, the index body, and every referenced safetensors shard were read with `unwrap`.

An availability pre-check now parses the index once and shares it with the assertion body, confirming that `config.json` and each shard named for a pinned weight root is present and readable before anything is asserted. `safetensors_shape` returns a `Result`, so a truncated or unparseable shard header also skips rather than panicking, and it bounds the declared header length against the file size before allocating. Every skip message names the offending path.

The skip stays deliberately narrow. Only availability and readability may skip: an absent file, an unreadable file, JSON that does not parse, a truncated header. Contract violations still fail, so a `weight_map` missing a pinned root, a config `validate()` rejects, and a shard whose recorded shape disagrees with the config all reach the unchanged `assert_eq!` calls. Two `should_panic` tests over synthetic checkpoints prove that boundary holds, and six more assert the pre-check names the specific missing file.

Adds opt-in `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`, read under the crate-wide env lock, which turns skips into failures so a corrupted checkpoint cannot quietly disable the contract check forever on the machine that owns it.

The pinned block moves to `muse_glimmer_fusion_pinned_tests.rs`, attached as a second test module, because it reads files off disk rather than exercising fusion math and the synthetic coverage would otherwise push the original file well past 500 lines.

Validated on a machine holding the real pinned checkpoint: `cargo test --lib vision::encoders::muse_glimmer_fusion` passes 19/19, and passes again under `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`, which proves the contract path executed rather than skipping. Running the test binary from a directory without `models/` skips with the named reason, and fails under the env var. Nothing under `models/` was moved or modified; all partial checkpoints are synthesized in `tempfile::tempdir()`.

Refs #1161
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:low Low priority area:models Model architectures, weights, loading, metadata status:review Under review labels Aug 15, 2026
@cla-assistant

cla-assistant Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make pinned_post_tower_weight_roots_and_shapes_match_published_contract skip with a named reason on a partially materialized checkpoint instead of panicking on an opaque unwrap, without letting any genuine contract violation become a skip.

Correctness boundary audit

Every path in load_pinned_checkpoint, assert_post_tower_contract, and safetensors_shape was traced against the fail/skip split. One ambiguous case, everything else is correctly classified.

  • unwrap_or_default() on weight_map: correct. A non-object or absent weight_map yields an empty map, actual_keys comes out empty, and assert_eq!(actual_keys, PINNED_POST_TOWER_WEIGHT_KEYS) fails. A non-object index (array, scalar) also lands here because Value's string index returns Null rather than panicking, so a wholly malformed index fails rather than skips. That is the safe direction.
  • continue on a pinned key absent from a parsed weight_map: correct, and executably proven by contract_assertion_still_fails_on_a_missing_weight_root.
  • A pinned key present but mapped to a non-string value: the pre-check continues, the weight-root assertion passes (the key exists), and the loop's unwrap_or_else(|| panic!("{key} must name a shard ...")) fires. Fails, does not skip. Correct.
  • config.validate() stays in assert_post_tower_contract as .unwrap(), so a config validate() rejects still panics. Correct.
  • safetensors_shape panics (does not return Err) when a header parses but records no shape or a non-integer dimension for the key. Correct per the "if unsure, it is wrong" rule.
  • The Err skip branch at lines 185-191 is scoped to availability only: open failure, metadata failure, truncation before or inside the header, a declared header length exceeding the file, and a header that is not JSON. No contract signal can reach it.

Findings

MEDIUM: a config.json that parses as JSON but does not deserialize into MuseGlimmerConfig skips rather than fails (muse_glimmer_fusion_pinned_tests.rs:74-79). This is the one place where something genuinely wrong can go silent. Schema drift in the pinned checkpoint's config (a renamed or dropped text_config field, a wrong model placed in the pinned directory) is exactly the kind of divergence this contract test exists to catch, and the brief's tie-breaker says an ambiguous case is "wrong" and must fail. An interrupted download leaves a truncated config.json, which is a JSON syntax error and would still skip correctly under a tighter split. Suggested shape: parse config.json to Value in the pre-check (syntax error skips), carry the Value in PinnedCheckpoint, and do serde_json::from_value::<MuseGlimmerConfig>(..).unwrap_or_else(|err| panic!(..)) inside assert_post_tower_contract next to validate(). pinned_precheck_names_an_unparseable_config would move to asserting "does not parse as JSON", with a new #[should_panic] test for the schema case. Note that the doc comment on load_pinned_checkpoint, the PR body, and the commit body all describe the skip set as "JSON that does not parse", which is narrower than what the code actually skips on, so at minimum the documented boundary and the implemented boundary should be reconciled.

LOW: the mid-loop skip can mask a later contract violation (:185-191). expected is a BTreeMap, so keys are visited in sorted order. If fc1's shard is unreadable, the function returns before checking fc2 and vision_projection, and a wrong recorded shape on those keys goes unreported. Previously the same checkpoint produced a loud failure. Inherent to any skip design (an unreadable shard cannot be asserted on) and bounded by MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1, but asserting the keys that are readable and skipping only at the end would be strictly better.

LOW: the header-length bound is file-relative only (:221). The arithmetic is right: for a valid safetensors file header_len = file_len - 8 - payload_len <= file_len - 8, so the check cannot reject a valid header, saturating_sub cannot underflow (an 8-byte read_exact already succeeded), and the as usize cast is lossless on this 64-bit target. What remains is that a corrupt length field inside a genuinely large shard (the real one is 50 GB) can still request a multi-GB allocation. An absolute sanity cap in addition to the file-size bound would close that.

LOW: contract_assertion_still_fails_on_a_wrong_recorded_shape's expected is not unique to the shape assertion (:454). "model.vision_adapter.fc1.weight" also appears in the weight-root assert_eq! output and in the "must name a shard" panic, so a future refactor could make this test pass for the wrong reason. expected = "failed: model.vision_adapter.fc1.weight" (the custom-message suffix assert_eq! emits) or a substring of the left value pins it to the shape assertion. contract_assertion_still_fails_on_a_missing_weight_root is fine as written: the only other reachable panic names fc1, not vision_projection.

LOW: the empty-weight_map case is not proven to fail end to end. pinned_precheck_leaves_an_absent_weight_map_to_the_contract_assertion proves the pre-check returns Ok with an empty map, but no test runs assert_post_tower_contract over it. The sibling missing-root case does have that #[should_panic] companion. A four-line addition closes the gap.

LOW: body inaccuracies that become the squash commit body. The PR body says "eleven new tests"; there are 13 new (14 in the file, 19 in the module overall). Both the PR body and the commit body justify the file split by a "500-line limit" that is not this repo's convention: the repo's own mlxcel-code-structure skill doc puts the threshold at 800 lines and 394 files under src/ already exceed 500. The split itself is sound on its own merits (disk-reading contract checks separated from fusion math, using the established #[cfg(test)] #[path] sibling-module pattern that src/vision/mod.rs already uses); only the stated rationale is wrong.

INFO: only one of the two pinned guards is hardened. pinned_weight_index_classifies_each_source_weight_once in src/loading/vlm_muse_glimmer_tests.rs does not honor MLXCEL_REQUIRE_PINNED_CHECKPOINTS, so on the checkpoint-owning machine one pinned guard can still skip silently. Out of scope for this issue by explicit instruction; worth a follow-up.

Env lock

No deadlock is possible. env_lock() is a non-reentrant std::sync::Mutex behind a OnceLock that recovers from poisoning, skip_or_fail_pinned_checkpoint acquires it in a nested block that contains only the std::env::var read, and the guard is dropped before the assert!, so a failing assertion cannot even poison it. The function is called from exactly two sites, neither of which already holds the lock, so there is no nesting. The backend seam tests from #1169 and muse_glimmer_startup_guard_tests share the same static in the same lib test binary and can only serialize briefly against this read. Worth noting that test_support::env_lock's module doc still says it is used by tests that call set_var/remove_var; this is the first read-only user.

Scope

Proportionate, with room to trim. Of the 499 lines, roughly half is the pinned test and helper that merely moved, and the synthetic coverage is what the issue explicitly asked for. The doc comments are longer than the surrounding code's norm and could lose about 30 lines without losing meaning, but they document the correctness boundary, which is the substance of the issue. Not worth churn.

Verification

  • All stated requirements implemented (criteria 1, 2, 3, and the optional 4)
  • No placeholder or mock code remaining
  • Integrated into project code flow (second #[cfg(test)] #[path] module, all 14 tests run, none orphaned, no production path touched)
  • Project conventions followed (license header, sibling test-module pattern, tempfile already a dev-dependency, no new dependency)
  • Existing modules reused where applicable (crate::test_support::env_lock, MuseGlimmerConfig)
  • No unintended structural changes (removal from the original file is exactly the pinned test, its helper, and the now-unused imports)
  • Tests pass (19 passed, and 19 passed again under MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 against the real checkpoint)
  • No AI attribution and no em dashes in the diff, commit body, or PR body; Closes #1161 present

No changes were made by this review; all findings are reported for the author to accept or decline.

The availability pre-check deserialized config.json straight into MuseGlimmerConfig, so a config that is valid JSON but does not fit the schema was reported as an availability problem and skipped. Schema drift in the pinned config, or a different model dropped into the pinned directory, is exactly the divergence this contract test exists to catch, so it has to fail.

The pre-check now parses config.json as plain JSON only, which still skips the truncated config an interrupted download leaves behind, and PinnedCheckpoint carries the raw Value. Deserializing into MuseGlimmerConfig moved next to validate() in the assertion body, where a mismatch panics.

Also tightens two tests so they cannot pass for the wrong reason: the wrong-shape case now expects the assert_eq! custom-message prefix rather than a bare key name that three different panics emit, and the absent weight_map case gains the should_panic companion its missing-weight-root sibling already had. Adds both halves of the schema-mismatch boundary, the pre-check passing it through and the assertion failing on it.
safetensors_shape bounded the declared header length against the file size alone before allocating. That is loose enough to matter on the pinned checkpoint: its shards are 50 GB and 9.6 GB, so a corrupt eight-byte prefix can declare a header of several gigabytes and still sit under the file length, at which point vec![0u8; header_len] plus read_exact either aborts the test process on allocation failure or pulls gigabytes of tensor payload into memory. An abort is a worse outcome than the opaque unwrap this PR set out to remove, since it carries no reason at all.

Adds an absolute 256 MiB ceiling checked before the file-relative bound, matching the guard read_safetensors_header_bytes in mlxcel-core already applies to the same prefix. The real pinned shard records an 11,720-byte header, so the margin is about four orders of magnitude and no genuine checkpoint can be rejected by it. Covered by safetensors_shape_refuses_a_header_over_the_allocation_ceiling, which declares u64::MAX in a tiny temp file so the test allocates nothing large either.

Verified with cargo test --lib vision::encoders::muse_glimmer_fusion (23 passed), the same run under MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 against the real checkpoint (23 passed, so the ceiling does not turn the contract check into a skip), cargo clippy --lib --tests -- -D warnings, and cargo fmt --check.

Refs #1161
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Reviewed at 3336732c, fix pushed as 3c61dd21. Test-only change, no production path touched, so the review focused on the binary parsing, the resource handling, the env-lock interaction, and the availability-versus-violation boundary.

Fixed: unbounded header allocation against a multi-gigabyte shard (MEDIUM)

safetensors_shape bounded the declared header length against the file size only. That bound is file-relative, and the pinned shards are 50 GB and 9.6 GB, so a corrupt eight-byte prefix could declare a header of several gigabytes, pass the check, and reach vec![0u8; header_len as usize] followed by read_exact. The outcome is either an allocation-failure abort or gigabytes of tensor payload read into memory, on the one machine that owns the checkpoint. An abort carries no reason at all, which is a worse failure mode than the opaque unwrap this PR set out to replace.

3c61dd21 adds a 256 MiB ceiling checked before the file-relative bound, the same value and rationale as the guard read_safetensors_header_bytes in mlxcel-core already applies to this identical eight-byte prefix. The real pinned shard records an 11,720-byte header, so the margin is roughly four orders of magnitude and no genuine checkpoint can be rejected. Covered by safetensors_shape_refuses_a_header_over_the_allocation_ceiling, which declares u64::MAX in a tiny temp file so the test allocates nothing large either.

Verified clean

  • Correctness boundary. Every Err path in load_pinned_checkpoint and safetensors_shape is an availability or readability problem. Everything wrong-but-present reaches an assertion: an absent or non-object weight_map becomes an empty map that fails the weight-root assertion, a pinned key missing from a well-formed map is skipped by the shard loop and reported by that same assertion, a key mapped to a non-string value hits the "must name a shard" panic, and a header that parses without a shaped entry for the key panics rather than returning Err. No path was found where something wrong skips.
  • The 3336732c follow-up is correct and complete. PinnedCheckpoint.config is a raw Value, the pre-check verifies JSON syntax only, and from_value::<MuseGlimmerConfig> plus validate() both sit in assert_post_tower_contract where they panic. text_config and its inner fields have no serde defaults, so a config that is valid JSON but is not this model genuinely fails deserialization rather than passing by default.
  • Env lock. env_lock() recovers from poisoning via unwrap_or_else(|p| p.into_inner()), the guard is scoped and dropped before the assert!, and nothing reachable from skip_or_fail_pinned_checkpoint re-acquires it. No deadlock against the four src/backend/tests.rs holders or against muse_glimmer_startup_guard_tests, and no poisoning hazard in either direction.
  • Resources. The shard File is dropped at function scope on every path including the early Err returns, only the header is ever read, and every TempDir is bound to a live local, so the should_panic tests still clean up on unwind.

Observation, not blocking

contract_assertion_still_fails_on_an_absent_weight_map and contract_assertion_still_fails_on_a_missing_weight_root expect a bare key name that also appears in the loop's "must name a shard in the pinned weight index" panic, so they do not pin the weight-root assertion the way the wrong-shape test pins the shape assertion with its failed: prefix. Both alternatives are failures rather than skips, so the invariant the tests exist to protect still holds either way. Left as is to avoid depending on more of assert_eq!'s output formatting.

Verification

cargo test --lib vision::encoders::muse_glimmer_fusion 23 passed, the same run under MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 against the real checkpoint 23 passed (so the new ceiling does not turn the contract check into a skip), cargo clippy --lib --tests -- -D warnings clean, cargo fmt --check clean. Nothing under models/ was written, moved, or truncated; both shards verified present and unmodified afterwards.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Aug 15, 2026
Bilingual report covering the pinned Muse Glimmer skip guard: the availability versus contract boundary and how it is enforced structurally, the two defects found in review (a schema-mismatched config that skipped instead of failing, and a header allocation bounded only by file size), and how each acceptance criterion was proven using the new env gate against the real checkpoint.
@inureyes
inureyes merged commit 0adb53c into main Aug 15, 2026
7 checks passed
@inureyes
inureyes deleted the fix/issue-1161-pinned-checkpoint-skip-guard branch August 15, 2026 17:38
inureyes added a commit that referenced this pull request Aug 16, 2026
The paragraph said a partially materialized checkpoint made the availability pre-check panic. There was no availability pre-check before #1173; that PR created it, and the panic came from unwrapping the reads directly. Restates what actually changed: unwraps became a pre-check that skips with a named reason while contract violations stay failures.
inureyes added a commit that referenced this pull request Aug 16, 2026
The paragraph claimed there was no availability pre-check before PR #1173. There was one, just a narrower one: PR #1157 (`92d6d4c8`) replaced the vision-side test's `assert!(index_path.exists(), ...)` with a silent skip and added the same index-absent skip to `pinned_weight_index_classifies_each_source_weight_once`. Issue #1161 records this as well, both in its third acceptance criterion and in its note that #1157 "added the index-absent guard".

As written the paragraph implied every partially materialized state was loud before #1173, which overstates what that PR gave up and therefore what the gate buys back. An absent index already skipped quietly under #1157. Restates the sequence accurately: #1157 made the index-absent case quiet, #1173 made the index-present-but-incomplete case quiet by replacing the unwraps past that guard, and `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1` restores the loudness for both.

Documentation only; no code, test, or gate behavior changes.
inureyes added a commit that referenced this pull request Aug 16, 2026
Bilingual report covering the shared pinned-checkpoint gate: why the gate had to move into test_support rather than be copied, why the loading-side panic on a classification error stays a panic, and why documenting when to enable the variable was half the deliverable given it was set nowhere in the tree. Records the two-step correction the pre-#1173 paragraph needed, since the #1157 and #1173 sequence is easy to state wrongly.
inureyes added a commit that referenced this pull request Aug 16, 2026
…REQUIRE_PINNED_CHECKPOINTS (#1180)

## Summary

Extends the pinned-checkpoint gate PR #1173 introduced to the loading-side sibling test, shares the gate logic between both call sites instead of duplicating it, and documents the variable including when and how to actually turn it on, per the scope the issue's comment added.

## What changed

`src/test_support/pinned_checkpoint.rs` (new) holds a single `skip_or_fail_pinned_checkpoint(test_name, reason)` helper, declared from `src/test_support/mod.rs` alongside the existing `env_lock` module; it reads `MLXCEL_REQUIRE_PINNED_CHECKPOINTS` under `crate::test_support::env_lock::env_lock()`, drops the guard before asserting, and treats only the exact value `1` as enabling.
`src/vision/encoders/muse_glimmer_fusion_pinned_tests.rs` drops its private copy of the gate and calls the shared helper at both of its call sites, passing its own test name so the skip message is byte-identical to before and the failure message still names that test.
`src/loading/vlm_muse_glimmer_tests.rs` routes `pinned_weight_index_classifies_each_source_weight_once`'s previously unconditional skip through the same shared helper, so it now fails rather than skips when the gate is on and the pinned index is absent; the existing `panic!` on `read_muse_weight_inventory_from_index` returning `Err` is untouched, since that is a genuine contract violation rather than an availability problem.
`docs/environment-variables.md` adds a row for `MLXCEL_REQUIRE_PINNED_CHECKPOINTS` to the existing "Test and CI variables" table, whose `Variable | Purpose` shape carries the value and default semantics inline, stating that only the exact string `1` enables it, plus prose covering that it is test-only, that it belongs on a machine that owns the pinned checkpoint, a single-run invocation example and a persistent-export suggestion, and its role in turning an ambiguous `ok` into positive evidence that the checkpoint was actually read (how acceptance criterion 2 of #1161 was proven).

## Test plan

- [x] `cargo check --lib --tests`
- [x] `cargo clippy --lib --tests -- -D warnings`
- [x] `cargo test --lib vision::encoders::muse_glimmer_fusion` (23 passed, real pinned checkpoint present)
- [x] `cargo test --lib loading::vlm::muse_glimmer::` (14 passed, real pinned checkpoint present)
- [x] Compiled test binary run from a temp directory with no `models/`, variable unset: both pinned guards skip, each still naming itself
- [x] Compiled test binary run from a temp directory with no `models/`, `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`: both pinned guards fail, each still naming itself, exit 101

Closes #1177
inureyes added a commit that referenced this pull request Aug 16, 2026
#1181)

## Summary

The file-size and module-split thresholds existed only in the agent-facing `.claude/skills/mlxcel-code-structure/SKILL.md`, with no contributor-facing document referencing them, which is how PR #1173's commit body ended up citing a nonexistent "500-line limit." This PR adds a "File Size and Module Structure" section to `docs/code-guidelines.md` as the single authoritative home for those numbers, and widens the places that describe that document so the guidance is reachable by the normal contributor path.

## Option chosen

Option 1 from the issue: the thresholds live in `docs/code-guidelines.md`, and the section states as a rule that anything else citing them, agent-facing tooling under `.claude/skills/` included, should link there rather than restate them. This is preferable because the thresholds are project convention that any human contributor needs, not agent-specific configuration; a document only agents read is the wrong home for a rule contributors are expected to follow. The tradeoff is that the skill file's structural rules are now split across two documents for a reader working through it top to bottom, but the pointer names exactly what moved and where, so that cost is small next to having one number that cannot drift.

The rule is written prescriptively rather than as a claim about what any particular consumer currently contains, because no such claim is verifiable from this repository.

## Correction to the brief

The brief this implementation started from asserted that `.claude/skills/` is tracked in this repository and instructed treating the skill-file edit as a real committed change. That is incorrect: `.gitignore` line 28 is `/.claude/`, committed at `HEAD`, and `git ls-files .claude/` returns zero files, so the entire `.claude/` directory is untracked here and ships no content with the repository. What was missing was therefore not de-duplication within this repository but a discoverable, contributor-facing home for the numbers, which this PR adds.

## What changed

- `docs/code-guidelines.md`: new "File Size and Module Structure" section before "Shared Function Comments", carrying the size table (under 800 fine as a single file, 800 to 1,200 acceptable with a helpers file, 1,200+ extract `<name>_helpers.rs`, 1,500+ consider a directory module, 2,000+ with no helpers file as the anti-pattern), the reason-based exception for `nemotron_h.rs`, `llama4.rs` as an illustration of the 1,200+ row, an explicit note that several files sit well past the thresholds and should be read as debt rather than as precedent, the inline-test-versus-sibling-`_tests.rs` threshold (roughly 100 lines to move, 200 at the latest) with the wiring both forms of which this repository already uses, and the `<name>_helpers.rs` / `<name>_tests.rs` naming convention.
- `CONTRIBUTING.md`: widened the intro paragraph and the "Quick links" row describing `docs/code-guidelines.md`, which called it narrowly the shared-function rules, and added a "Code standards" bullet linking straight to the new section.
- `docs/README.md`: widened entry 19, which described `code-guidelines.md` as covering only the `// Used by:` convention and the JIT kernel rule, so the docs index names the thresholds too.

Every line count quoted in the new section was measured against this branch rather than carried over, because the source this section was assembled from had gone stale: it recorded `nemotron_h.rs` at 2,342 lines (actually 2,914) and `llama4.rs` at 1,499 (actually 1,862), and its "complete model in one file" example, `qwen2.rs`, is a 31-line re-export shim over `llama3`, so `dbrx.rs` (606 lines, a full model through `impl LanguageModel`) replaced it. The section also tells readers the figures are approximate and to check the file rather than trust a number quoted anywhere, that section included.

What was deliberately left in the skill file rather than carried into `docs/`: the module-versus-directory trigger, trait-placement rules, the model-registration checklist, subsystem dependency-direction rules, error-handling and config-deserialization patterns, and the rest of the anti-patterns table. That material is about how to structure new code while implementing a model, not something a contributor looks up as a size or split threshold.

Out of scope, per the issue: the `0adb53c5` commit body on `main` is not rewritten, the PR #1173 technical report already records the discrepancy correctly, and the thresholds themselves are unchanged, only relocated and surfaced.

## Test plan

- [x] Documentation-only change; no code or test files touched, so there is nothing for `cargo test` to exercise.
- [x] Every file path and line count cited in the new section verified against this branch with `wc -l`, including that `nemotron_h.rs` has no sibling `_helpers.rs` and `llama4.rs` does.
- [x] Confirmed `gemma3n_helpers.rs`, `llama4_helpers.rs` and `qwen3_next_helpers.rs` are the only `*_helpers.rs` files under `src/models/`.
- [x] Confirmed `dbrx.rs` is a complete model (`Attention`, `SparseMoeBlock`, `DecoderLayer`, `DbrxModel`, `impl LanguageModel`) rather than a re-export shim.
- [x] Confirmed the outlier claim: `gemma4.rs` 6,680 lines and `qwen3_5.rs` 3,451 lines both with no helpers file, `gemma3n.rs` 5,594 lines, and nine files under `src/models/` over 2,000 lines.
- [x] Confirmed the `CONTRIBUTING.md` anchor `#file-size-and-module-structure` matches the `## File Size and Module Structure` heading, with no duplicate heading that would shift the slug.
- [x] Confirmed the described sibling-test wiring matches this repository: both `#[cfg(test)] mod <name>_tests;` and the `#[path = "..."]` form are in use.

Closes #1178
@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
…lablup#1173)

## Summary

`pinned_post_tower_weight_roots_and_shapes_match_published_contract` skipped gracefully only when `model.safetensors.index.json` was absent. With the index present but anything else it reads missing or corrupt, the shape an interrupted `hf download` or `mlxcel download` leaves behind, it unwrapped its way to an opaque panic instead of skipping with a reason. This adds an availability pre-check that names the offending file, while leaving every contract assertion able to fail exactly as before.

## Implementation choice

The issue offered two options; this is the hybrid the brief recommended. Option 1 alone (a pure existence pre-check) cannot detect a shard that exists but whose header was truncated mid-download, and option 2 alone (converting each unwrap into a skip) reads the index twice, which the issue explicitly asked to avoid. The hybrid gets both: `load_pinned_checkpoint` parses the index once and hands the parsed `weight_map` to the assertion body, and `safetensors_shape` returns a `Result` so header corruption is covered too.

## How the correctness boundary is kept

The skip is deliberately narrow, and the split is enforced by construction rather than by convention.

- Only **availability and readability** may skip: an absent file, an unreadable file, JSON that does not parse, a truncated or unparseable safetensors header. `load_pinned_checkpoint` returns `Err` for exactly these, and `read_checkpoint_file` distinguishes "not present" from "could not be read" so the message names the path either way.
- **Contract violations still fail.** The `assert_eq!` calls are untouched and are not wrapped in any skip path. `load_pinned_checkpoint` is structured so it cannot swallow one: a `weight_map` that is absent or non-object yields an empty map (which drives the weight-root assertion to fail, not to skip), and a pinned key absent from an otherwise well-formed `weight_map` is skipped over by the shard loop with a comment saying why, so the weight-root assertion is what reports it.
- Inside `safetensors_shape`, a header that parses but does not describe the key as a shaped tensor panics rather than returning `Err`, following the issue's "if unsure whether it is missing or wrong, it is wrong" rule.
- The contract assertions moved into `assert_post_tower_contract`, which takes an already-validated `PinnedCheckpoint` and contains no skip path at all. That split is what makes the two `should_panic` tests below possible.

## What changed

- `src/vision/encoders/muse_glimmer_fusion_pinned_tests.rs` (new): the pinned-checkpoint contract check, the `load_pinned_checkpoint` availability pre-check, a `Result`-returning `safetensors_shape`, and synthetic partial-checkpoint coverage. `safetensors_shape` also bounds the declared header length against the file size before allocating, so a corrupt length cannot turn into a multi-gigabyte allocation.
- `src/vision/encoders/muse_glimmer_fusion_tests.rs`: the pinned block and its now-unused imports removed, leaving 196 lines of fusion-math tests.
- `src/vision/encoders/muse_glimmer_fusion.rs`: attaches `pinned_tests` as a second `#[cfg(test)]` module, the same pattern `src/vision/mod.rs` already uses. The split keeps both files under the 500-line limit; folding the synthetic coverage into the original file would have pushed it well past that.

Test-only change. No production loading path is touched, and `src/loading/vlm_muse_glimmer_tests.rs` is untouched as the issue required.

## Synthetic-checkpoint tests

The real pinned checkpoint is either complete or absent, so the partial cases cannot be exercised against it, and nothing under `models/` may be moved or truncated to fake one. All eleven new tests build throwaway checkpoints in `tempfile::tempdir()` (already a dev-dependency, no new dependency added).

Pre-check names the specific missing or unreadable file: `pinned_precheck_names_an_absent_index`, `pinned_precheck_names_a_missing_config`, `pinned_precheck_names_a_missing_shard` (index present naming a shard that does not exist), `pinned_precheck_names_an_unparseable_index`, `pinned_precheck_names_an_unparseable_config`, and `pinned_precheck_accepts_a_complete_synthetic_checkpoint` as the negative control.

Pre-check refuses to swallow contract violations: `pinned_precheck_leaves_a_missing_weight_root_to_the_contract_assertion` and `pinned_precheck_leaves_an_absent_weight_map_to_the_contract_assertion` both assert the pre-check returns `Ok`, so the violation reaches the assertion.

Contract violations still fail, proven executably rather than by reading the diff: `contract_assertion_still_fails_on_a_missing_weight_root` and `contract_assertion_still_fails_on_a_wrong_recorded_shape` are `#[should_panic]` tests over complete-but-wrong synthetic checkpoints. The second fails with `assertion left == right failed: model.vision_adapter.fc1.weight / left: [1, 1] / right: [4096, 6144]`, which is the shape assertion firing, not a skip.

Header handling: `safetensors_shape_reads_a_well_formed_header`, `safetensors_shape_reports_a_truncated_header`, `safetensors_shape_reports_an_unparseable_header`.

## Optional env var

`MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1` is implemented. It is read inside `skip_or_fail_pinned_checkpoint` under `crate::test_support::env_lock::env_lock()`, held for the duration of the read, because this crate is edition 2024 and `src/server/muse_glimmer_startup_guard_tests.rs` mutates the process environment with `unsafe set_var` under that same lock; an unlocked read is the same class of race being fixed elsewhere in this chain. Only the exact value `1` enables it.

It also turned out to be the cleanest way to prove acceptance criterion 2 on this machine: with skips disabled, the pinned test passing is positive evidence that it read the real checkpoint rather than silently skipping.

## Test plan

- [x] `cargo test --lib vision::encoders::muse_glimmer_fusion` on a machine holding the real pinned checkpoint: `19 passed; 0 failed`.
- [x] `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 cargo test --lib vision::encoders::muse_glimmer_fusion`: `19 passed; 0 failed`. Since any skip is a hard failure under this variable, this confirms the full pinned checkpoint still validates the weight-root and shape contract for real (criterion 2).
- [x] Test binary run from a directory containing no `models/`: skips with `Skipping pinned_post_tower_weight_roots_and_shapes_match_published_contract: models/mlx/muse-glimmer-30b/model.safetensors.index.json is not present` (criterion 3, behavior unchanged).
- [x] Same run with `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`: fails with `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 but the pinned Muse Glimmer checkpoint is not usable: ... is not present` (criterion 4).
- [x] `cargo clippy --lib --tests -- -D warnings`: clean.
- [x] `cargo check --lib --tests`: clean.
- [x] `cargo fmt --check` on all three changed files: clean.
- [x] Nothing under `models/` or `/home/inureyes/models` was moved, renamed, deleted, truncated, or written to; both 50 GB and 9.6 GB shards verified present afterwards.

Closes lablup#1161
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…REQUIRE_PINNED_CHECKPOINTS (lablup#1180)

## Summary

Extends the pinned-checkpoint gate PR lablup#1173 introduced to the loading-side sibling test, shares the gate logic between both call sites instead of duplicating it, and documents the variable including when and how to actually turn it on, per the scope the issue's comment added.

## What changed

`src/test_support/pinned_checkpoint.rs` (new) holds a single `skip_or_fail_pinned_checkpoint(test_name, reason)` helper, declared from `src/test_support/mod.rs` alongside the existing `env_lock` module; it reads `MLXCEL_REQUIRE_PINNED_CHECKPOINTS` under `crate::test_support::env_lock::env_lock()`, drops the guard before asserting, and treats only the exact value `1` as enabling.
`src/vision/encoders/muse_glimmer_fusion_pinned_tests.rs` drops its private copy of the gate and calls the shared helper at both of its call sites, passing its own test name so the skip message is byte-identical to before and the failure message still names that test.
`src/loading/vlm_muse_glimmer_tests.rs` routes `pinned_weight_index_classifies_each_source_weight_once`'s previously unconditional skip through the same shared helper, so it now fails rather than skips when the gate is on and the pinned index is absent; the existing `panic!` on `read_muse_weight_inventory_from_index` returning `Err` is untouched, since that is a genuine contract violation rather than an availability problem.
`docs/environment-variables.md` adds a row for `MLXCEL_REQUIRE_PINNED_CHECKPOINTS` to the existing "Test and CI variables" table, whose `Variable | Purpose` shape carries the value and default semantics inline, stating that only the exact string `1` enables it, plus prose covering that it is test-only, that it belongs on a machine that owns the pinned checkpoint, a single-run invocation example and a persistent-export suggestion, and its role in turning an ambiguous `ok` into positive evidence that the checkpoint was actually read (how acceptance criterion 2 of lablup#1161 was proven).

## Test plan

- [x] `cargo check --lib --tests`
- [x] `cargo clippy --lib --tests -- -D warnings`
- [x] `cargo test --lib vision::encoders::muse_glimmer_fusion` (23 passed, real pinned checkpoint present)
- [x] `cargo test --lib loading::vlm::muse_glimmer::` (14 passed, real pinned checkpoint present)
- [x] Compiled test binary run from a temp directory with no `models/`, variable unset: both pinned guards skip, each still naming itself
- [x] Compiled test binary run from a temp directory with no `models/`, `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`: both pinned guards fail, each still naming itself, exit 101

Closes lablup#1177
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
lablup#1181)

## Summary

The file-size and module-split thresholds existed only in the agent-facing `.claude/skills/mlxcel-code-structure/SKILL.md`, with no contributor-facing document referencing them, which is how PR lablup#1173's commit body ended up citing a nonexistent "500-line limit." This PR adds a "File Size and Module Structure" section to `docs/code-guidelines.md` as the single authoritative home for those numbers, and widens the places that describe that document so the guidance is reachable by the normal contributor path.

## Option chosen

Option 1 from the issue: the thresholds live in `docs/code-guidelines.md`, and the section states as a rule that anything else citing them, agent-facing tooling under `.claude/skills/` included, should link there rather than restate them. This is preferable because the thresholds are project convention that any human contributor needs, not agent-specific configuration; a document only agents read is the wrong home for a rule contributors are expected to follow. The tradeoff is that the skill file's structural rules are now split across two documents for a reader working through it top to bottom, but the pointer names exactly what moved and where, so that cost is small next to having one number that cannot drift.

The rule is written prescriptively rather than as a claim about what any particular consumer currently contains, because no such claim is verifiable from this repository.

## Correction to the brief

The brief this implementation started from asserted that `.claude/skills/` is tracked in this repository and instructed treating the skill-file edit as a real committed change. That is incorrect: `.gitignore` line 28 is `/.claude/`, committed at `HEAD`, and `git ls-files .claude/` returns zero files, so the entire `.claude/` directory is untracked here and ships no content with the repository. What was missing was therefore not de-duplication within this repository but a discoverable, contributor-facing home for the numbers, which this PR adds.

## What changed

- `docs/code-guidelines.md`: new "File Size and Module Structure" section before "Shared Function Comments", carrying the size table (under 800 fine as a single file, 800 to 1,200 acceptable with a helpers file, 1,200+ extract `<name>_helpers.rs`, 1,500+ consider a directory module, 2,000+ with no helpers file as the anti-pattern), the reason-based exception for `nemotron_h.rs`, `llama4.rs` as an illustration of the 1,200+ row, an explicit note that several files sit well past the thresholds and should be read as debt rather than as precedent, the inline-test-versus-sibling-`_tests.rs` threshold (roughly 100 lines to move, 200 at the latest) with the wiring both forms of which this repository already uses, and the `<name>_helpers.rs` / `<name>_tests.rs` naming convention.
- `CONTRIBUTING.md`: widened the intro paragraph and the "Quick links" row describing `docs/code-guidelines.md`, which called it narrowly the shared-function rules, and added a "Code standards" bullet linking straight to the new section.
- `docs/README.md`: widened entry 19, which described `code-guidelines.md` as covering only the `// Used by:` convention and the JIT kernel rule, so the docs index names the thresholds too.

Every line count quoted in the new section was measured against this branch rather than carried over, because the source this section was assembled from had gone stale: it recorded `nemotron_h.rs` at 2,342 lines (actually 2,914) and `llama4.rs` at 1,499 (actually 1,862), and its "complete model in one file" example, `qwen2.rs`, is a 31-line re-export shim over `llama3`, so `dbrx.rs` (606 lines, a full model through `impl LanguageModel`) replaced it. The section also tells readers the figures are approximate and to check the file rather than trust a number quoted anywhere, that section included.

What was deliberately left in the skill file rather than carried into `docs/`: the module-versus-directory trigger, trait-placement rules, the model-registration checklist, subsystem dependency-direction rules, error-handling and config-deserialization patterns, and the rest of the anti-patterns table. That material is about how to structure new code while implementing a model, not something a contributor looks up as a size or split threshold.

Out of scope, per the issue: the `0adb53c5` commit body on `main` is not rewritten, the PR lablup#1173 technical report already records the discrepancy correctly, and the thresholds themselves are unchanged, only relocated and surfaced.

## Test plan

- [x] Documentation-only change; no code or test files touched, so there is nothing for `cargo test` to exercise.
- [x] Every file path and line count cited in the new section verified against this branch with `wc -l`, including that `nemotron_h.rs` has no sibling `_helpers.rs` and `llama4.rs` does.
- [x] Confirmed `gemma3n_helpers.rs`, `llama4_helpers.rs` and `qwen3_next_helpers.rs` are the only `*_helpers.rs` files under `src/models/`.
- [x] Confirmed `dbrx.rs` is a complete model (`Attention`, `SparseMoeBlock`, `DecoderLayer`, `DbrxModel`, `impl LanguageModel`) rather than a re-export shim.
- [x] Confirmed the outlier claim: `gemma4.rs` 6,680 lines and `qwen3_5.rs` 3,451 lines both with no helpers file, `gemma3n.rs` 5,594 lines, and nine files under `src/models/` over 2,000 lines.
- [x] Confirmed the `CONTRIBUTING.md` anchor `#file-size-and-module-structure` matches the `## File Size and Module Structure` heading, with no duplicate heading that would shift the slug.
- [x] Confirmed the described sibling-test wiring matches this repository: both `#[cfg(test)] mod <name>_tests;` and the `#[path = "..."]` form are in use.

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

Labels

area:models Model architectures, weights, loading, metadata priority:low Low priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test: muse_glimmer fusion skip guard panics on a partially materialized checkpoint

1 participant