Repository navigation
refactor: decompose array/mod.rs into focused submodules - #16
Conversation
Split the monolithic mod.rs into 8 focused submodules while preserving the existing public API. Each submodule contains a separate `impl MxArray` block with related methods, improving navigability and maintainability. New submodules: - creation.rs: array constructors (from_*, zeros, ones, full, linspace, eye, arange) - ops.rs: arithmetic, math, trig, NaN/Inf checks - reduction.rs: sum, mean, max, min, argmax, var, std, logsumexp, cumsum, cumprod - shape.rs: reshape, transpose, slice, concatenate, split, squeeze, pad, sort, stack - comparison.rs: equal, not_equal, less, greater, logical_and/or/not, where_ - data.rs: eval, shape, dtype, size, to_float32/int32/uint32, item_at_*, copy, astype - random.rs: random_uniform, random_normal, random_bernoulli, randint, categorical - memory.rs: free functions for cache/memory management - tests.rs: all #[cfg(test)] content (~1,565 lines) mod.rs reduced from 3,150 to 105 lines (struct def, DType, module decls, re-exports). All 715 Rust tests and 457 TypeScript tests pass unchanged. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds many new N‑API MxArray methods (creation, ops, reductions, shape, random, memory, data, comparisons), extensive tests, expanded TypeScript declarations, and updates the FFI/C++ API to support multi‑axis logsumexp (and removes split_at_indices). Changes
sequenceDiagram
actor JS as JavaScript (Node.js)
participant NAPI as N‑API Binding
participant Rust as Rust MxArray Wrapper
participant FFI as mlx_sys FFI
participant Cpp as MLX C++ Library
JS->>NAPI: call MxArray.method(...)
NAPI->>Rust: invoke impl MxArray::method(...)
Rust->>FFI: unsafe mlx_array_*call*(handle, ...)
FFI->>Cpp: forward to MLX C++ op
Cpp-->>FFI: return mlx_array* handle
FFI-->>Rust: return handle
Rust->>Rust: MxArray::from_handle(handle)
Rust-->>NAPI: return wrapped MxArray
NAPI-->>JS: JS-visible MxArray result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/array/creation.rs`:
- Around line 8-34: The from_* constructors (from_int32, from_int64,
from_uint32, from_float32 and the internal from_bfloat16/from_float16) currently
call the FFI without checking that data.len() matches the product of shape
elements, risking out-of-bounds in the C++ layer; before calling
sys::mlx_array_*, compute expected_size = shape.iter().map(|&s| s as
usize).product(), compare it to data.len(), and if they differ return an Err
with a clear message (e.g., "data length mismatch: expected X but got Y")
instead of proceeding to the FFI; apply this check in each constructor
(referencing the functions by name) so only validated slices reach
MxArray::from_handle.
In `@crates/mlx-core/src/array/reduction.rs`:
- Around line 132-152: The logsumexp Rust wrapper incorrectly uses -1 to signal
“reduce all axes” for mlx_array_logsumexp (function logsumexp), but the FFI
interprets -1 as “last axis”; update the wrapper to call a new FFI that matches
the axes-array pattern used by sum/mean/max/min (e.g., add and use
mlx_array_logsumexp_axes(handle: i64, axes: *const i32, axes_len: usize,
keepdims: bool)) and pass an empty axes pointer/zero length when axes.is_none()
or axes.unwrap_or_default().is_empty(); alternatively, if you cannot add the FFI
now, explicitly document and assert MLX semantics and return an error instead of
using -1. Ensure references to mlx_array_logsumexp and the wrapper method
logsumexp are updated accordingly.
In `@crates/mlx-core/src/array/shape.rs`:
- Around line 196-227: The split method currently uses a hardcoded max_splits =
100 which can silently truncate results when indices_or_sections is larger;
update split to determine the needed buffer size dynamically: use
indices_or_sections (or call the FFI to query the required count first) to size
the handles Vec (with a reasonable sanity upper bound to avoid unbounded
allocation), then call sys::mlx_array_split_multi with that sized buffer and
convert the returned handles via MxArray::from_handle as before; ensure you
handle the case where the FFI returns a larger count than expected by retrying
with a larger buffer or returning an error.
🧹 Nitpick comments (7)
crates/mlx-core/src/array/random.rs (1)
9-26: Silentf64→f32truncation of distribution bounds.
lowandhighare accepted asf64(from JSnumber) but cast tof32at lines 20-21. If a caller passes values outside f32 range (e.g.,1e40), they silently become±inf. The same applies torandom_normal(lines 35-36) andrandom_bernoulli(line 46).Consider adding a bounds check or at minimum documenting the narrowing behavior so JS callers are aware, similar to how
linspacevalidates itsnumparameter increation.rs.crates/mlx-core/src/array/memory.rs (1)
49-51: Negative or NaNf64inputs silently become0onusizecast.In
set_memory_limit(line 50) andset_cache_limit(line 72),limit as usizewith a negative or NaNf64saturates to0in Rust ≥1.45, which would effectively zero-out the memory/cache budget. Since these are internal-only, this is unlikely to be hit, but a debug assertion or early return could guard against accidental misuse.🛡️ Optional guard example
pub fn set_memory_limit(limit: f64) -> f64 { + debug_assert!(limit >= 0.0 && limit.is_finite(), "memory limit must be non-negative and finite"); unsafe { sys::mlx_set_memory_limit(limit as usize) as f64 } }Also applies to: 71-73
crates/mlx-core/src/array/creation.rs (1)
169-174:arangedoes not validatestep != 0.Passing
step = Some(0.0)would likely cause an infinite loop or undefined behavior in the underlying FFI. Consider a guard:🛡️ Proposed step validation
pub fn arange(start: f64, stop: f64, step: Option<f64>, dtype: Option<DType>) -> Result<Self> { + let step_val = step.unwrap_or(1.0); + if step_val == 0.0 { + return Err(Error::from_reason("arange step must not be zero")); + } let dt = dtype.unwrap_or(DType::Float32); - let handle = unsafe { sys::mlx_array_arange(start, stop, step.unwrap_or(1.0), dt.code()) }; + let handle = unsafe { sys::mlx_array_arange(start, stop, step_val, dt.code()) }; MxArray::from_handle(handle, "array_arange") }crates/mlx-core/src/array/data.rs (1)
29-39:async_eval_arrays: raw pointer lifetime across async boundary.The collected raw pointers (
arr.handle.0) are valid only as long as the caller's&[&MxArray]references are alive. Ifmlx_async_evalenqueues background GPU work that accesses these handles after this function returns, the handles must remain live until that work completes. Since this ispub(crate), callers bear this responsibility, but it may warrant a# Safetydoc comment noting the lifetime requirement.crates/mlx-core/src/array/shape.rs (1)
101-119:slice_assign_axis_inplacemutates throughArc<MxHandle>— document thread-safety implications.This takes
&mut selfbut the underlying handle is inside anArc. If any clones of thisMxArrayexist (viaArc::cloneon the handle), they would observe the mutation, breaking the typical shared-ownership contract. Since this ispub(crate), consider adding a safety comment noting that callers must ensure exclusive logical ownership. As per coding guidelines,Arc<MxHandle>is used for thread-safe lifetime management, so mutation through it needs special care.packages/core/index.d.cts (1)
473-473:splitparameter nameindicesOrSectionsis misleading — only accepts sections, not indices.The parameter is typed as
numberand only accepts a section count, but the nameindicesOrSectionsimplies it could also accept an array of split indices (like NumPy'snp.split). The Rust implementation has bothsplit(indices_or_sections: i32)for sections and a separatesplit_at_indices(&[i32])for indices, but only the former is exposed in the TypeScript bindings. Rename the Rust parameter tosectionsornum_sectionsfor clarity.crates/mlx-core/src/array/ops.rs (1)
117-118: Thef64 → f32cast foralphaandbetais intentional and necessary.The FFI binding
mlx_array_addmmexplicitly expectsf32parameters, so the cast on lines 117–118 is required. Unlikeclip()which receivesf64from the C FFI,addmmmust convert. Since napi-rs maps all JS numbers tof64in Rust, the NAPI signature cannot be changed tof32. Adding a doc comment clarifying thef32conversion would improve clarity for maintainers.
…l-axes, fix split buffer sizing - creation.rs: Add data length vs shape product validation in all from_* methods to prevent OOB GPU reads - reduction.rs: Fix logsumexp None case (was passing -1 meaning "last axis", now correctly reduces all axes via updated FFI) - mlx.cpp: Update logsumexp C++ bridge to axes pointer+length pattern (matching sum/mean/max), fix var/std all-axes dispatch - shape.rs: Replace hardcoded max_splits=100 with dynamic allocation based on requested split count Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
crates/mlx-sys/src/mlx.cpp (1)
1897-1907:⚠️ Potential issue | 🟠 MajorApply the same FFI exception barrier to
mlx_array_var/mlx_array_std.Both updated entry points still lack try/catch, so exceptions can leak across FFI.
🛡️ Suggested fix (pattern for both functions)
mlx_array* mlx_array_var(mlx_array* handle, const int32_t* axes, size_t axes_len, bool keepdims, int32_t ddof) { - auto arr = reinterpret_cast<array*>(handle); - array result = (axes_len == 0) - ? mlx::core::var(*arr, keepdims, ddof) - : mlx::core::var(*arr, make_axes(axes, axes_len), keepdims, ddof); - return reinterpret_cast<mlx_array*>(new array(std::move(result))); + try { + auto arr = reinterpret_cast<array*>(handle); + array result = (axes_len == 0) + ? mlx::core::var(*arr, keepdims, ddof) + : mlx::core::var(*arr, make_axes(axes, axes_len), keepdims, ddof); + return reinterpret_cast<mlx_array*>(new array(std::move(result))); + } catch (const std::exception& e) { + std::cerr << "[MLX] Exception in var: " << e.what() << std::endl; + return nullptr; + } catch (...) { + std::cerr << "[MLX] Unknown exception in var" << std::endl; + return nullptr; + } }(Repeat for
mlx_array_stdwith the same pattern.)Based on learnings: In crates/mlx-sys/src/mlx.cpp, all extern "C" FFI entry points must be wrapped in try/catch to prevent exceptions from crossing the Rust FFI boundary. On failure: log to stderr with an “[MLX]” prefix, return nullptr for pointer-returning functions, and set out-parameters to safe sentinel values (e.g., null handles and unchanged cache index).
Also applies to: 1909-1918
🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/array/reduction.rs`:
- Around line 9-20: The sum method currently passes axes directly to the FFI
which can trigger MLX exceptions for out-of-range or duplicate axes; add and use
a shared axis-validation helper (e.g., fn validate_axes(&self, axes:
Option<&[i32]>) -> Result<Vec<i32>>) that: resolves negative axes to positive by
adding ndim, checks each axis is within 0..ndim-1, removes duplicates (and
optionally sorts), and returns a Vec<i32> or an Err with a clear message; update
sum to call validate_axes(self, axes) and pass the returned Vec's pointer/len to
sys::mlx_array_sum (and reuse the same helper in other axis-based reductions) so
invalid axes are caught in Rust before making the FFI call.
In `@crates/mlx-core/src/array/shape.rs`:
- Around line 162-168: The stack function currently calls sys::mlx_array_stack
with possibly zero inputs which can trigger MLX errors; add an early validation
in stack (before building handles) that returns an appropriate error (or creates
an empty/zero-length MxArray) when arrays.is_empty(), mirroring the pattern used
in concatenate_many, then only call sys::mlx_array_stack when arrays.len() > 0
and pass result into MxArray::from_handle; ensure axis.unwrap_or(0) behavior
remains the same and use the same error type/format used elsewhere for
empty-array guards.
- Around line 195-226: The split method currently casts indices_or_sections to
usize before validating it, allowing non‑positive or zero values to produce huge
allocations; update MxArray::split to first check that indices_or_sections > 0
(and return an Err with a clear Status if not) before converting to usize and
allocating handles, and use that validated usize (num_splits) when calling
mlx_array_split_multi and when creating the handles Vec and iterating results;
reference the split method, indices_or_sections, num_splits, handles and the
call to sys::mlx_array_split_multi when making this change.
- Around line 51-62: The slice method currently only checks starts/stops
equality but must also ensure their length matches the array dimensionality;
before calling sys::mlx_array_slice, validate that starts.len() ==
self.shape().len() (or self.ndim() if available) and return an
Error::from_reason describing the mismatch if not, so you never pass incorrect
lengths into the FFI (update the early-return check in pub fn slice(&self,
starts: &[i64], stops: &[i64]) to include this dimension check and keep the
subsequent call to sys::mlx_array_slice and MxArray::from_handle unchanged).
- Around line 170-187: The pad implementation must validate that the provided
pad_width applies to every array dimension: check that pad_width.len() is even
and that pad_width.len() / 2 equals self.ndim(), returning an Err if not; update
the pad function (referencing pad, pad_width, self.ndim(), sys::mlx_array_pad,
and MxArray::from_handle) to perform this validation before calling
sys::mlx_array_pad and only proceed to call MxArray::from_handle when the
dimension check passes.
- Around line 228-262: The method split_at_indices is not exported to JS because
it lacks the #[napi] attribute; add the #[napi] annotation immediately above the
pub fn split_at_indices(&self, indices: &[i32], axis: i32) ->
Result<Vec<MxArray>> declaration so it matches the other exported array ops in
shape.rs, then run a build/test to ensure the napi export compiles correctly.
In `@crates/mlx-sys/src/mlx.cpp`:
- Around line 424-432: Wrap the extern "C" function mlx_array_logsumexp in a
try/catch exception barrier: put the existing body (reinterpret_cast of handle,
call to logsumexp, and return new array) inside a try block, and add a
catch(...) that writes an error message prefixed with "[MLX]" to stderr and
returns nullptr (since mlx_array_logsumexp returns a pointer). Ensure you
reference the function mlx_array_logsumexp and use the same pointer-return
behavior (reinterpret_cast<mlx_array*>) on success while returning nullptr on
any exception to prevent C++ exceptions from crossing the Rust FFI boundary.
Negative i32 cast to usize wraps to ~18 quintillion, causing immediate OOM on vec allocation before FFI is reached. Add early return for <= 0. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- reduction.rs: Add validate_axes() helper, validate axes bounds in sum/mean/max/min/prod/var/std/logsumexp before FFI calls - shape.rs: Validate slice dimensions match array ndim - shape.rs: Guard stack() against empty input (matching concatenate_many) - shape.rs: Validate pad_width dimensions match array ndim - shape.rs: Remove unused split_at_indices method (zero callers) - lib.rs/mlx.cpp: Remove split_at_indices FFI binding and C++ bridge Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/array/reduction.rs`:
- Around line 63-75: The argmax and argmin methods currently call the FFI
without validating the provided axis; reuse the existing validate_axes helper to
check bounds and normalize the axis before calling
sys::mlx_array_argmax/sys::mlx_array_argmin. Specifically, call validate_axes
with the array's shape/ndim and the single-axis slice (e.g., &[axis]) from
inside argmax and argmin, propagate any validation error, extract the validated
axis (the first element) and pass that normalized axis into the unsafe
sys::mlx_array_argmax/sys::mlx_array_argmin call while keeping the existing
keepdims handling and error propagation to MxArray::from_handle.
- Around line 191-200: The cumsum and cumprod methods call the FFI without
validating the provided axis, so add the same axis bounds check used elsewhere:
retrieve the array dimensionality (e.g., via self.ndim or the existing
shape/ndim accessor on MxArray), normalize negative axes, and ensure 0 <= axis <
ndim before calling unsafe sys::mlx_array_cumsum / sys::mlx_array_cumprod; if
the axis is out of range return an Err with an appropriate message instead of
invoking MxArray::from_handle on an invalid handle. Ensure you use the same
validation/messaging pattern used by other reduction methods to keep behavior
consistent.
🧹 Nitpick comments (2)
crates/mlx-core/src/array/shape.rs (2)
196-204: Silent f64 → f32 truncation ofconstant_value.The public API accepts
f64but Line 201 casts it tof32for the FFI call. This silently loses precision for values that don't round-trip through f32 (e.g., very small deltas, large integers > 2²⁴). Consider either:
- Changing the parameter type to
f32so the contract is explicit, or- Documenting that the value is internally truncated to f32.
This is minor since pad constants are typically simple values (0.0, etc.), but the mismatch between the declared and actual precision could surprise callers.
Option A: Make the public API honest about precision
#[napi] - pub fn pad(&self, pad_width: &[i32], constant_value: f64) -> Result<MxArray> { + pub fn pad(&self, pad_width: &[i32], constant_value: f32) -> Result<MxArray> { ... constant_value as f32, + constant_value,
109-127:slice_assign_axis_inplace: unchecked FFI result.The unsafe FFI call at Lines 117–123 returns no status and the method unconditionally returns
Ok(()). If the underlying MLX call fails (e.g., shape mismatch betweenselfandupdate), the error is swallowed. This is acceptable if the C layer logs to stderr per the project convention, but worth noting that callers won't see Rust-level errors from this path.
Reuse existing validate_axes() helper for single-axis methods to prevent uncaught C++ exceptions from crossing the FFI boundary on invalid axes. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Split the monolithic mod.rs into 8 focused submodules while preserving the existing public API. Each submodule contains a separate `impl MxArray` block with related methods, improving navigability and maintainability. New submodules: - creation.rs: array constructors (from_*, zeros, ones, full, linspace, eye, arange) - ops.rs: arithmetic, math, trig, NaN/Inf checks - reduction.rs: sum, mean, max, min, argmax, var, std, logsumexp, cumsum, cumprod - shape.rs: reshape, transpose, slice, concatenate, split, squeeze, pad, sort, stack - comparison.rs: equal, not_equal, less, greater, logical_and/or/not, where_ - data.rs: eval, shape, dtype, size, to_float32/int32/uint32, item_at_*, copy, astype - random.rs: random_uniform, random_normal, random_bernoulli, randint, categorical - memory.rs: free functions for cache/memory management - tests.rs: all #[cfg(test)] content (~1,565 lines) mod.rs reduced from 3,150 to 105 lines (struct def, DType, module decls, re-exports). All 715 Rust tests and 457 TypeScript tests pass unchanged. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Mostly a structural refactor, but it touches a large API surface and changes error/validation behavior for array creation, reductions, and shape ops, which could affect callers relying on previous lax validation. > > **Overview** > Refactors `crates/mlx-core/src/array/mod.rs` by splitting the large `MxArray` API surface into focused submodules (`creation`, `ops`, `reduction`, `shape`, `comparison`, `data`, `random`, `memory`) and moving the test suite into `tests.rs`, while keeping the public exports intact. > > Adds extra input validation at the Rust boundary to avoid unsafe FFI calls: constructors now check `data.len()` matches `shape`, reductions validate axes (including negative normalization), and shape ops validate dimension counts for `slice`, `pad`, `stack`, and `split`. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 2c02e48. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Major expansion of MxArray: element-wise comparisons, logical ops, conditional selection, broad math/arithmetic/linear-algebra ops, reductions, shape/tensor manipulation, random generators, many array constructors, data introspection/conversion, sync/async evaluation, and memory management/safety helpers. * **Tests** * Extensive test suite covering creation, arithmetic, comparisons, reductions, shape/indexing, RNG, memory, evaluation, and numerous edge cases. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
… iterative FD-bounded model walk Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced two Important edge-case defects in the two dashboard #15 fixes. Both verified via control-flow analysis before fixing. - A (models.ts isDownloaderOwned): the ownership marker was read with readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an external directory carrying a valid .mlx-download-complete.json was reported downloader-owned — slipping a foreign install past the no-follow occupancy preflight (a wasted overwrite, or a false "done" through the link). R15 #2 hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL directory before reading the marker, so ANY symlink/non-directory (dangling OR live-into-a-marked-dir) is foreign at all three ownership call sites. - B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a child while the parent Dir handle was still open, holding one fd per level; a deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child opendirSync, which was swallowed with truncated=false — a silent false-complete undercount. Rewrote the walk as an explicit worklist of directory paths: each handle is closeSync'd before any child is opened (at most one fd ever live), and opendirSync/readSync failures now set truncated=true (a lower bound) instead of a silent return. Budget, no-follow symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary are preserved. Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native (#4/#5) and api.ts (#3) unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
…weep, no-follow reap, no-follow deferred walk Fix-delta review of the review-#16 fixes surfaced two more symlink-safety defects adjacent to those fixes. Both verified via control-flow analysis. - Finding 1 (download.ts, data-loss): processJob ran sweepStaging BEFORE the no-follow ownership preflight, and the sweep's dead-owner backup reap decided via isModelInstalled(finalDir), which FOLLOWS symlinks. A live finalDir symlink into an external complete marked model therefore made the sweep permanently delete a recoverable rollback backup before the preflight could reject the symlink. Fixed two ways: (a) hoisted the no-follow ownership preflight to the top of the try body, before assertRealDirOrAbsent / mkdir / sweepStaging, so a foreign finalDir is refused before any recovery work; and (b) hardened the reap site to classify finalDir no-follow — reap only a proven owned-complete real directory, restore only when finalDir is absent, otherwise (foreign symlink / unowned / incomplete-owned) retain the backup untouched (this also closes the job.overwrite=true path that bypasses the preflight). - Finding 2 (models.ts walkDirStats): the iterative walker lstat'd a popped path for the dev:ino guard but never rejected a non-directory before opendirSync, which follows symlinks — so a queued real directory swapped to a symlink between enqueue and pop was followed into its external target. Added `if (!self.isDirectory()) continue;` after the lstat. No regression: discoverLocalModels already filters symlink roots, so every walk root is a real directory. Gate: typecheck 0; dashboard 200/200 (×2); lint 0. Dashboard-only — native and api.ts unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
… iterative FD-bounded model walk Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced two Important edge-case defects in the two dashboard #15 fixes. Both verified via control-flow analysis before fixing. - A (models.ts isDownloaderOwned): the ownership marker was read with readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an external directory carrying a valid .mlx-download-complete.json was reported downloader-owned — slipping a foreign install past the no-follow occupancy preflight (a wasted overwrite, or a false "done" through the link). R15 #2 hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL directory before reading the marker, so ANY symlink/non-directory (dangling OR live-into-a-marked-dir) is foreign at all three ownership call sites. - B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a child while the parent Dir handle was still open, holding one fd per level; a deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child opendirSync, which was swallowed with truncated=false — a silent false-complete undercount. Rewrote the walk as an explicit worklist of directory paths: each handle is closeSync'd before any child is opened (at most one fd ever live), and opendirSync/readSync failures now set truncated=true (a lower bound) instead of a silent return. Budget, no-follow symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary are preserved. Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native (#4/#5) and api.ts (#3) unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
…weep, no-follow reap, no-follow deferred walk Fix-delta review of the review-#16 fixes surfaced two more symlink-safety defects adjacent to those fixes. Both verified via control-flow analysis. - Finding 1 (download.ts, data-loss): processJob ran sweepStaging BEFORE the no-follow ownership preflight, and the sweep's dead-owner backup reap decided via isModelInstalled(finalDir), which FOLLOWS symlinks. A live finalDir symlink into an external complete marked model therefore made the sweep permanently delete a recoverable rollback backup before the preflight could reject the symlink. Fixed two ways: (a) hoisted the no-follow ownership preflight to the top of the try body, before assertRealDirOrAbsent / mkdir / sweepStaging, so a foreign finalDir is refused before any recovery work; and (b) hardened the reap site to classify finalDir no-follow — reap only a proven owned-complete real directory, restore only when finalDir is absent, otherwise (foreign symlink / unowned / incomplete-owned) retain the backup untouched (this also closes the job.overwrite=true path that bypasses the preflight). - Finding 2 (models.ts walkDirStats): the iterative walker lstat'd a popped path for the dev:ino guard but never rejected a non-directory before opendirSync, which follows symlinks — so a queued real directory swapped to a symlink between enqueue and pop was followed into its external target. Added `if (!self.isDirectory()) continue;` after the lstat. No regression: discoverLocalModels already filters symlink roots, so every walk root is a real directory. Gate: typecheck 0; dashboard 200/200 (×2); lint 0. Dashboard-only — native and api.ts unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
… iterative FD-bounded model walk Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced two Important edge-case defects in the two dashboard #15 fixes. Both verified via control-flow analysis before fixing. - A (models.ts isDownloaderOwned): the ownership marker was read with readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an external directory carrying a valid .mlx-download-complete.json was reported downloader-owned — slipping a foreign install past the no-follow occupancy preflight (a wasted overwrite, or a false "done" through the link). R15 #2 hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL directory before reading the marker, so ANY symlink/non-directory (dangling OR live-into-a-marked-dir) is foreign at all three ownership call sites. - B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a child while the parent Dir handle was still open, holding one fd per level; a deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child opendirSync, which was swallowed with truncated=false — a silent false-complete undercount. Rewrote the walk as an explicit worklist of directory paths: each handle is closeSync'd before any child is opened (at most one fd ever live), and opendirSync/readSync failures now set truncated=true (a lower bound) instead of a silent return. Budget, no-follow symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary are preserved. Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native (#4/#5) and api.ts (#3) unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
…weep, no-follow reap, no-follow deferred walk Fix-delta review of the review-#16 fixes surfaced two more symlink-safety defects adjacent to those fixes. Both verified via control-flow analysis. - Finding 1 (download.ts, data-loss): processJob ran sweepStaging BEFORE the no-follow ownership preflight, and the sweep's dead-owner backup reap decided via isModelInstalled(finalDir), which FOLLOWS symlinks. A live finalDir symlink into an external complete marked model therefore made the sweep permanently delete a recoverable rollback backup before the preflight could reject the symlink. Fixed two ways: (a) hoisted the no-follow ownership preflight to the top of the try body, before assertRealDirOrAbsent / mkdir / sweepStaging, so a foreign finalDir is refused before any recovery work; and (b) hardened the reap site to classify finalDir no-follow — reap only a proven owned-complete real directory, restore only when finalDir is absent, otherwise (foreign symlink / unowned / incomplete-owned) retain the backup untouched (this also closes the job.overwrite=true path that bypasses the preflight). - Finding 2 (models.ts walkDirStats): the iterative walker lstat'd a popped path for the dev:ino guard but never rejected a non-directory before opendirSync, which follows symlinks — so a queued real directory swapped to a symlink between enqueue and pop was followed into its external target. Added `if (!self.isDirectory()) continue;` after the lstat. No regression: discoverLocalModels already filters symlink roots, so every walk root is a real directory. Gate: typecheck 0; dashboard 200/200 (×2); lint 0. Dashboard-only — native and api.ts unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Split the monolithic mod.rs into 8 focused submodules while preserving the existing public API. Each submodule contains a separate
impl MxArrayblock with related methods, improving navigability and maintainability.New submodules:
mod.rs reduced from 3,150 to 105 lines (struct def, DType, module decls, re-exports). All 715 Rust tests and 457 TypeScript tests pass unchanged.
Note
Medium Risk
Mostly a structural refactor, but it touches a large API surface and changes error/validation behavior for array creation, reductions, and shape ops, which could affect callers relying on previous lax validation.
Overview
Refactors
crates/mlx-core/src/array/mod.rsby splitting the largeMxArrayAPI surface into focused submodules (creation,ops,reduction,shape,comparison,data,random,memory) and moving the test suite intotests.rs, while keeping the public exports intact.Adds extra input validation at the Rust boundary to avoid unsafe FFI calls: constructors now check
data.len()matchesshape, reductions validate axes (including negative normalization), and shape ops validate dimension counts forslice,pad,stack, andsplit.Written by Cursor Bugbot for commit 2c02e48. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
New Features
Tests