Skip to content

guard mlx_array_dim against 0-dim and out-of-bounds access#113

Open
TheTom wants to merge 1 commit intoml-explore:mainfrom
TheTom:pr/fix-array-dim-crash
Open

guard mlx_array_dim against 0-dim and out-of-bounds access#113
TheTom wants to merge 1 commit intoml-explore:mainfrom
TheTom:pr/fix-array-dim-crash

Conversation

@TheTom
Copy link
Copy Markdown

@TheTom TheTom commented Apr 22, 2026

Proposed changes

mlx_array_dim crashes with SmallVector out of range when called on
scalar (0-dim) arrays or with dim >= ndim. The exception is caught by
mlx_error which calls Swift's fatalError, killing the process.

This happens during Swift metadata initialization when Module subclass
hierarchies trigger lazy evaluation of 0-dimensional arrays. The crash
is non-deterministic and depends on binary layout, making it difficult
to reproduce but fatal when it hits.

Fix: guard against invalid dimensions before accessing shape().
Returns 1 for scalars, 0 for out-of-bounds. No change for valid inputs.

Repro

Any Swift binary linking MLXLMCommon (from mlx-swift-lm) with certain
class hierarchies can trigger this at load time:

MLX/ErrorHandler.swift:343: Fatal error: SmallVector out of range.
at mlx-c/mlx/c/array.cpp:335

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

mlx_array_dim crashes with SmallVector out of range when called on
scalar (0-dim) arrays or with dim >= ndim. This kills the process
via mlx_error/fatalError during Swift metadata initialization.

Returns 1 for scalars, 0 for out-of-bounds. No change for valid inputs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant