Skip to content

Validate trace input ids match trace inputs in import_function - #4790

Merged
zcbenz merged 2 commits into
ml-explore:mainfrom
turingH:fix-mlxfn-input-count-mismatch
Nov 2, 2026
Merged

zcbenz merged 2 commits into
ml-explore:mainfrom
turingH:fix-mlxfn-input-count-mismatch

Conversation

@turingH

@turingH turingH commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Summary

The .mlxfn format serializes trace_input_ids and trace_inputs as two
parallel arrays. On import, the code never checks that the two lengths
match: it loops over trace_inputs.size() and directly indexes
trace_input_ids[i].

With trace_input_ids = [] and trace_inputs = [array], the very first
iteration accesses trace_input_ids[0] on an empty vector. This happens
during the import itself — the imported function never has to be called,
and no particular model or op parameters are involved.

Root cause

The relevant code is in the import path of mlx/export.cpp:

auto trace_input_ids = deserialize<std::vector<uint64_t>>(is);
auto trace_inputs = deserialize<std::vector<array>>(is);
for (int i = 0; i < trace_inputs.size(); ++i) {
  array_map.emplace(trace_input_ids[i], trace_inputs[i]);
}

When exporting a well-formed file the two arrays naturally have the same
length; when importing a third-party file that invariant cannot be assumed
— it must be validated before the first index. The bug triggers while
untrusted deserialized data is used to build internal object relationships,
before the imported graph is ever executed.

Fix

Validate the two counts at the deserialization boundary, before the first
lookup, so a corrupt file raises std::runtime_error (a catchable
exception from Python) instead of crashing the process:

if (trace_input_ids.size() != trace_inputs.size()) {
  std::ostringstream msg;
  msg << "[import_function] File is corrupted: expected "
      << trace_inputs.size() << " trace input ids but got "
      << trace_input_ids.size();
  throw std::runtime_error(msg.str());
}

Reproducing via the test added in this PR

The new test case test import rejects mismatched trace input arrays
builds the malformed file in-test from the serialized fields directly, so
no external file is needed:

// fewer ids than inputs: the import loop indexes past the end of the
// ids vector (with zero ids, through a null data pointer)
auto path = write_file("evil_input_ids_0.mlxfn", 0, 1);
CHECK_THROWS_AS(import_function(path), std::runtime_error);

// more ids than inputs: equally corrupt, must be rejected rather than
// silently accepted
path = write_file("evil_input_ids_2.mlxfn", 2, 1);
CHECK_THROWS_AS(import_function(path), std::runtime_error);

Running just this case on main (without the fix) crashes:

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DMLX_BUILD_METAL=OFF -DMLX_BUILD_TESTS=ON
cmake --build build --target tests -j8
./build/tests/tests --test-case="test import rejects mismatched trace input arrays"
tests/export_import_tests.cpp:193: FATAL ERROR: test case CRASHED:
SIGSEGV - Segmentation violation signal

Under ASan the crash site is exact:

cmake -S . -B build-asan -DCMAKE_BUILD_TYPE=Debug -DMLX_BUILD_METAL=OFF -DMLX_BUILD_CPU=ON \
  -DMLX_BUILD_TESTS=ON -DMLX_BUILD_EXAMPLES=OFF -DMLX_BUILD_PYTHON_BINDINGS=OFF \
  -DCMAKE_C_FLAGS="-fsanitize=address -fno-omit-frame-pointer -g" \
  -DCMAKE_CXX_FLAGS="-fsanitize=address -fno-omit-frame-pointer -g" \
  -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address"
cmake --build build-asan --target tests -j8
./build-asan/tests/tests --test-case="test import rejects mismatched trace input arrays"
ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000
    #0 std::__1::__unordered_map_hasher<unsigned long long, ...>::operator()(
       unsigned long long const&) const                     unordered_map:658
    #1 ...__emplace_unique<unsigned long long&, mlx::core::array&>(
       unsigned long long&, mlx::core::array&)              __hash_table:779
    #7 mlx::core::ImportedFunction::ImportedFunction(...)   export.cpp
   #10 the new test case                                    export_import_tests.cpp:244

The top frames are array_map.emplace(trace_input_ids[i], trace_inputs[i]):
an empty ids vector never allocated (the deserializer's reserve(0) is a
no-op), so trace_input_ids[0] is a reference through a null data pointer
and hashing the key reads from address 0. The crash happens while
deserialization builds the id-to-array map, before any of the imported
graph runs.

Behavior after the fix

The same commands pass with this PR: the malformed file is rejected at the
import boundary and existing export/import tests are unaffected.

Build Before (main) After (this PR)
Release test case crashes with SIGSEGV new case passes, 8/8 pass
ASan SEGV on unknown address 0x0 8/8 pass, clean run

@turingH
turingH marked this pull request as ready for review October 29, 2026 06:14
turingH and others added 2 commits November 2, 2026 09:32
The .mlxfn format serializes trace input ids and trace inputs as two
parallel arrays. The importer loops over trace_inputs and indexes
trace_input_ids with the same counter and no count check, so a crafted
file that records fewer ids than inputs reads past the end of the ids
vector during import; with zero recorded ids the empty vector never
allocates and hashing the key dereferences its null data pointer,
killing the process with SIGSEGV before the imported function is ever
called.

Check the two counts at the deserialization boundary and throw
std::runtime_error on mismatch so a corrupt file is rejected cleanly
instead of crashing.
@zcbenz
zcbenz force-pushed the fix-mlxfn-input-count-mismatch branch from 55532b0 to 9e96434 Compare November 2, 2026 17:33
@zcbenz
zcbenz merged commit 55626cb into ml-explore:main Nov 2, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants